General Information - Bitrix Site Manager - Content Management & Portal Solutions

Bitrix Site Manager Send feedback on this topic

General Information

The Bitrix Site Manager is the technological base for building and managing web sites. It offers efficient way to develop, support and maintain your web projects.

The Bitrix Site Manager can be used by both corporate customers and individual web developers as the base to develop new sites from scratch and manage the existing sites.

The Bitrix Site Manager allows to build as many sites as you need, using a single copy (license) of the product. This means that you have to keep a single copy of the system and database on the server.

What is more, with the Bitrix Site Manager you can:

  • manage the structure and content of your site;
  • publish news, press releases and other of frequently updated information;
  • manage advertising shows on your site;
  • create forums;
  • create mailing lists and send messages to your subscribers;
  • keep visitor statistics;
  • control advertising campaigns;
  • perform many other operations in managing your web project.

The product will minimize web site maintenance costs owing to simple process of management of static and dynamic information. You will not need any web design or programming expert service in maintaining and managing your site. A web site built with the Bitrix Site Manager can be managed by an office employee, i.e. a common PC user without any programming, HTML layout or web design skills.

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


System requirements - Bitrix Site Manager - Content Management & Portal Solutions

System requirements

The Bitrix Site Manager is developed with the PHP4 programming language. The product runs smoothly on any UNIX and Windows platform.

Minimum system requirements

  • PHP 4.1.2
  • Apache 1.3 or MS IIS 5.0 or higher
  • MySQL 3.35.55 or higher either Oracle 9 or higher

For use with MS IIS, PHP must be installed as an ISAPI.

The system expects MySQL or Oracle as the database engine.

The two database editions of the system provides identical features and uses the same kernel. Choice is usually stipulated by your requirements to reliability, scalability and expected load.

Bitrix Site Manager (PHP+MySQL)

The most popular and easily customizable edition. Developed with the common customer requirements in mind, it will satisfy needs of most clients. Fully functional, perfectly effective and cost-saving, this edition allow to create and deploy a site on almost any hosting that supports PHP and MySQL.

Bitrix Site Manager (PHP+Oracle)

The Oracle edition is aimed to build sites and business applications on the Internet that require ceiling reliability and scalability. This product edition can guarantee the faultless operation of the site of a large company, bank or popular Internet resource. This edition is a solid foundation for business applications, allowing to create richer relationships with clients and customers through a portal solution.

All product editions are shipped with full and unabridged source code. This allows the developer to customize and develop solutions without assistance.

If you cannot decide which edition to purchase, please contact us. Our engineers will provide you assistance and answer all your questions.

Sites developed with the Bitrix Site Manager can be viewed with any browser. The only limitation applies to HTML editor used in the administrative section. It requires Internet Explorer 5 or higher to be installed.


Support for Multiple Sites- Bitrix Site Manager - Content Management & Portal Solutions

Support for Multiple Sites

The Bitrix Site Manager features creation of unlimited number of sites with the use of a single copy (license) of the product, keeping a single installation of the system kernel and database on the server.

When building a site, you usually install the system to the root directory and then create static pages and files intended for output in different language mirrors in corresponding subdirectories of the root directory. If you create more than one site on the same server, you would have to install the system in the root directories of each site. This approach is evidently inefficient and results in absolute decentralization of project management.

The Bitrix Site Manager system had been developed taking into account requirements of companies that may need to maintain multiple sites (e.g. language mirrors or subject directories). Web design studios will also find this feature useful as it allows to neatly arrange multiple projects with the same hosting. The multiple sites concept requires substantially less resources and allows to manage all sites from the single control point.

The Bitrix Site Manager kernel allows the use of the following URL types to identify sites controlled by the system:

  • relative (/fr/, /en/) - for mirrors of a site of the same domain controlled by a single system;
  • absolute root (www.site.ru) - for different sites controlled by a single system;
  • absolute (www.site.ru/en/) - for separate mirrors and/or sites controlled by a single system.

For example, to create two sites without having to install the system in the root directories of each site, or to create two sites not distributing them to subdirectories of the root directory, you have to create two web servers (or virtual hosts) with different root folders and create symbolic links to folders /bitrix and /upload using the operation system tools.

Thus, common entities for all projects are folders /bitrix and /upload and the database. Sites are distinguished by static pages and a field Site of the database objects (news, polls etc.)

You can download the white papers on the multiple site system configuration in the PDF or Microsoft® Word format from the Bitrix documentation web page: http://www.bitrixsoft.com/sitemanager/doc.php


Additional documentation and manuals - Bitrix Site Manager - Content Management & Portal Solutions

Additional documentation and manuals

This help system is aimed at both product users and web developers who build their projects with the use of Bitrix Site Manager. Web site visitors may also find useful information in some of the help section's parts, for example Forum.

This help system, while being the comprehensive manual containing information on the system front-end and the custom web solution development with the system API, does not include some details on the system start-up and configuration. The documents summarized in the table below covers all aspects of the web server and site initial configuration in various conditions.

The range of white papers is constantly extended. Please watch the following web page for new manuals: http://www.bitrixsoft.com/sitemanager/doc.php.

Document PDF DOC ZIP
Quick Start Guide

This document depicts common guidelines that should be followed when integrating the Bitrix Site Manager into the web solution design or developing custom solutions.

 download
(270 kB) 		download
(350 kB) 		download
(300 kB)
Integration Manual

This manual provides the detailed description of the system integration in a new or existing web site.

download
(470 kB) 		download
(742 kB) 		download
(507 kB)
Multiste system configuration guide

This document is for use by system administrators who are involved in configuring the Bitrix Site Manager for use with more than one site and the server software so that they function altogether without collisions.

download
(76 kB) 		download
(88 kB) 		download
(42 kB)
Recommendations on configuring web servers

This document contains recommendations on how to customize the server software settings.

download
(86 kB) 		download
(107 kB) 		download
(47 kB)


Getting started and authorizing - Bitrix Site Manager - Content Management & Portal Solutions

Getting started and authorizing

You manage your site with the use of the administrative section. The administrative section is only accessible by authorized users with sufficient permissions granted (for example, the Administrator). Common site visitors cannot access the administrative section, even if they are properly authorized in the system.

You must authorize before you start working with the administrative section. To do so, do the following.

  1. Open URL http://www.your_site/admin/ in your browser. Your browser will redirect to http://www.your_site/bitrix/admin/. All system files of your site are stored in folder /bitrix/. This name is unique, which guarantees that no other folder with such name will ever exist on the server.
  2. Enter your login and password in the authorization form.

    If you have previously set the option Allow user to remember password in the site settings, the authorization form will show option Remember me. If you check this option, you will no longer need to authorize when you enter the administrative section.
  3. Click the Authorize button.

If the authorization procedure succeeds, you can start managing your site with the administrative section. A site public section will display the site control toolbar on the top of a page:


Logging off - Bitrix Site Manager - Content Management & Portal Solutions

Logging off

To finish the authorized session and switch to the unauthorized mode, click the Log off [image] link on the control toolbar in the public section or administrative section.


Using complex logic in filter - Bitrix Site Manager - Content Management & Portal Solutions

Using complex logic in filter

Most system forms display information in the form of report tables. To define the subset of data to be displayed in a form report table, the system provides filters. With filters, a user can provide numeric, textual or other kind of information which is used as the criteria to match against data selected from the database. If the data selected satisfies the provided criteria, it is displayed in the report. Filter is the part of the page body; it is mostly positioned on top of the form.

The following illustration shows the filter of a user web form (partially collapsed for better visibility).

Filter fields marked with ? on the right of the field allow using queries. On the picture above, the following filter fields are enabled with the query language: ID, Status ID, User ID, Visitor ID, Session ID, e-mail.

How to use queries

A query is a logic expression. For example, you want to filter a table with user data by field Name. If you type in the following text:

John & Smith

the output will contain all users having both words in their names, either partially or in full. This query is equivalent to typing these two words separated with a space: John Smith.

If you need to display all users having either John or Smith in their names, you would have to type the following query:

Brown | Smith

In case you need to use the negation, a special logical operator is provided: "~". For example:

(Brown | Smith) & ~John.

This query means to display all users having either Brown or Smith in their names, but not John.

The last query made use of round brackets. The use of brackets is stipulated by the priority of operator | which is lower than that of operator & (see table Logic Operators Priority below). On the other hand, if you do not use round brackets here, this query would mean to display all users having Brown in their names, or users having Smith in their names but not John.

Round brackets can be used to build more complex queries.

In addition to the above described operators, the system provides wildcard operators. For example, you cannot remember the name of a person but sure that the last name starts from Wil and ends with son, while the first name is either Blythe or Blithe. The following query will match these conditions: Wil%son & Bl_the. In this query, symbol % (percent sign) means zero or more symbols, and symbol _ (underscore) means any one symbol.

If you need to include any reserved symbol in the query, enclose the query phrase in single or double quotation marks. For example: "~NICK~" | '&Leon&'. Similarly, if you need to find a phrase containing space(s), enclose it in single or double quotation marks, for example: "Microsoft Internet Explorer" | 'Netscape Navigator'.

In all cases, the search is not case sensitive.

Query operators

Operator | Description
& | Logical operator and can be omitted. A query John & Smith is equivalent to John Smith.
| | Logical operator or allow searching for records containing at least one of operands.
~ | Logical operator not searches for records not containing an operand stated after the operator. Additionally, it negates expression after the operator.
( ) | Round brackets define the logical operators precedence.
% | Wildcard operator. Means zero or more symbols.
_ | Wildcard operator. Means any one symbol.

Logical operators priority

Operator | Priority
~ | 1
& | 2
| | 3


Common interface parts

In this section

  • Control toolbar
  • Function selector
  • Functions, content and structure access area
  • Main work area
  • Context bar
  • Report forms
  • Filter
  • Report tables
  • Action menu
  • Editing forms
    •

    • The interface of the Bitrix Site Manager administration control panel is logically divided in special areas thereby providing access to system functions. The interface is built using hierarchical approach: parent areas switch dependent areas to different modes. This allows to hide system functions that a user does not require at the moment, while bringing the wanted functionality to the foreground. The user interface, being managed in such way, ensures that it remains legible and not overloaded.

    The user interface includes the following main parts.

    Control toolbar

    The administration control toolbar contains general commands that a user may need to manage a site.

    Command | Description
 | Opens the site public section (the section accessible by visitors). Hold the Shift key down to open the public section in a new window.
 | Opens the main page of the administration section (Control Panel).
 | Adds the current page to the list of favorites.
 | Shows settings of the currently active module. For example, if you have one of the Site Explorer module forms open, this button shows settings of the Site Explorer module.
 | Displays help topic about the current form, in a new window.
 | Switches to a special form where you can download and install latest system updates.
 | Selects the desired language of the control panel.
 | Ends an authorised administration session.

    Function selector

    This panel is used to choose an isolated set of functions or entities relevant to a specific functional part of the system. Depending on whether a specific module is installed or not, the set of selector functions may vary.

    The Content set offers tools which one may require to manage information blocks, site structure (files and folders), or set up and control the document workflow.

    The Services function set depends on the presence of modules in the system. The full set of functions allows to manage polls, web forms, advertisement, technical support system, forums and mail system.

    The Web Analytics section is entirely dedicated to functions responsible for collecting, processing and displaying the site statistics. This section is only available if the Statistics module is installed.

    The Settings section contains tools which can be used to manage users, currencies, templates, obtain system updates, or adjust other parameters of the system and sites.

    Functions, content and structure access area

    The menu of this panel depends on the function set selected in the function selector. For example, selecting the Content set displays the following menu:

    By selecting items in the tree menu, you can directly access the corresponding functions. This causes the work area (4) to offer user interface for using and manipulating these functions.

    Main work area

    This is the main interface part in which you perform most operations: view entities composing the site content (e.g. information block, banners etc.); add content; create or delete files and folders; customize menu etc. The system offers two main types of user interface forms to fulfil these operations:

    • report forms. Report forms are used to display (and view) elements in tables, or, is some special cases (statistics forms) - in the form of graphs and diagrams;
    • editing forms. You use these forms to add or edit the content entities, as well as customise both system and per-module settings.

    The main work area forms have many common elements. You are strongly advised to learn their functions - this will help you much in your work.

    Context bar

    You will find context bars on both report and editing forms. If an active form allows any action to be performed on the displayed elements, the context bar can be found below the filter. For example, the Catalog: Information Blocks report form displays the following context bar:

    The first button adds a new information block, while the Excel button exports the list to the Microsoft Excel format. The Settings button opens a dialog box in which you can customise the table columns, set the default sort order etc.

    Report forms

    Report forms are opened whenever you select an item in the tree menu of the Functions, content and structure access area. Report forms display the essential information about entities included in the report. For example, if you select the Banners item in the Advertising section, the system returns with a thorough report about all existing banners:

    Click on image to enlarge

    Click on image to enlarge

    The following sections describe interface parts common to all report forms.

    Filter

    A filter, in its core, is essentially a means to search and select data to be displayed in tables of the report forms. By providing search criteria in the filter, you can find and display only the required information (usually a selection of database records).

    A typical filter looks like follows:

    The Show filter button displays the filter and all its criteria. Clicking the Hide filter button minimises the filter leaving only the filter toolbar and (optionally) the default condition marked with bold typeface. The More filters button opens a pop-up menu in which you can choose individual search conditions to be included in the filter.

    Filter fields having a question mark on the side (?) allow using complex logic in filter.

    Report tables

    The system uses tables to group and display information. Despite the fact that there are many different types of tables in the system, all they have common fields.

    Checkbox column

    Checkbox columns are used to select one or more elements for applying the desired action to them. Check the box in the table head to select all elements in the table.

    You can perform operations on the selected elements by choosing the desired command in the action toolbar below table:

    Please pay special attention to the Quick edit command. It allows to modify the most important, frequently used properties of the selected elements simultaneously, without leaving the current report form (i.e. without having to open an editing form).

    For example, you can mark information blocks Phones and Accessories in the Catalog: Information Blocks form:

    After you click the Quick edit button, editable values of the selected elements will be displayed as input fields:

    After you have completed editing, click the Save button to apply changes.

    Action menu

    The Action menu column ( [image] ) contains buttons [image], each of which, being clicked, opens a context menu containing actions available to be performed on a table element. For example, elements of the Catalog: Information Blocks form table offer the following actions:

    Editing forms

    These forms are used to modify elements comprising the site content, or edit parameters of the system. For example, selecting the Edit command of the information block action menu opens an information block editing form.

    Since site elements (or module settings forms) may include a lot of editable properties, some editing forms are implemented using the so-called property sheets. With their advent, property sheets are widely used to enhance user interface, and it's no wonder because property sheets allow to divide numerous properties in logical groups (pages) thus making user interface easy to handle and comprehensive. Usually, properties are grouped in such a way that first property pages in a sheet contain the most frequently used properties, while other pages hold all other parameters.

    The figure below illustrates a part of the information block property sheet form.

    For short, this help system uses the term tab as a synonym of a property page.


Overview - Bitrix Site Manager - Content Management & Portal Solutions

Overview

The Site Explorer empowers web developer or other person responsible for site content management with a set of features allowing to create new pages, sections (folders), copy, move and delete files and folders, edit web site pages and perform other essential operations.

You do not have to possess any knowledge in web programming or HTML design. Using control toolbar commands, you can easily manage the structure of your site and menus, create and edit pages, assign access permissions.


Site Explorer - Bitrix Site Manager - Content Management & Portal Solutions

Site Explorer

In this section

  • Context bar
  • Site explorer fields
  • File and folder operations
  • Editing a section menu
    •

    The Site Explorer (Content -> Site Explorer) is a part of the system that provides a graphical user interface for accessing the site and file system objects. The Site Explorer's structure is similar to that of right pane of Windows Explorer and shows a list of files and folders. On the top level of the folder hierarchy are sites controlled by the system.

    The structure of the top level of a site is generally as shown on the following figure.

    Click on image to enlarge

    Click on image to enlarge

    Usually, a web site is divided into sections (displayed as folders) containing files grouped by subject. The folders provide structured storage of information: web pages, templates, images etc.

    The table displays the following information: file or folder name, size, date of last modification, access permission level. To browse a folder, click a link with the folder name. By double-clicking the file row, you can open the file for editing.

    Context bar

    The Site Explorer menu is used to manage the folder contents and customize its settings.

    Button | Description
New folder | Creates a new folder in the current folder.
New file | Creates a new file in the current folder.
Upload file | Uploads a file into the current folder from a local machine.
Add menu | Creates and adds a menu to the current section.
Folder properties | Allows to view and edit the current folder properties (modify the section name; edit the section access permissions and properties).
Show access permissions for | Shows a menu in which you can select a user group whose access permissions for files and folders are to be displayed in the Bitrix access permissions column. See also: Access permissions.
Path | To open a certain site folder, specify a path to the folder and click OK.
Excel | Exports data from the table to the MS Excel format.

    Site explorer fields

    Column | Description
    Checkbox column | Selects files and folders to which the desired actions are to be applied.
    Action menu
             Contains available actions on folders and files.

    Actions on folders:
    • Open - opens a folder in the Site Explorer;
    • Folder properties - opens the folder properties form;
    • Delete - deletes the selected folder.
    Actions on files:
    • Edit as text - edits the file in the text format;
    • Edit as HTML - edits the file in the HTML editor;
    • Edit as PHP - edits the native PHP code of the file;
    • Edit in the Workflow module - registers the file with the Workflow module and edits it in the HTML editor;
    • View file - view the file contents and its properties: size, last access and modification date;
    • Delete - deletes the file.
    Actions on menu description files:
    • Edit menu - edits the menu parameters and items;
    • Delete - deletes the file.
    Name | The folder or file name.
    Size | The file size, in bytes.
    Modified | The date and time when the file or folder was last modified.
    Type The list element type:
    • Folder;
    • File (image, archive etc.);
    • System file;
    • Text document;
    • HTML document;
    • PHP script.
    Access permissions | Access permissions to files and folders, at the operating system level.
    Bitrix access permissions | The user group access permissions to files and folders.

    File and folder operations

    You can apply various actions to files and folders in the Site Explorer to change their content, location and properties.

    To apply any action to files and/or folders, you have to select the desired files by checking the corresponding boxes in the left column of the Site Explorer table. After that, you can use the Actions field in the command bar to select and execute the required operation:

    Select the required action and click Apply.

    Action | Description
Access | Opens a form to edit the selected files and/or folders access permissions. To change access permissions, select the required permission for the user group and save changes.
Copy | Copies the selected files and/or folders to a folder specified in the destination field. You can select a folder by clicking [image] .
Move | Moves the selected files and/or folders to a folder specified in the destination field. You can select a folder by clicking button [image] .

    Editing the current section menu

    The Site Explorer shows menus of the current section as files named Menu type «XXX» (e.g., Menu type «top»). You can edit a menu by selecting the Edit menu command from the action menu.

    See also: Menu

    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


HTML Edtior - Bitrix Site Manager - Content Management & Portal Solutions

HTML Editor

In this section

  • "Editing" tab
  • HTML editor fields
  • HTML editor toolbar
  • "Properties" tab
  • "Menu" tab
  • Control buttons
  • Uploading images to the site
  • Visual components
    •

    A special software module implements simple visual HTML editor running inside your browser and allowing to edit text and insert images online. The editor functions in such a way that it alters only the page working area, thus ensuring the web site design integrity. For easier operation, the visual HTML editor form is divided into three tabs:

    • Editing;
    • Properties;
    • Menu.

    "Editing" tab

    This tab contains the visual HTML editor pane and is intended to create and edit documents. The user interface of the editor window is very ergonomic; you will find it much similar to that of Microsoft Word.

    You can format text, insert tables and images into pages etc. Appearance of your new pages will be consistent with that of the existing ones. Editor tracks your changes being the base to generate HTML code for your page. After the changes are saved, the page is updated in the site public section automatically.

    HTML editor functionality is available on any machine with Internet Explorer 5.0 or higher installed.

    HTML editor fields
    Field | Description
Template dropdown list | A template on whose basis a new page is created. For example: Standard page, Page include area or Section include area.
File name | The file name including extension, for example, news.php.
Page title | An arbitrary page title. The specified title will be displayed in the page body.
    HTML editor toolbar
    General commands
 | Switches to the fullscreen mode.
 | Cuts the selection and places it on the clipboard.
 | Copies the selection to the clipboard.
 | Inserts the clipboard contents.
 | Inserts the clipboard contents previously copied in MS Word. Strips the fragment out of redundant formatting (e.g. styles).
 | Inserts the clipboard contents as plain text.
 | Undoes 1 action.
 | Redoes 1 action.
 | Toggles the table borders visibility.
 | Inserts a table.
 | Inserts a hyperlink anchor (bookmark).
 | Inserts a hyperlink.
 | Deletes a selected hyperlink.
 | Inserts an image.
 | Switches to the visual editing mode.
 | Switches to the source code editing mode.
 | Switches to the split editing mode.
 | Quits the editor.
 | Creates a new page.
 | Opens the page property editor.
Text properties
 | Changes background colour.
 | Changes text colour.
Text formatting buttons
 | Makes the selected text bold.
 | Makes the selected text italic.
 | Applies the underline text character style to the selected text.
 | Aligns the current paragraph to the left margin of the page.
 | Centers the current paragraph in the middle of the page.
 | Aligns the current paragraph to the right margin of the page.
 | Justifies the paragraph.
 | Formats the current paragraph as a numbered list.
 | Formats the current paragraph as a bulleted list.
 | Decreases the indentation of a paragraph.
 | Increases the indentation of a paragraph.
 | Inserts a horizontal rule.
 | Removes formatting.
Styling commands
 | Contains a list of available styles (CSS). Select the style you want to apply to the selected paragraphs. It is strongly recommended to format your text using styles only for design consistency.
 | Changes the text format. For example: Heading1, Heading2, ..., Normal.
 | Changes the text font.
 | Changes the text size.
 | The site template (design) using which the page is displayed.
Properties
The Properties section contains formatting parameters of the selected text. Also it is used to display and customise visual components placed in the page body.

    "Properties" tab

    This tab is used for customising and editing the page property values and for managing the META tags, such as page keywords and description.

    Field | Description
Property | The property name.
Value | Field for specifying the property value.

    Note!
     The More button adds an empty row where you can create a new property of the current page (this property is used only for the current page). When creating a property, its mnemonic code should be specified in the Property field. Only Roman letters can be used here.

    "Menu" tab

    This tab allows to add an item linked to the created page to current section menu (i.e. the section in which the page is created).

    Field | Description
    Add a page to menu | Check this field if you want to add an item linked to the created page to the current site section menu.
    Menu type | Specify the menu type to which the link to the created page is to be added.
    Menu item Specify how the link to the page be added:
    • Add a new item - a new menu item will be created;
    • Link to an existing item - an existing menu item will be linked to the page.
    The value of this field determines the values of the below fields.
    "Add a new item"
    Name of a new item | The name of a new menu item linked to the created page.
    Insert before the item | Here you can specify the location of the menu item. For example, if the field value is "Last item", the created item will be the last one in the section menu.
    "Link to an existing item"
    Item | Selects the existing menu item to which the link to the page will be added.

    Control buttons

    Button | Description
Save | Saves the created page.
Apply | Saves the page parameters. Editing continues.
Cancel | Cancels changes performed.

    Uploading images to the site

    With the HTML editor, you can easily upload images from a local disk and add them to your pages. The image uploading procedure is very simple:

    1. Place the caret to the image insertion position and click [image] on the toolbar.
    2. Click [image] to open the image upload form.
    3. Select folder in which the image will be stored (usually images).
    4. In the Upload file field, specify the file path on your local machine. Select a file you wish to upload by clicking Browse.
    5. Check Overwrite if the destination folder already contains a file with the same name and if you want to replace it.
    6. Click Upload. The file selected will be uploaded.

    7. Select the uploaded file in the Site Explorer and click Open.

    8. If required, specify additional image parameters: width, height, border width etc.
    9. Click Save.

    Visual components

    Visual components are the logically finished program code performing operations on the data of system modules. With their help you can publish news, display photo gallery elements or catalogue items etc. Virtually any source code can be published as a component.

    For easier adding components to a page, a special interface is developed on the base of the HTML editor. When editing a page, you can select a desired component from the list and drop it into the page body.

    Beside code, components offer a set of parameters determining the component behaviour.

    The main peculiarity of a component is that they allow to manage these parameters via the visual interface. After a component is inserted in the working area, the component properties bar will be displayed at the bottom of the page. For example: the toolbar of the "All news" component properties looks like the following:

    If the property inspector is not visible, select a component - this will unhide it. After the required properties have been set, the page is ready to go.

    2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Menu - Bitrix Site Manager - Content Management & Portal Solutions

Menu

In this section

  • Menu types
  • Menu editing modes
    •

    The use of menu simplifies navigation through the site sections and pages. Bitrix Site Manager allows you to take full control over the site menu:

    • you can create menu items linked to the site sections and pages;
    • change text and links of menu items;
    • assign display conditions to menu items and control their visual aspect;
    • delete menu items.

    Bitrix Site Manager does not place restrictions on the use of the site menu. Number and types of menus used on the site pages are defined by the site design template. The appearance of the public section menu is defined by the menu template.

    Menu types

    A menu type is a conventional menu name. Menu types are used to display menus on a site page (i.e. the site template stipulates the menu display area; then, a menu of the required type is included into this area). Also the type is used as a prefix specifying files related to this menu, and for building the site map.

    The system expects the following menu types (menu disposition):

    • top menu; used to navigate through the site sections;
    • left menu, used to navigate through the site subsections and section pages.

      Note!
      By default, the menu of the parent section is used in all subsections of a site unless these don't have their own menu.

      For example, the top menu relates to the whole site and contains links to the topmost divisions of the site structure. Therefore, the main menu is created only for the root folder and is displayed in all site sections.

      The left menu concerns site sections and contains links to pages and subsections of the main sections. Therefore, generally, the left menu is created for each site section individually.

      A site can also display other menu types, for example, the bottom menu. The menu types used on the site are specified in the Site Explorer module settings.

      Menu editing modes

      You can customise menu settings either from the public section or from the Site Explorer.

      • To manage menus from the public section, you have to enable the display of include areas by clicking [image] on the administration toolbar, then click [image] located in the upper right corner of the menu or in the menu location area.
      • To create a menu in the Site Explorer, click Add menu. To edit the section menu, open the section folder and click a link with name of the required menu, for example, Menu type "top".

      The system provides for the two menu editing modes.

      • Simple mode. The simple editing mode allows to quickly add new menu items by specifying a link to the target page and the order of menu items in the public section.
      • Extended mode. The extended mode allows to specify extra links to highlight, specify conditions and parameters.

      You can switch between modes by clicking the Simple mode/Extended mode button in the editing page menu.


Editing menu

In this section

  • Context bar
  • Simple mode
  • Extended mode
  • Control buttons
    •

    This page is designed to create a new menu and edit the parameters of existing ones.

    Context bar

    Button | Description
Folder | Shows a folder currently opened in the Site Explorer.
Extended/ Simple mode | Switches between editing modes.
Edit as file | Switches to the menu source code editing mode. The button is displayed when editing the existing menu only.
Delete menu | Deletes the menu being edited.

    Menu editing. Simple mode

    This table is the user interface used to create menu items in simple mode. To add new items, fill in the fields and click Save.

    Field | Description
Menu type | The type of the menu to be created.
Menu items
Name | The menu item name. It is the name to be displayed in the public section menu.
Link | The hyperlink to a page or section which will be opened when a visitor selects the item.
Sorting | Specifies the menu item sort weight. The less is the number, the higher is the item in menu.
Delete | Deletes the menu item. Check this field and click Save or Apply to delete the menu item.

    Menu editing. Extended mode

    In addition to the simple mode, the advanced mode allows changing the following parameters.

    Field | Description
    Menu type | The type of the menu to be created.
    Menu template | If a menu requires a special template for display, you can specify the path to a template here.
    Menu items
    Name | The menu item name. It is the name to be displayed in the public section menu.
    Link | The hyperlink to a page or section which will be opened when a visitor selects the item.
    Sorting | Specifies the menu item sort weight. The less is the number, the higher is the item in menu.
    Delete | Deletes the menu item. Check this field and click Save or Apply to delete the menu item.
    Additional links to highlight Specifies the site pages which, when opened, will cause the menu item to be highlighted.

    For example, the menu item Siemens is linked to a page containing a list of phones (/catalog/phone/section.php). If you want the Siemens menu item to highlight when a user views the phone details, specify the detailed information page in this field (for example, /catalog/phone/element.php).

    All paths should be specified relative the site root. If all these pages are stored in one folder, specify the path to this folder relatively to the root (for example, /catalog/phone/element.php).
    Condition type Specifies the condition type. When the condition is met, the menu item is displayed to the visitors:
      • For file or folder: page or the current section subsection in which this menu item will be displayed;
      • For user group: user groups for which this menu item is displayed;
      • Time period: the date and time period within which the menu item is shown to site visitors;
      • URL parameters: the page URL parameter which, if present, will cause the menu item to be displayed;
      • PHP expression: an arbitrary PHP condition. The condition must be specified as it looks inside the if() operator. When a page is built, the condition is checked for being met. If the condition is met (i.e. it is true), the menu item will be displayed to visitors.

        For example, the $USER->IsAuthorized() condition allows to check if the current user is authorised.
    Condition | Specifies the condition type. When the condition is met the created menu item is displayed.
    Parameters Specifies any parameters used when a template-based menu item is being built. The parameters are stored in an associated array $PARAMS in form of pairs "name => value". When a template-based menu is being built, the template itself may contain the condition to check the parameter, for example:

if ($PARAMS["MY_PARAM"]=="Y")
    or of a value is specified:

<a href='".$link."'
 class='".$clrtext."'
 title='".$PARAMS["ALT"]."'>".$TEXT."". $clrimg ."</a>

    The product is shipped with the special option to highlight menu items. This option is used in conjunction with the Additional links to highlight field. To separate the first menu item, type SEPARATOR in the field Name and give it a value of Y.

    Control buttons

    Button | Description
Save | Saves the current changes.
Apply | Saves the menu item parameters. Editing continues.
Cancel | Cancels current changes.


Access Permissions - Bitrix Site Manager - Content Management & Portal Solutions

Access Permissions

In this section

  • Context bar
  • Form fields
  • Control buttons
    •

    You can customise the user access permissions for the site pages and sections is accomplished via the Site Explorer tools: Content -> Site Explorer.

    The access permission table shows site users registered with the Users module. In all cases, there always are two predefined users: Everyone and Administrators.

    To change the file or folder access permissions, you have to:

    • mark the checkbox of a required file or folder in the checkbox column (you can edit permissions to more than one file or folder);
    • select Access in the action bar at the bottom of the page and click Apply.

    This will open an access permissions editing page for a file or folder (or several files or folders). All access permissions of the nested files and folders are inherited by default.

    Context bar

    Button | Description
Folder | Switches to the file currently opened in the Site Explorer.

    Form fields

    Field | Description
    Group | The site user group for whose members the access permissions are customised. You can manage users and user groups in the Users module.
    Access level Modifies the current access permission for a file or a section. You can assign the following access permissions to user groups.
    • Deny - any access to this folder is denied.
    • Read - users can view the file or folder contents.
    • Workflow - permits users to edit the file only indirectly via the Workflow module.
    • Write - permits users to create, modify and delete files.
    • Full access - permits users to modify files and manage access permissions.
    • Inherit - the selected files and folders will be given the same access permissions as the parent folder.
    Current access level | The current group access permission for a file or a section.

    Control buttons

    Button | Description
Save | Saves the current changes.
Apply | Saves the access permissions. Editing continues.
Cancel | Cancels current changes.


Creating a new folder - Bitrix Site Manager - Content Management & Portal Solutions

Creating a new folder

In this section

  • Context bar
  • Folder creation form
  • Example of the folder creation
    •

    This form opens every time you select link New folder in the Site Explorer or click [image] in the administration toolbar in the site public section. A new folder is created in the folder currently opened in the Site Explorer. For example, if you have the folder /en/about/ opened, a new folder will be created in /about/.

    Context bar

    Button | Description
Folder | Switches to a folder currently opened in the Site Explorer.

    Folder creation form

    Field | Description
Folder name | The name of a new folder. Only Roman letters can be used here.
Section name | The name of a new section as it will display in the public section navigation chain.
Add a menu item | If this option is active, a link to a created section will be added to the specified menu.
Menu | The type of menu to which the link to the created section will be added.
Item text | The menu item title. This text will be shown in the public section.
Create index page for this section | If this option is checked, the file index.php will be created in a new section. This will allow visitors open the section without having to provide the page file name. For example: http://yoursite.com/en/about/ourdepartment/.
Template | The template that will be used to create the index page.
Switch to editing | If this option is active, the index page will be opened in the HTML editor after the section is created. This allows you to start editing the index page without delay.

    Example of creating a section

    1. Switch to the Site Explorer: Settings -> Site Explorer.
    2. Click New folder in the page context bar.
    3. Enter the folder name. The name can contain Roman letters only.
    4. Enter the section name. This text will be shown in the navigation chain as a link to the section created.
    5. Check the Create index page for this section box to add the index.php file to the newly created folder. When the new site section is opened in browser, this page will be displayed by default.
    6. Select the template for the index page. The following page templates are included in the product: Standard page, Page include area or Section include area.
      • The Standard page template is the base for all the site pages.
      • The Page include area template is used for include sections (shown on a side part of a page).
      • Section include area is applied when creating an include area for all pages of this site section.
    7. Check the Switch to editing box to start editing the index page right after the section is created.
    8. Edit your index page as desired.
    9. Click Save to save the file in the created folder.


Folder properties - Bitrix Site Manager - Content Management & Portal Solutions

Folder properties

In this section

  • Context bar
  • Form fields
  • Control buttons
    •

    You can switch to the folder editing firm either by clicking Folder properties in the Site Explorer menu or clicking [image] in the administration toolbar.

    This form is used to customise permissions to access the section, and edit properties of the section pages.

    Context bar

    Button | Description
Folder | Switches to the folder currently opened in the Site Explorer.

    Form fields

    Field | Description
    Section name | The name of the folder displayed in the navigation chain as a link to the section.
    Folder properties
    Field | Description
Code | The property name specified in the Site Explorer module settings.
Value | A property value.

    An empty form field can be used to create a property whose value is used only for pages of this section. In this case, the Code field should contain the property mnemonic name. The property code is specified with the Roman letters only.

    The More button adds a new row that you can use to add a new property for the current section pages.
    Access rights
    [User group] The user group access permissions for the current section. The following permissions are available.
    • Deny - denies any access to this folder, including the right to read and view properties.
    • Read - permits to view the folder contents.
    • Workflow - permits users to edit documents in the folder via the workflow.
    • Write - permits users to modify files in the folder.
    • Full access - permits users to modify and delete folder files and manage their properties.
    • Inherit - the selected files and folders will be given the same access permissions as the parent folder.
    Customising the access permission in the All groups with "Inherit" access level field permits to edit the access level for all groups whose members have the Inherit permission.

    Control buttons

    Button | Description
Save | Saves the current changes. Returns to the folder currently opened in the Site Explorer.
Apply | Saves the folder properties. Editing continues.
Cancel | Cancels current changes. Returns to the folder currently opened in the Site Explorer.


Creating and editing a file - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a file

In this section

  • Context bar
  • Form fields
  • Example of creating a file
    •

    This form serves to create and edit files. To create a new file, click New file in the Site Explorer, or click [image] on the administration toolbar in the site public section. A new file/page is created in the folder currently opened in the Site Explorer. By creating a new file, you add a new page to the current section of the site.

    To open an existing file for editing, click this file in the Site Explorer, or click [image] in the administration toolbar.

    Context bar

    Button | Description
View file | Displays the file source code. The button is displayed when editing an existing document.
Edit as PHP | Edits the file source code. This mode is for use by developers only.
Edit as HTML | Edits the document in the integrated visual HTML editor whose user interface is similar to that of Microsoft Word.
Edit as text | Displays the file text as is without PHP code. However, HTML tags are displayed in this mode.
Rename | Opens a form in which you can provide a new file name. The button is displayed when editing an existing document.
Download file | Downloads the selected file to your local machine. The button is displayed when editing an existing document.

    Form fields

    Field | Description
    Template | The template that will be used to create the page. For example: Standard page, Page include area or Section include area. The field is displayed when creating a new file.
    File name | The file name including extension, for example, news.php. The field is displayed when creating a new file.
    Page title | An arbitrary page title. The specified title will be displayed in the page body. The field is displayed in the Edit as HTML or Edit as text mode.
    Page properties
    This section is used for customising and editing the page property values and for managing the META tags, such as page keywords and description. The section is displayed in the Edit as HTML or Edit as text mode.
    Field | Description
Code | The property name.
Value | Specifies the property value.

    Note!
    You can define properties in the Site Explorer module settings. An empty form field can be used to create a property, whose value will be used only with the current page. In this case, the Code field should contain the property mnemonic name. The property code is specified with the Roman letters only.

    See also: Folder properties.

    Control buttons

    Button | Description
Save | Saves the current page.
Apply | Saves the page properties. Editing continues.
Cancel | Cancels current changes.

    Example of creating a file

    1. Click New file in the Site Explorer. The default editor specified in the Site Explorer module settings will be opened.
    2. Select the template that will be used to create a page.
    3. Specify the file name (e.g. company.php).
    4. Click Save to add the new file to a current folder. Click Apply to save the file in a current folder and continue editing.


Uploading a File - Bitrix Site Manager - Content Management & Portal Solutions

Bitrix help system Send feedback on this topic

Uploading files

In this section

  • Uploading files
  • Form fields
  • Control buttons
    •
  • Example of uploading
    •

    Uploading files

    You can upload a file to the site from a local machine. The file will be stored in a folder currently opened in the Site Explorer. You can upload up to 5 files simultaneously.

    Form fields

    Field | Description
File name | The name to be given to a file after it is uploaded to the site. By default, the original file name is specified.
Upload file | Specifies the name and path to the uploaded file. Click the Browse button to select a file.

    Control buttons

    Button | Description
Save | Uploads the selected files. Opens the folder to which the file is uploaded.
Apply | Uploads the selected files. Clears the form fields for the next upload session.
Cancel | Cancels the file uploading. Switches to the folder currently opened in the Site Explorer.

    Example of uploading an image

    1. Select the /images/ folder in the Site Explorer (it is the recommended location to store images).
    2. Click Upload file.
    3. Click Browse and select a file on your local disk. After you have selected a file, the File name field will contain the name of a selected file. The field Upload file will show path to the file on your local disk. If required, you can change the file name to the one which will be given to it after uploading.
    4. Click Upload files.


Settings - Bitrix Site Manager - Content Management & Portal Solutions

Settings

In this section

  • Module settings
  • Module access level
  • Control buttons
    •

    The Settings form of the Site Explorer module is designed for customising the global module settings. For convenience, the form is divided into two tabs: Settings and Access.

    "Settings" tab

    This tab is used to alter the general module parameters.

    Field | Description
    Default page editor The default mode in which pages are edited. The following modes are available:
    • Text editor - displays the file as is without PHP code. However, his mode shows all HTML tags.
    • PHP source editor - displays the page source code. The mode is to be used by developers only.
    • Visual HTML editor - opens the document in the integrated visual HTML editor, whose user interface is similar to that of Microsoft Word.
    Use previous version of the visual HTML editor | Check this box to use the previous HTML editor version. Can be useful on outdated systems.
    Allow using styles without names in visual HTML editor Check this box to have also nameless CSS styles displayed in the CSS list when editing a page in the HTML editor mode.

    Note!
    Style names are specified in the .styles.php file located in the site template folder.
    Open WYSIWYG editor in full-screen mode by default | If the visual HTML editor is selected as the default editor, enabling this option will open the editor in the full screen mode rate rather than within a page.
    Show additional icons in the panel | Check this box to display the page include areas editing buttons in the administration toolbar. This is recommended setting for the 3.x product versions.
    Site settings
    Use individual settings for every site | If checked, each site will have own set of preferences. Otherwise, the default names of properties and menu types etc. are used for all sites.
    Settings for the site | Select here the site whose properties are to be edited in the fields below.
    Menu types This form contains pairs of mnemonic names of menu types and their descriptions. Menu types are usually named after their disposition, but you are free to provide any name you want.
    Field | Description
Type | The site menu type (mnemonic name). Usually, mnemonic names of menu types are specified according to the menu location (e.g. top, left etc.). Only Roman letters are possible here.
Name | An arbitrary name (description) of the menu type.
    Number of additional menu parameters | Number of parameters which can be passed in the menu item hyperlink and further processed by the menu display template. For example, if this field equals 1, the following parameter may be passed: ?lang=ru
    Property types This form is used to create the site page properties and their descriptions.
    Field | Description
Type | The property type (mnemonic name). Only Roman letters are possible here.
Name | An arbitrary property name (description). The name specified will be displayed in the folder (file) property editing form.

    Mnemonic names of the page property types used must correspond to the names of the META tag attributes, such as page keywords or description.

    "Access" tab

    This form is used to customize permissions of user groups to access the module resources.

    Field | Description
    Default | The access level of user groups for which the default value is specified.
    [User groups] Changes access policy for the specified user group. The following access permissions are possible:
    • deny - denies users to access files and folders;
    • accessible folders only - permits users to access folders whose settings allow access for this user group;
    • view module settings in read-only mode - permits users to view the module preferences but not edit them.

    Control buttons

    Button | Description
Save | Saves the current changes.
Reset | Cancels current changes. Restores the original parameter values.
Restore defaults | Returns the default module property values.


Information blocks - Bitrix Site Manager - Content Management & Portal Solutions

Information blocks

The Information blocks is the module aimed to manage and catalogue different types (blocks) of uniform information. Some examples of information blocks are:

  • news;
  • product catalog;
  • photo galleries;
  • job lists and other information.

Information blocks offer a convenient way to store the frequently updated information. This method of publishing the information saves time and efforts. You can easily add new information to the site. For example, you can set up a news feed informing visitors on important events in your company or new products.

The online store built with Bitrix Site Manager offer an immense potential of extensibility due to use of information blocks to group and catalogue products and services. That's why becoming familiar with the information blocks concept is essential if you intend to launch a trade representative of your company in the Internet.

The Information blocks module implements the following hierarchical model of information repository.

The information block types are created in the Information block types form (Content -> Information blocks -> Information block types), and displayed in the content and structure access area:

Blocks are populated with information via the administration section web interface. The only thing you have to do is to fill several required fields. As soon as you save changes, new information will be placed in an appropriate site section.

The site can have more than one types of information blocks, for example: news, catalog and other. You are free to create new types of information blocks depending on the subject of the site.

If your site provides multiple language mirrors, you can publish news and create catalogs in any available language. Documents will be dispatched to an appropriate site automatically. For example: if you denote the news is to be published in English, this news will be shown in the English mirror only.

A good take-off with information blocks is creating and publishing several types of blocks. A block type requires that you specify whether elements of the type can be grouped by categories. Example of a groupable type is a product catalog with commodities combined in different groups. For instance, a Video cassette player can be bound to groups Domestic equipment and Video equipment.


Information block types

In this section

  • Filter
  • Context bar
  • List of information block types
    •

    This form (Content -> Information blocks -> Information block types) is used to manage types of information blocks.

    Filter

    The filter is used to define one or more parameters to select types to be displayed in the list.

    Field | Description
Name | Searches for information block types by the name.
ID | The ID of a required information block type.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add new type | Switches to a form where you can create a new information block type.
Excel | Exports data from the table to the MS Excel format.

    List of information block types

    Field | Description
    Checkbox column | Used to select information block types to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any information block type opens a menu:
    • Information blocks - opens a list of information blocks of this type;
    • Edit - opens the information block type for editing;
    • Delete - deletes the information block type.
    ID | The information block type ID. Used by developers to select elements of information blocks of this type from the database.
    Name | The name of the information block type.
    Sorting | The sort weight defining the position of information blocks of this type in lists.
    Contains sections | Indicates whether the information blocks of this type have a hierarchical structure or not. Hierarchical blocks can be divided in sections and subsections. Structuring can be used to union products in logical groups, classify plants by genus, species etc.
    RSS export | Indicates whether the contents of information blocks of this type is allowed to be exported to an RSS file.


Creating and editing information block types

In this section

  • Context bar
  • Editing form
  • "Main" tab
  • "Additional" tab
  • Controls
  • How to create a new information block type
    •

    Bitrix Site Manager assumes that you create information block types using the New information block type form (Content -> Information blocks -> Information block types, click Add new type). Every new information block type is automatically added to the left menu of the administrative section for faster access:

    Context bar

    Button | Description
List | Opens a list of all information blocks.
Create | Creates a new information block type in this form.
Delete | Deletes the currently edited information block type. Important! This will delete all existing information blocks of this type.

    Editing form

    All fields marked with a red asterisk (*) are required.

    "Main" tab

    This tab offers basic parameters of an information block type.

    Field | Description
    ID | The code uniquely identifying the information block type.
    Use tree view to classify section elements (contains sections) If checked, information blocks of this type will have a hierarchical structure which means they can be divided in sections and subsections. You can assign the preferred names of sections in the Sections field.

    You can use structuring to union products in logical groups, classify plants by genus, species etc.

    If the option is unchecked, the information blocks of this type will have a linear structure.
    Language-dependent names and object titles
    Field | Description
Language | Languages installed and used in the system. You have to provide the section, element and type titles for each language.
Name | The name of an information block type for the respective language (e.g. Catalog).
Sections | The name of information block sections (e.g. Groups).
Elements | The name of information block elements (e.g. Products).
    "Additional" tab
    Field | Description
Use RSS export | If checked, the information blocks may be exported to an RSS file stored in a directory specified in the Path to exported RSS files field of the module settings form.
Sorting index | The sort weight defining the position of information blocks of this type in lists. The less is the value, the higher the blocks are positioned in lists.
Save operation handler | The full path name of the script (handler) called when saving an information block. The handler is responsible for pre-processing the information block element fields and can be used to alter data before it is saved. This field is for use by developers only. See Creating custom forms for the information block elements editing.
File with element editing form | The full path name of the script which is used to display the element editing user interface. Can be used to create custom editing forms. This field is for use by developers only.

    Controls

    Field | Description
Save | Applies changes performed on this page and switches to the list of information block types.
Apply | Applies changes performed on this page without switching to the list of information block types.
Cancel | Cancels current changes and restores parameters to their original values.

    How to create a new information block type

    1. Open the New information block type form (Content -> Information blocks -> Information block types).
    2. Click Add new type.
    3. Specify the symbolic code of the new information block type in the ID field. This can be a set of arbitrary Roman letters meaningful to the administrator.
    4. If the new type is to contain sections to group the information block elements, enable the Use tree view to classify section elements option.
    5. Enter the information block type names for different languages.
    6. If the new type contains sections [4], specify the section name. For example, information block Catalog may consist of groups. Check the box Contains sections to activate sections for this type if needed.
    7. Specify the element names. For example, News for the News type, and Product for Catalog.
    8. Click Save.
    9. After the save, the new type will be available in the left menu.


List of information blocks - Bitrix Site Manager - Content Management & Portal Solutions

List of information blocks

In this section

  • Filter
  • Context bar
  • List of information blocks
    •

    This page displays a list of all information blocks of the specific type.

    The Information Blocks form is used to manage information blocks of the given type. You can easily add information blocks, switch to filling blocks with information (e.g. add products manually), edit properties of an element (e.g. change product description and price) and perform other operations.

    Filter

    The filter is used to define one or more parameters to filter out blocks that are to be displayed in the list.

    Field | Description
Name | The name of a required block. You can use wildcards here.
Sites | Select a site whose information blocks are to be displayed.
Active | Allows to show active blocks, inactive blocks or both. Active state denotes the information of a block is permitted to be displayed in the public section.
ID | The ID of the required information block.
Mnemonic code | The symbolic code of the required information block.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add information block | Opens a form in which you can add a new information block of the given type.
Excel | Exports data from the table to the MS Excel format.

    List of information blocks

    Field | Description
    Checkbox column | Used to select information blocks to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any information block opens a menu:
    • section name - switches to a list of sections of this information block;
    • element name - opens a list of elements of this information block;
    • Edit - opens the information block for editing;
    • Delete - deletes the block.
    Name | Name of a block.
    Sort | Sort index (determines the order in which blocks are displayed).
    Active | Active state. Yes denotes the block is permitted to be displayed in the public section.
    Elements | Number of elements contained in this information block, including elements of nested sections. The link opens a list of elements.
    Sections | Number of sections in this information block. The link opens a list of sections.
    Site | Site(s) on which the block is allowed to display.
    Modified | The date and time the block was last modified.
    ID | The information block ID. The link opens the information block editing form.


Creating and editing a block - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing an information block

In this section

  • Context bar
  • Form fields
  • Information block
  • Properties
  • RSS
  • Access
  • Controls
  • Example of creating a news information block
    •

    This form is used to create and edit information blocks of the selected type. You can create information block types on the module settings page.

    Context bar

    Button | Description
List of information blocks | Opens a form displaying a list of information blocks of the type to which the edited block belongs.

    Table of block properties

    "Information block" tab
    Field | Description
    ID | The information block ID.
    Modified | The date and time the information block was last modified.
    Active | Toggles the block active state.
    Symbolic code The information block mnemonic code. Consists of the Roman letters. Underscores allowed.

    The mnemonic code consists of the Roman letters (and digits) which should be meaningful to an administrator. For example, the symbolic code of the Company News information block could be company_news. The symbolic code can be used by developers to select or exclude information from a specific information block.
    Sites | Site(s) on which the block is allowed to display.
    Name* | The name of the block.
    Sort index* | The sort index denotes the information block display order. Generally, blocks are displayed individually, but sometimes you may want to display all blocks on a single page (e.g. on the main page). The less sort index a block has, the higher it is displayed on a page.
    Element view page The address of a public page which is used to display the block elements. The following macros are allowed in the path:
    • #SITE_DIR# - the site root folder (from the site settings);
    • #SERVER_NAME# - the site URL (from the site settings);
    • #IBLOCK_ID# - the information block ID.
    Section view page The address of a public page which is used to display elements of a block section. This field is only available if the Use tree view to classify section elements option is enabled for the corresponding information block type.

    The following macros are allowed in the path:
    • #SITE_DIR# - the site root folder (from the site settings);
    • #SERVER_NAME# - the site URL (from the site settings);
    • #IBLOCK_ID# - the information block ID;
    • #ID# - the ID of an information block section;
    • #EXTERNAL_ID# - the external ID of an information block section.
    You can insert a required macro by clicking

    Value of this field is used by the Search module for building links, and with visual components in the public section.
    Detailed view page The address of a public page which is used to display the element detailed view. This field is only displayed if the property Contains sections is activated for the corresponding information block type.

    The following macros are allowed in the path:
    • #SITE_DIR# - the site root folder (from the site settings);
    • #SERVER_NAME# - the site URL (from the site settings);
    • #IBLOCK_ID# - the information block ID;
    • #ID# - the ID of an information block element;
    • #EXTERNAL_ID# - the external ID of an information block element.
    Index sections for the Search module Specifies whether the information block sections are to be indexed by the Search module.

    To add existing sections to the search index, fill in the Section view page field and allow section indexing. Next, re-index the site completely.

    To exclude the required section from the index, disable section indexing (uncheck this field) and then re-index the site completely.
    Index elements for the Search module Specifies whether the information block elements are to be indexed by the Search module.

    To add existing sections to the search index, fill in the Detailed view page field and allow element indexing. Then, re-index the site completely.

    To exclude the required element from the index, disable element indexing (uncheck this field) and then re-index the site completely.
    Description
    Image | An image associated with this block.
    Text / HTML | Defines how the block content is created and displayed.
    Use visual editor | If checked, activates toolbars with text formatting options for the HTML format.
    "Properties" tab

    A set of properties can be assigned to an information block. You can set values of these properties when adding a new element to the information block. For example: on your site, you may want to place articles about your company that had been published in mass media earlier. All these articles can be accumulated in the information block Publications. The following two properties can be assigned to this block: Author and Source. In this case, when adding an article, you will have to fill in the two new fields: Author and Source.

    Field | Description
    ID | Property ID.
    Name | Name of the property.
    Active | Active state denotes the property is permitted to be used when adding elements.
    Type Property type (text, number, list etc.)
    • Text - a property is a single line text;
    • Number - a property is a number;
    • List - the property value can be selected from a list;
    • File - a property is a file (image, document etc).
    • Link to sections - this property allows to link elements of this information block to sections of another block;
    • Link to elements - allows to link elements of this information block to other elements.
    Each property type has its own set of parameters which can be defined in the Property details form.
    Mult. Indicates a multiple property.

    This means that more than one value can be assigned to a property. Number of input fields can be set in the property details form (click the corresponding Modify button).
    Sort | The property sort weight. Defines the property position in lists.
    Code | The mnemonic code. Can contain Roman letters and digits but cannot start from a digit.
    Edit | Click this button to open the Property details form.
    Delete | If checked, the property will be deleted upon clicking Save.
    "RSS" tab

    This tab contains settings that are followed when exporting the information block data to RSS.

    Field | Description
    Allow dynamic RSS export | If checked, the system will export RSS directly to the HTTP stream bypassing file creation.
    Valid (hours) | The period of time during which the RSS remains valid.
    Allow export to RSS file | If checked, the RSS file will be created regardless of the option Allow dynamic RSS export.
    Number of elements exported to RSS file | The number of block elements exported to RSS file. A value of -1 forces all elements to be exported.
    Export last days | The number of last days for which to export information to RSS file. A value of -1 forces all elements to be exported
    Allow Yandex format | Check this option to export files compatible with the Yandex catalog exchange format.
    RSS export fields assignment
    Field | Description
RSS field | Field in an RSS file to export into.
Field template | The information block field to export from.
    "Access" tab

    This tab controls the user access to this information block.

    Field Description
    [user group] Defines the user group access permission to manage the information block.
    • read - allows viewing the information block elements in the public section;
    • workflow - allows editing elements via the workflow;
    • write - allows editing parameters of information block sections and elements;
    • deny - denies any access to the information block;
    • full access - same as write, but also allows to edit permissions of other user groups.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of information blocks.
Apply | Applies changes performed on this page without switching to the list of information blocks.
Cancel | Cancels current changes and restores parameters to their original values.

    Example of creating a news block

    Perform the following operations to create a new information block News.

    1. Open the News information block type editing page (Content -> News).
    2. Click Add information block.
    3. Check the Record active box to make the section visible to visitors.
    4. Specify the section symbolic code (company_news).
    5. Select the site to display news of this section (English).
    6. Type in the section name (Company news).
    7. Set the sort index.
    8. Set the values of the fields Page with list of elements, Section view page and Detailed view page. For the news to display correctly, you have to set the following URL's:
      • Page with list of elements: #SITE_DIR#/about/news.php?ID=#IBLOCK_ID#
      • Section view page: #SITE_DIR#/about/news_list.php?ID=#ID#
      • Page with detailed view: #SITE_DIR#/about/news_detail.php?ID=#ID#
    9. Allow the information block contents to be indexed.
    10. Set user group access permissions.
    11. Click Add to save changes.


Information block sections - Bitrix Site Manager - Content Management & Portal Solutions

Information block sections

In this section

  • Filter
  • Context bar
  • List of sections
    •

    When creating an information block, you can set the block in the hierarchical mode so that a block contains not only elements, but also sections. The latter, in their turn, can contain sections and elements as well. For example, the Trading Catalog information block can contain a section Computer peripherals, that can contain sections Printers and Scanners.

    This form helps manage elements and sections of an information block.

    Filter

    The filter is used to define one or more parameters to select sections to be displayed in the list.

    Field | Description
    Name | The name of the required section. You can use wildcards here.
    Section | Searches for sections by their parent section.
    ID | The ID of the required section.
    Modification date Specifies to display sections whose modification date lies within the specified interval. The date can be specified in one of the following ways:
    • days since the last modification;
    • range of days within which the section information was modified.
    Symbolic code | The mnemonic code of the required section.
    External code | Searches for sections by their external ID (used to bound a section to external information sources).
    Active | Allows to show active sections, inactive sections or all. Active state denotes the information of a section is permitted to be displayed in the public section.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Elements | Opens a list of elements of the current information block section.
Add subsection | Adds a new subsection to the current section.
Add element | Opens a form in which you can create a new element in this information block section.
Information Block properties | Switches to the information block properties editing form.
Excel | Exports data from the table to the MS Excel format.

    Table

    Field | Description
    Checkbox column | Used to select information block sections to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any section opens a menu:
    • section name - switches to a list of subsections of this section;
    • element name - opens a list of elements of this section;
    • Edit - opens the information block section for editing;
    • Delete - deletes the section.
    Name | The section name.
    Active | Active state. Yes denotes the section contents is permitted to be displayed in the public section.
    Sort | Sort index (determines the order in which sections are displayed).
    Elements | Number of elements contained in this section; in brackets - total number of elements contained in this and child sections. The link opens a list of elements. The [+] link adds a new element.
    Subsections | Number of subsections contained in this section. The link opens a list of subsections. The [+] link adds a new section.
    Modified | The date and time the section was last modified.
    ID | The information block section ID. The link opens the section for editing.


Creating and editing an information block section - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing an information block section

In this section

  • Context bar
  • Editing form
  • Section parameters
  • More
    •
  • Controls
    •

    If, when creating an information block, you specified the block is to contain sections, this form opens every time you create or edit an information block section.

    Context bar

    Button | Description
Sections | Opens a page containing a list of the information block sections.
New section | Adds a new section to the current information block.
Delete section | Deletes the current section.

    Editing form

    To add a new section, fill in the form fields and click Add.

    "section name" tab
    Field | Description
ID | The ID of the section being edited.
Last update | The date and time the section was last modified.
Active | In checked, the section contents is permitted to be displayed in the public section.
Parent section | Section that is to contain the created one. That is, the created section becomes a child of the selected section.
Name | The name of a section.
Image | An image to be associated with this section.
Description
Text / HTML | Defines how the block visual contents is created and displayed.
Use visual editor | If checked, activates toolbars with text formatting options for the HTML format.
Section description | A meaningful section description. This description will be shown in the public section.
    "More" tab
    Field | Description
Sort index | The sort index (defines the order in which sections are displayed).
Mnemonic code | The information block mnemonic code. Should consist of the Roman letters and digits. Underscores are also allowed.
Detailed image | A detailed (e.g. large or high-resolution) image associated with this section.

    Controls

    Field | Description
Save | Applies changes performed on this page and switches to the list of information block sections.
Apply | Applies changes performed on this page without switching to the list of information block sections.
Cancel | Cancels current changes and restores parameters to their original values.


Information block elements - Bitrix Site Manager - Content Management & Portal Solutions

Information block elements

In this section

  • Filter
  • Context bar
  • List of elements
    •

    This page shows a list of elements of an information block, or an information block section. An element is an entity that cannot be further atomized within the hierarchy, for example: the element Mousepad of the section Accessories.

    Filter

    The filter is used to define one or more parameters to select elements to be displayed in the list.

    Field | Description
Find | Allows to find elements by the text in their name or description.
ID | Specifies the range of the ID's of elements to be displayed.
Section | Finds elements by their parent section.
Modified | The date when the required elements was last modified .
Modified by | Searches for elements modified by the specified user. You can select a user from the list, or type the ID of a user.
Created | The date when the required elements was created.
Created by | Searches for elements created by the specified user. You can select a user from the list, or type the ID of a user.
Status | Status of the required elements (for elements modified via the workflow).
Active | Allows to show active elements, inactive or all.
Name | The name of the required elements. Complex queries allowed.
Description | Element description (this allows to filter by both short and detailed description). Complex queries allowed.
Symbolic code | The mnemonic code of the required elements.
External ID | Searches for elements by their external ID.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add element | Opens a form in which you can create a new element in this information block section.
One level up | Displays elements of the parent section.
Information Block properties | Edits properties of the information block which contains the displayed elements.
Excel | Exports data from the table to the MS Excel format.

    List of elements

    Field | Description
    Checkbox column | Used to select elements to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any element opens a menu:
    • Unlock - releases the element previously locked for editing;
    • Modify - opens the information block element for editing;
    • Change log - shows the element modification history;
    • Preview - shows the element as it looks in the public section;
    • Delete - deletes the section.
    Name | The name of the element.
    Active | Indicates the element state. The active state denotes the element is permitted to be displayed in the public section.
    Sort | The element sort order.
    Modified | The date and time the element was last modified.
    Status | The element status (if modified via the Workflow module)
    Locked Signals of the element availability:
  • - the element can be edited;
  • - the element is locked by you. You can unlock it by selecting the Unlock command in the action menu;
  • - the element is locked by another user.
    •
    ID | The element ID.


Editing the information block element - Bitrix Site Manager - Content Management & Portal Solutions

Editing the information block element

In this topic

  • Context bar
  • Editing form
  • The element properties tab
  • The Commercial catalog section
  • The Prices tab
  • The Prices (ext.) tab
  • The Parameters tab
  • The Groups tab
  • The Discounts tab
  • The "Preview" tab
  • The "Details" tab
  • The "Section name" tab
  • The "More" tab
  • The "Workflow" tab
  • Controls
    •

    This form is the foremost tool to add elements manually. For example, you can use it to add new products to the catalog, publish news and so on.

    Context bar

    Button | Description
List of elements | Opens a page displaying the list of elements of this information block.
Add new element | Creates a new element in this form.
Delete | Deletes the current element.

    Editing form

    All fields marked with a red asterisk (*) are required.

    The element properties tab
    Field | Description
    Active | If checked, denotes the element is permitted to be displayed in the public section.
    Active period | The period during which the element is active. If the ending date is omitted, the element is permanently active. If the ending date is omitted, the element is considered active since its creation.
    Name | Name of an element in the public section.
    Properties and values
    Pairs "Property Name" : "Value". You can create element properties on the information block settings page.
    Commercial catalog
    This section is only displayed if the information block settings has the option Is catalog enabled.
    The "Prices" Tab
    This tab is used to specify product prices for different price types.
    Field | Description
Base price | The base price of the product.
Base price currency | Currency in which the base price is specified.
Price type | Available price types.
Type of extra | This field is used to select the type of extra (or discount) which is to be used to calculate the final price, for the corresponding price type.
Amount | Final product price adjusted for the chosen type of extra. The final amount is calculated using the following formula: [Cost] = [Base price] + [Base price] * [Extra percentage] / 100 If no extra is selected, you can type the amount manually.
Currency | Currency in which the product price is specified for this price type.
    The Prices (ext.) tab
    This tab servers to specify the product price for different price types. You can provide here extra factors that can affect the final amount.
    Field | Description
Price type | Available price types.
From | These fields serve to specify relationship between the quantity of product units and the price. For example, you can indicate that, for 1 to 5 pcs. the product price is $100 per unit, and for 6 to 10 pcs. - $90 per unit. You can specify range as the product quantity.
To
Type of extra | Used to select the type of extra (or discount) which is used to calculate the final price for this price type. You cannot apply extra or discount to the base price.
Unit price | Price of a single piece of the product for the specified price type and quantity.
Currency | Currency in which the product price is specified for this price type.

    Click More... to add more rows where you can define more price parameters and settings.
    The Parameters tab
    This tab contains information about the product to be put for sale. If the catalog is enabled to sell electronic content, this tab displays the subscription parameters.
    Parameters
    In stock | Quantity of products currently in stock. If the option Reduce quantity upon order is active, you cannot change this value manually.
    Reduce quantity upon order | Check this option if you want the value of the field In stock to automatically decrement when an order occurs.
    Weight | Weight of a product unit, in grams.
    Subscription parameters
    Payment type Defines the type of payment for purchasing the electronic content. The following types are available:
    • One-time - means that a customer can buy the product only once. No further actions will be performed on the product;
    • Recurring (subscription) - instructs the system that, when the specified period expires, a customer is to be billed again to renew the product usage;
    • Trial - implies purchasing a trial version of the product (e.g. trial access). When the specified period expires, a customer will be billed to buy a full version of the product.
    Payment duration | Period of time on expiry of which the system will bill a customer again. This field should be filled for the payment types recurring and trial.
    Time unit of payment duration | The time unit used to define the payment duration (month, day, hour etc.)
    Trial for | If you have chosen a trial as the payment type, specify the full version here. When the trial period expires, a customer will be asked to purchase the specified product (full version).
    Renewal without ordering | For use with the recurring payment type. If this option is active, the order total amount will be calculated when renewing (subscription), but an order will not be created in the system. This option may be useful if small regular charges are to be drawn off the user internal account.
    The Groups tab

    The Groups tab is displayed only for elements of a content selling enabled commercial catalog. This tab helps manage selling permissions to access the site resources.

    Field | Description
Include | Used to select user groups to which the customers are to be added when they purchase the product.
User group | Name of the respective user group.
Active period | Period of time during which customers are the members of the user group. When the specified period expires, a customer will be deleted from the group. If set to 0, customers are added to the user group forever.
    The Discounts tab

    The Discounts tab allows to choose discounts that can be applied to the current product.

    Field | Description
ID | The discount ID.
Site | The ID of the site whose products can be sold with this discount.
Active | Indicates that the discount is active. If the discount is inactive, it cannot be applied.
Name | The name of the discount.
Amount | The discount value.
Action | Actions that can be performed to discounts. Click Edit to switch to the discount editing.
    The "Preview" tab

    This form is used to provide an element with a short description. Such description can be used to enrich an element with a brief review in lists.

    Field | Description
Image | A small image for the element preview function.
Text / HTML | This format defines how the content is created and displayed.
Use visual editor | If checked, activates toolbars with text formatting options for the HTML format.
    The "Details" tab

    Here you have to provide a full description of an element. For example: complete article body, full product description etc.

    Field | Description
Image | A large image for an element.
Text / HTML | This format defines how the content is created and displayed.
Use visual editor | If checked, activates toolbars with text formatting options for the HTML format.
    The "Section name" tab

    Here you can select one or more sections of an information block to which the element relates.

    Field | Description
Sections | Sections to which the element is to be bound. This field is unavailable if the underlying information block has the option Contains sections disabled.
    The "More" tab
    Field | Description
Sorting index | The sort weight of the element. The less is the value, the higher is an element positioned in lists.
External ID | The code used to link an element to an external data source.
Symbolic code | The mnemonic code used to address elements (for use by developers).
    The "Workflow" tab
    Field | Description
Created | The date and time the element was created.
Last modified | The date and time the element was last changed. The ID and name of a user who performed the change.
Locked | If locked: the date and time the element was locked. The ID and name of a user who locked the element.
Status | The current status of the element. You can create and edit statuses in the Workflow module.
Comments
Arbitrary comment (e.g. for the status change).

    Controls

    Button | Description
Add | Confirms that a new element is to be created. Then, switches to the list of information block elements. Displayed when creating a new information block element.
Save | Saves changes. Returns to the list of information block elements. Displayed when editing an existing information block element.
Apply | Applies current changes. Editing continues.
Don't save | Cancels changes to an existing element, or dismisses creation of a new element. Returns to the list of information block elements.
Reset | Dismisses recent changes. Editing continues.


Information block property editor

In this section

  • Form fields
  • Controls
    •

    This form displays when you click Modify on the Properties tab of the information block settings screen.

    Form fields

    Field | Description
    Common properties
    ID | The property ID.
    Mnemonic code | The information block mnemonic code. Should consist of the Roman letters and digits. Underscores are also allowed.
    Name | The name of the property.
    Property active | Toggles the property active state. Active properties can be displayed in the public section.
    Type The property type:
    • String - a property value is a text string;
    • Number - a property value is a number;
    • List - user can select a property value from the list;
    • File - a property value is a file (which can be posted by a user to the server);
    • Link to sections - this property allows to link elements of this information block to sections of another block;
    • Link to elements - allows to link elements of this information block to other elements.
    Multiple | If checked, indicates the property is multiple, i.e. more than one value can be assigned to a property. For example, a Colour property may have values blue, black, red etc.
    Number of input fields for multiple entries | For multiple properties: this field define the number of fields to accept property values (number of possible values).
    Sorting | The sort weight of a property defining its position in lists.
    Fields used with "String" and "Number" types
    Default value | This value will be assigned to this property of all newly created elements by default.
    Input field size The width and height of the input field as it will appear in the element creation form.
    The size values should be specified as the number of columns and rows, respectively.
    Property values will be used in search | Enables or disables indexing values of this property by the internal search engine.
    Use property in a filter on an element list page Denotes that the filter in the list of elements will include a special field that can be used to search for elements by values of this property.

    The filter field will have the same title as the property has, and will be of the same type.
    Display value description field | Specifies to display the property description beside the property field in the information block element editing form.
    Fields used with "List" type
    Appearance Select here the control to use for choosing the property value:
    • list - uses a listbox to select values;
    • checkboxes - uses a set of checkboxes to select the reqiored option.
    Number of rows (for "list") | For the list control type: specifies the field height, in rows.
    Property values will be used in search | Enables or disables indexing values of this property by the internal search engine.
    Use property in a filter on an element list page Denotes that the filter in the list of elements will include a special field that can be used to search for elements by values of this property.

    The filter field will have the same title as the property has, and will be of the same type.
    List values

    This field is used to define a list of possible property values:

    Field | Description
ID | The list item ID. Can contain Roman letters and digits, but must not start with a digit.
Value | The list item value.
Sort | The list item sort weight; defines the item position.
Default | Indicates the value will be selected by default for all newly created elements.
    Fields used with "File" type
    File types | A comma-separated list of extensions of files allowed for upload.
    Input field size | The property field width, in columns.
    Display value description field | Specifies to display the property description beside the property field in the information block element editing form.
    Fields used with "Link to sections" type
    Information block | An information block to whose sections the elements of the current information block can be bound.
    Fields used with "Link to elements" type
    Information block | An information block to whose elements the elements of the current information block can be bound.

    Controls

    Button | Description
Continue | Saves the property parameters and switches back to the information block editing form.
Reset | Discards the changes performed.


Exporting the information block contents

In this section

  • Step 1. Information block
  • Step 2. Export settings
  • Step 3. Result
    •

    The Catalog export form serves to export the information block contents to a CSV file.

    Step 1. Information block

    Field | Description
Export information block | Select here the information block whose data is to be exported to a CSV file.

    Click Next to proceed.

    Step 2. Export settings

    In this form you have to specify how the export procedure is to be performed.

    Field | Description
    File format settings
    Delimiter | Choose the symbol with which fields are to be separated in the output file.
    First row is a header | Check this box if you want the first row of the output file to contain field names.
    Assign database fields to file fields
    Field | Description
Export | Check this box if you want this field to be exported to the output file.
Field name | Names of the fields to be exported. Important! Be sure to select at least one of the fields Unique identifier (B_IBLOCK_ELEMENT.XML_ID) or Name (B_IBLOCK_ELEMENT.NAME). These fields are used to match database fields to file fields.
Sort order | These fields define the order in which the fields will be positioned in the output file.
    Output file
    Data file name Type here the full path name of the output file, relative to the site root. For example: /upload/export_file.csv.

    Important!
    If a file with such name already exists, it will be overwritten.

    To revert to the previous step, click Back. To start the export procedure, click Start.

    Step 3. Result

    This screen displays the export results, and a link which can be clicked to download the generated CSV file to a local computer. You can click Back to first step if you want to export more data.


Importing the information block contents

In this section

  • Step 1. Data file
  • Step 2. Format
  • Step 3. Fields
  • Step 4. Result
    •

    This form (Content -> Information blocks -> Import) is used to import external data in an information block.

    Step 1. Data file

    Here you can choose the file whose contents is to be imported, and an information block to receive the imported data.

    Field | Description
Data file | Click Browse to select a file containing data to be imported.
Information block | Choose an information block to which the data will be added.

    Step 2. Format

    Field | Description
    Select data file format Choose the appropriate CSV file format:
    • delimited - fields in file are separated with a special symbol (e.g. comma or space);
    • fixed-width fields.
    The other options depend on your choice here.
    Delimited
    Field delimiter | Choose a symbol which is the field separator in the source file.
    First row is a header | Check this option if a first row in the file contains field names.
    Fixed-width fields
    Delimiters | Type here ordinals of columns which are the field separators in the source file.
    First row is a header | Check this option if a first row in the file contains field names.
    Data samples
    This field displays an extract from the source file.

    Click Next to proceed, or Back to return to the previous step .

    Step 3. Fields

    In this form you have to specify how the import procedure is to be performed.

    Field | Description
    Assign file fields to database fields
    In this form you need to assign the source file fields to the target information block fields.
    Field | Description
File field | The source file fields.
Database field | The fields of an information block to which the imported data will be added. Important! Be sure to select at least one of the fields: Unique identifier (B_IBLOCK_ELEMENT.XML_ID) or Name (B_IBLOCK_ELEMENT.NAME). These fields are used to match file fields to database fields.

    Important!
    Ensure that the field correspondence is set up correctly. Otherwise, importing may lead to unpredictable results.
    Additional settings
    Path to images | To import elements containing images, upload images to any site folder via FTP prior to importing the CSV file. Then, specify the path to the folder in this field.
    Existing items not found in the file Defines how to treat information block elements which are currently in the database but not in the file:
    • Deactivate - these elements will become inactive;
    • Delete - elements will be deleted;
    • Keep - elements will be left as is.
    Existing inactive items/groups present in the file Select an action to perform on inactive elements and groups of an information block:
    • Leave as is - elements and groups will not be changed;
    • Activate - elements and groups will become available in the public section.
    Step execution time | Duration of one execution step, in seconds. If 0, the import will be performed in a single step.
    Data samples
    This field displays an extract from the source file.

    To revert to the previous step, click Back. To start the import procedure, click Load data.

    Step 4. Result

    This screen displays the import results. You can click Back to first step if you want to import more data.


Module settings

Settings

In this topic

Settings
Controls

Settings

Field | Description
Use visual HTML editor | If this option is checked, the system activates the embedded HTML for editing the information blocks contents. This allows to change the text format, size, type; insert images etc.
Show code from external DB source | If checked, the administrative section displays code that the system uses to bind the external data (e.g. Internet catalogs) to data of your site.
Path to exported RSS files | Path to folder relative to the site root in which the RSS feed files are stored. The RSS feeds may contain information on latest updates to information blocks.

Controls

Field | Description
Save | Applies changes performed.
Reset | Cancels current changes and restores parameters to their original values.
Restore defaults | Resets the form parameters to their default values.


How to create a news information block - Bitrix Site Manager - Content Management & Portal Solutions

How to create a news information block

Perform the following actions to create a new information block News.

  1. Open the News information block type form (Administration section -> Content -> News).
  2. Click Add information block.

  3. Check the Record active box to make the new block visible in the public section.
  4. Specify the section symbolic code (company_news). The symbolic code is provided to aid developers to display information in the public section.
  5. Select the site to display news of this section (English).
  6. Type in the section name (Company news).
  7. Set the sort index.
  8. Set the values of the fields Page with list of elements and Page with detailed view. For the news to display correctly, you have to set the following URL's:
    • Page with list of elements: #SITE_DIR#/about/news/index.php?ID=#IBLOCK_ID#
    • Section view page: #SITE_DIR#/about/news/list.php?ID=#ID#
    • Detailed view: #SITE_DIR#/about/news/detail.php?ID=#ID#
  9. Enable indexing sections and elements of the information block.
  10. Upload an image to be used with the information block. The image will be displayed in the list of information blocks.
  11. Type the description. The description text will be displayed in the list of information blocks.
  12. If properties are required to describe elements, add properties to the information block.

    For example, for each news of the Company news information block you can specify an information source and an author. Open the Properties tab and create the properties: Source and Author. Later, when creating the news, you will be prompted to fill in these fields.

  13. Assign the required permissions to user groups for this information block.
  14. Click Save to save the new information block.


How to add news

Perform the following actions to publish news.

  1. Open the News information block editing form (Administration section -> Content -> News).
  2. Select the information block to which you want to add news (e.g. Company news).
  3. In the action column menu, select the item titled after the element name (News)to open a list of all news of this block.

  4. In the list of news, click Add.
  5. Enable the Record active option to make the news available in the public section.
  6. Specify the period of time during which the record is active. Click the button beside the Active period field to invoke a calendar to select dates. The news will be displayed starting from the date that you specify here.

  7. Provide the news title.
  8. Enter the short description of a news. The short description will be displayed in the list of news.
  9. Type in the full text of the news.
  10. On the Groups tab, choose a section of the information block to which the news relates.
  11. Open the More tab if you want to assign a sort weight or symbolic identifier to the news.
  12. Click Save to add the news and go back to the list of news.


How to create a new information block type - Bitrix Site Manager - Content Management & Portal Solutions

How to create a new information block type

  1. Open the form displaying available information block types (Content -> Information blocks -> Information block types).
  2. Click Add new type.
  3. Specify the symbolic code of the new information block type in the Identifier field. This can be a set of arbitrary Roman letters meaningful to the administrator. For example, photogal for the PhotoGallery type.
  4. Enable the Use sections to classify elements option if you want information blocks of the new type to contain sections.

  5. Provide the name of the information block (Name) for all languages in the system.
  6. Type the title of the information block sections (if it contains sections).
  7. Specify the element name. For example, News for the News type, or Product for the Catalog type.
  8. Click Save. After the save, the new type will be available in the left menu.


Workflow - Bitrix Site Manager - Content Management & Portal Solutions

Workflow

The Workflow module is designed for staged processing of static pages and dynamic components of the site. Using the module allows for arranging teamwork for site content management.

The module adheres to the following preconditions.

  1. Documents on all site pages can be modified in the workflow mode. To do so, a user should have at least the right Workflow for the specified page.
  2. A Document is a copy of the static page in the Workflow module. Each static page can have only one document. Editing a static page means modifying the corresponding document (a copy of this page) in the Workflow module. While modifying the document, the user can change its state. The final status is status #1, when the document contents is transformed into a page (file). Note that the order of changing the document status can be arbitrary. When creating a new page, at first, its document is created; upon publishing the document, the corresponding page is created.
  3. To use links to different files (jpeg, gif, pdf, etc.) in the document, the user should load them into the document. Upon publishing the documents, all these loaded files are moved into the specified directories.
  4. All modifications of the document are recorded in the document history. To roll back changes in the document, the user should copy the required part of the document from its history.


Documents - Bitrix Site Manager - Content Management & Portal Solutions

Documents

In this topic

  • Filter
  • Context bar
  • List of documents
    •

    The Documents form (Content -> Workflow -> Documents) shows documents in the workflow. A document is a copy of a static page being edited in the workflow mode. When the document obtains status #1 (ready for publication), all the changes are transferred from the document into the file (a static page being edited).

    Filter

    This form is used to find documents matching the specified criteria.

    Field | Description
    Document ID | The ID of the required document.
    Document access indicator Specifies to find a document by its editing status.
  • green – document is ready for editing;
  • yellow – document is temporarily locked by you. Note that no one but you can edit it. Maximum time interval of document locking can be defined in the module settings.
  • red – document is being currently edited by another user.
    • Modified | The date the document was last modified.
    Modified by | A user who was the last to edit the document.
    Site | The site displaying the document being edited in the module.
    Filename | Specifies to find a document by its filename.
    Title | Specifies to find a document by its title.
    Content | Arbitrary text included in the document.
    Status | The document status.

    To filter documents by the specified search criteria, click Set filter. To have all documents displayed, click Cancel.

    Context bar

    Button | Description
Add | Opens a form in which you can create a new document in the workflow mode.
Excel | Exports data from the table to the MS Excel format.

    List of documents

    Column | Description
    Checkbox column | Selects documents to which the desired actions are to be applied.
    Action menu
             Actions on the document:
    • Modify - edits the document in the workflow mode;
    • Preview - opens a copy of the document for viewing;
    • History - views the document modification history;
    • Delete - removes information about the document from the workflow database.
    Ind. Indicates the document editing status.
  • – Document is ready for editing;
  • – Document is temporarily locked by you. Note that no one but you can edit it. Maximum time interval of document locking can be defined in the module settings.
  • – Document is being currently edited by another user.
    • Modified | The date the document was last modified.
    Modified by | A user who was the last to edit the document.
    Title | The document title.
    Filename | The documents filename.
    Status | The current document status (for example, Draft).
    Site | The site on which the document can be shown.


Editing a document

In this section

  • Context bar
  • Editing form
  • Edit document
  • Uploaded files
  • Comment
  • Control buttons
    •

    This form is intended for editing documents in the workflow mode. For users convenience, the page if divided into separate tabs.

    Context bar

    Button | Description
List of documents | Opens a page containing a list of documents.
Create new document | Opens a form in which you can create a new document in the workflow mode.
Delete current document | Deletes the document being edited.

    Editing form

    "Edit document" tab

    This tab is used to edit the document body.

    Field | Description
Template | Template to be used to create the page. Displayed when creating a new document.
*Site | The site for which the document is being created. Displayed when creating a new document.
Status | The document status.
Created | The date the document was created.
Modified | The date the document was last modified.
Locked | The name of a user who locked the document; date and time of locking.
*Full file name | The full file name (with the path). When specifying the full path to the file on server, you must at least have the Workflow permission to the folder you have specified.
Title | The document title.
Text/HTML | The creating and editing mode. If the Use visual editor option is enabled and the editing mode is HTML, document editing is carried out in the visual HTML editor mode.
    "Uploaded files" tab

    To include images or any other files into the document, you must load them into it. It is recommended to type the filename without the path - in this case, it will be loaded into the same directory as the document being edited.

    You can view, download or delete the uploaded files from the document. In the document body, you can use both relative and full paths to the loaded files. You can also insert links to any files located on the server.

    Field | Description
Uploaded files
ID | The unique ID of the uploaded file.
Name | The name of the file.
Size | The file size.
Uploaded | The date and time when the file was uploaded.
Uploaded by | The user who uploaded the file.
Del. | To delete the file, check this box and click Apply.
File upload fields
Uploaded file name on server | The name that will be given to the file after uploading.
Local file name | The name of the loaded file. To select a file, click Browse.
    "Comment" tab

    This tab is used to provide the document with an arbitrary comment (for example, about moving the document to another status). It does not affect the final view of the file.

    Control buttons

    Button | Description
Save | Saves the document.
Apply | Saves current changes. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


History - Bitrix Site Manager - Content Management & Portal Solutions

Change history

In this topic

  • Filter
  • Report table
    •

    The Change history page (Content -> Workflow -> History) contains the history of document changes. Each time a document is saved, a record is added to the history log. You can specify the maximum number of the most recent history records in the module settings. The module settings also allow to define the maximum period of time to keep the history records.

    Filter

    This form is used to find the change history records matching the specified criteria.

    Parameter | Description
ID | The ID of the record in the change history (can be separated with a comma).
Document ID | The ID of the document (can be separated with a comma).
Modified | The date when the required document was last modified (the date history record was created).
Modified by | A user who was the last to edit the document.
File name | Specifies to find a document by its filename.
Title | Specifies to find a document by its title.
Content | Specifies to find a history record by the document body text.
Document status | The document status.

    To filter the document by the specified search criteria, click Set filter. To have all documents displayed, click Cancel.

    Report table
    Column | Description
    Checkbox column | Selects documents to which the desired actions or rules are to be applied.
    Action menu
             Actions on the change history record:
    • View - opens a copy of the document for viewing;
    • Delete - removes the record.
    Modified | The date the document was last modified.
    Modified by | A user who was the last to edit the document.
    Filename | The documents filename.
    Title | The document title.
    Status | Status of the document at the moment the change history record was being created.


Statuses - Bitrix Site Manager - Content Management & Portal Solutions

Statuses

In this topic

  • Filter
  • Status table
  • Example of using statuses
    •

    The Statuses (Content -> Workflow -> Statuses) page displays all the possible statuses of static documents and the information block elements. Statuses are used to break the document work chain into several stages, for each of which a single user or a group of users is responsible. Status #1 is the final status in the workflow chain; it is reserved and cannot be deleted. When the document obtains the final status, all the changes take effect, and the document gets published.

    Filter

    This form is used to find the document statuses matching the specified criteria.

    Parameter | Description
ID | The status ID (can be separated with a comma).
Active | Specifies to display only active or inactive statuses.
Title | The status title.
Description | Finds statuses by their description.
Documents | Specifies to display statuses by the number of documents currently in these statuses. Number of documents can be specified both as a range and as a single number.

    To enable the filter, click Set filter; to disable it, click Cancel.

    Context bar

    Button | Description
Add | Opens a form in which you can create a new status.
Excel | Exports data from the table to the MS Excel format.

    List of statuses

    Column | Description
    Checkbox column | Selects statuses to which the desired actions or rules are to be applied.
    Action menu
             Actions on the status:
    • Modify - edits the status parameters;
    • Delete - deletes the status. The final status (with the ID of 1) cannot be deleted.
    ID | The status ID.
    Modified | The date the status was last modified.
    Active | Indicates the status is active. Inactive status cannot be applied to documents.
    Sort. | The status sort weight. Defines the position of the status in lists.
    Title | The status title.
    Documents | Displays the number of documents currently in this status. Link containing the number of documents opens the list of documents in this status.

    Example

    Assume there is a group of authors making articles for the site. There is also an editor-in-chief who is in charge of checking and publishing articles. To organize the workflow according to this scheme, you have to create 2 additional statuses:

    • Draft;
    • Ready (for publication).

    Authors should be permitted to edit documents in the Draft status and assign the Ready status to them. The editor-in-chief should be entitled to edit these documents in the Ready status, as well as assign them the Draft status (to be revised) and status #1, Published (i.e. publish these documents).

    The use of e-mail message templates allows to create and send an e-mail notification to a user automatically each time when the document status changes. For example, messages about assigning documents the Ready status can be sent to the editor-in-chief.

    To have an e-mail address inserted into a message automatically, following variables are to be used in the TO field of the e-mail template:

    1. An e-mail message is sent to the address of the document author (#ENTERED_BY_EMAIL#).
    2. An e-mail message is sent to all addresses of workflow administrators (#ADMIN_EMAIL#).
    3. An e-mail message is sent to all participating in editing the document in its current status (#BCC#).

    In case the Notify all users... checkbox is selected in the settings of the current status, an e-mail message will be sent to all members of groups with the permission to edit the document in its current status (#BCC#).


Workflow: Status parameters - Bitrix Site Manager - Content Management & Portal Solutions

Status parameters

In this topic

  • Context bar
  • Editing form
  • Control buttons
    •

    This form is designed to create new statuses and change parameters of existing ones.

    Context bar

    Button | Description
List of statuses | Opens a page containing the list of document statuses.
Create new status | Creates a new status in this form. The button is displayed when editing the existing group only.

    Editing form

    Field | Description
Modified | The date the status was last modified.
Documents in this status | Number of documents in this status.
Active | Specifies whether the status is active or not. Inactive status cannot be assigned to a document.
Sorting index | The status sort weight. Defines the status position in lists.
Title* | The status title.
Description | The status description.
Allowed to set this status to the document | List of user groups entitled to assign the status to documents.
Allowed to edit and save the document in this status | List of user groups entitled to edit and save the document in this status specified.
Notify all users allowed to either edit or view the document when it enters this status | With this field enabled, a notification will be sent to all users allowed to edit documents in this status when a document obtains this status.

    * Required fields.

    Control buttons

    Button | Description
Save | Saves the status parameters. Opens a page with the list of document statuses.
Apply | Saves the status parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Module settings (workflow) - Bitrix Site Manager - Content Management & Portal Solutions

Module settings

In this section

  • Settings tab
  • Access tab
    •

    The Settings form (System Settings -> Settings) is designed to edit the system-wide parameters of the Workflow module. For the convenience of users, the page is divided into separate tabs, each of which contains a specific set of the module parameters.

    "Settings" tab

    This form is used to set basic parameters of the Workflow module.

    Parameter | Description
Use html editor (only for IE 5.0 and higher) | When checked, allows to use the embedded HTML-editor for editing documents in the workflow mode.
Store history of file changes during the common editing (not in workflow module): | When selected, allows to save the change history of documents that are edited in common mode (without the use of workflow).
Maximum time of locking (min.): | Maximum amount of time within which a document is allowed to be locked. A locked document cannot be edited by other users.
How many days to keep document after publishing (<0 - always): | Time period (days) within which a copy of a document is stored in the Workflow module history after being assigned the Published status. Negative value means the storage period is unlimited.
Maximum number of last records in history | Maximum number of records about a document or an information block element modification stored in the Workflow module history.
How many days to keep history (<0 - always) | Maximum number of days within which the change history of a document or of an information block element is stored. Negative value forces to store the document change history forever.
Workflow administrators group | The group of workflow administrators: users entitled to edit, move, remove documents in any status as well as unlock any documents.

    "Access" tab

    This form specifies the access permissions of user groups for different sections of the Workflow module.

    Field | Description
    Default | The access level of user groups for which the default value is specified.
    User groups The user group access permission to the module resources:
    • Denied - access denied;
    • Read-only - allows to view files without modifying them;
    • Edit documents in workflow - allows to edit files in the workflow mode;
    • Full access - allows to edit documents in any status and to set module parameters (as well as manage access permission of other users).


How to create a new page in workflow - Bitrix Site Manager - Content Management & Portal Solutions

How to create a new page in workflow

  1. Click the following button on the toolbar: Create a new page in workflow [image].
  2. Select the page template (for example, Standard page or Include area).
  3. By default, the Draft state is selected. In this case the document will not be published on the site, and other users (with the Workflow right for this document) will be able to view it in the Documents administrator section or edit it. If the user has the right to edit the page (for instance, a site editor), he/she can change the document state and select Ready (for publication) or Published.
  4. In the Name field, enter the full filename. For example, /en/about/contacts.php.
  5. Type the page title. For example, Contact Information.

  6. Enter the required information. To edit text, you can use an HTML-editor, HTML-code or standard text. To select the required editing mode, click the appropriate checkbox.
  7. Select the files (images, etc.) for a new page.
    To insert links to other files (jpg, gif, pdf, etc.) into the document, you should load them into the document, i.e. if you use images in your text, type their names and paths in the Loaded files field. After the document is published, all the loaded files will be moved into the specified directories.
  8. In the Comment field, you can leave a message for other users.
  9. Click Add.

There's another way to create a new page in workflow: via the administration section. To do so, click Add in the window containing the list of documents.


Organize step-by-step editing of a news block - Bitrix Site Manager - Content Management & Portal Solutions

Enabling the step-by-step editing of a news block

Users can be granted rights to create and edit news messages. A site editor or administrator is entitled to publish news on the site. To do so, perform the following steps:
  1. In the administrator section Management -> User groups, add a user group named Authors.
  2. Add all the users entitled to create and edit news blocks to this group.
  3. In Workflow -> States, set the rights to manage news messages so that members of the Authors group are able to edit such documents (assign them the Draft state), but not publish them (assign them the Published state).
  4. In the news editing mode, give the Authors group the Workflow right.

As a result, members of the Authors group will be able to create or change news blocks but not publish them on the site. To publish them, confirmation of the site editor or administrator is required.

To confirm publication of news messages, the editor should open the news editing section and change the message state (Draft will be replaced with Published).


Polls - Bitrix Site Manager - Content Management & Portal Solutions

Polls

The Bitrix Site Manager allows for conducting polls that will help you find out the site visitors' opinion on various topics.

You can manage the poll settings: define the range of dates of conducting polls, offer the site visitors several answers to the question and many more options.

In the public section of the site, site visitors can vote and view the vote results in the form of diagrams.


Vote channels - Bitrix Site Manager - Content Management & Portal Solutions

Poll channels

This page contains information on poll channels. Each poll channel can have only one active poll (defined by the time interval of conducting polls).

Filter

To display only the required channels, set the filters according to the search criteria. The following table describes the filter fields.

Parameter | Description
Title* | The title of a required poll channel.
ID | The ID of a required poll channel.
Site | The site on which a required poll channel is used.
Active | Specifies to find only active poll channels.
Symbolic name* | the symbolic name of a poll channel.

* - in these fields you can use special logical expressions.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Create | Creates a new poll channel.
Excel | Exports data from the table to the MS Excel format.

Table of poll channels

Column | Description
Checkbox column | Used to select poll channels to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any poll channel opens a menu allowing to:
  • Edit - starts editing the poll channel;
  • Delete - deletes the poll channel.
ID | The ID of the poll channel in the database.
Modified | The date the record was last modified.
Sites | The site where the poll channel is used.
Active | Indicates the poll channel is active.
Sort. | The sorting index (can be used in the public section of the site for displaying the list of poll channels).
Mnemonic code | The symbolic name (used in the public section when displaying the current poll of the channel).
Title | The title of the poll channel .
Polls | Number of polls in the channel.
Selected | Number of channels selected from the database.
Checked | Number of marked channels.

Possible actions

The action bar contains commands that can be applied to one or more poll channels. Mark the required channels in the list and select the desired action:

Activate
Moves the selected poll channels to the active state.
Deactivate
Moves the selected poll channels to the inactive state.


Creating and editing poll channels - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing poll channels

This form is used to create and edit poll channels. There can be only one active poll in a vote channel (defined by the time interval of conducting votes).

Context bar

Button | Description
List | Opens a list of poll channels.
Create | Creates a new poll channel.
Delete | Deletes the current poll channel.
Polls | Opens a list of polls belonging to this channel.
Create a poll | Creates a new poll in this channel.

"Properties" tab

Field | Description
Modified | The date a record was last modified..
Active | Indicates the poll channel is active.
Sort index | The sorting index (can be used in the public section of the site for displaying the list of poll channels).
Sites | The site where the poll channel is used.
Mnemonic code | The name uniquely identifying a poll channel. This name can contain only Latin letters.
Title | The title of the poll channel.

"Access" tab

Field Description
Access rights of user groups This form is used to assign access permissions for vote channels to different user groups:
  • vote - voting allowed;
  • denied - all actions are denied, even voting;
  • view results - both voting and viewing results are allowed.

Upon making the required changes, do not forget to click the Save button.


Poll channel - Bitrix Site Manager - Content Management & Portal Solutions

Polls

This page contains polls (surveys etc.). Each poll can consist of one or several questions. In its turn, each question contains variants of answers of different types.

Filter

To display only the required polls, set the filters according to the search criteria. The following table describes the filter fields.

Parameter | Description
Title* | The title of the required poll.
ID* | The ID of a poll in the database.
Indicator Specifies to search for polls by the following criteria:
  • Red – the poll is inactive, or the poll is outdated.
  • Green – the poll is active, or is not outdated.
Starting date | Specified to find polls whose starting date intersects with the value of this field.
End date | Specified to find polls whose ending date intersects with the value of this field.
Poll channel* | The poll channel to which a required poll belongs.
Active flag is on | Specifies to find only active polls.
Number of votes | Specifies to find polls with a specific number of votes.

* - in these fields, you can use special logical expressions.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Create | Creates a new poll.
Excel | Exports data from the table to the MS Excel format.

Table of poll parameters

Column | Description
Checkbox column | Used to select polls to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any poll opens a menu allowing to:
  • Edit - edit the poll channel;
  • Erase - clears the poll results (votes etc.);
  • Form - views the poll form;
  • Results - views the poll results;
  • Delete - deletes the poll.
ID | The ID of the poll in the database.
Ind. Indicator:
  • Red – the poll is inactive, or the poll is outdated.
  • Green – the poll is active, or the poll is not outdated.
Start | The date the poll started or is about to start.
End | The date the poll finished or is about to finish.
Channel | The ID of the poll channel to which the poll belongs.
Active | Indicates the poll is active.
Sort. | The sorting index (can be used in the public section for displaying the list of polls).
Title | The title of the poll.
Questions | Number of questions; clicking the link adds a question.
Votes | Number of votes in this poll. The link opens a list of votes.
Selected | Number of polls selected from the database.
Checked | Number of marked polls.

Possible actions

The action bar contains commands that can be applied to one or more polls. Mark the required polls in the list and select the desired action:

Activate
Moves the selected polls to the active state.
Deactivate
Moves the selected polls to the inactive state.


Creating and editing a poll - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a poll

This form is used to edit the poll parameters. Upon entering the required information, click Save.

Context bar

Button | Description
List | Opens a list of polls.
Create | Creates a new poll.
Delete | Deletes the current poll.
Erase | Clears the poll results (votes etc.).
Questions | Opens a list of questions of the current poll.
Add a question | Opens a form in which you can create a new question for the current poll.

"Properties" tab

Field | Description
Modified | The date the record was last changed.
Number of votes | Number of votes in the current poll.
Active | Indicates the poll is active.
Notify by e-mail upon each vote | Select this checkbox if you want to automatically send an e-mail notification for every voting in the current poll.
Sorting index | Order of vote sorting at displaying it in a list.
Channel | Group to which a poll belongs.
Start date | The date the poll is to be started.
Number of days | For a new poll, you can specify the number of days within which it will be active and accessible for site visitors.
End date* | The date the poll is to finish.

"Description" tab

Field | Description
Image | You can load images in the following formats from your local computer: bmp, jpg, jpeg, jpe, gif, png.
Description Poll description in the form of:
  • Text;
  • HTML by using an embedded HTML-editor. It can be used with systems on which Internet Explorer 5.0 or higher is installed. You should also select the Use an HTML-editor checkbox in the poll module settings.

"Limits" tab

Field | Description
Not to vote twice This parameters allows for prohibiting users to vote twice.
  • <No limitations> - votes are not tracked; each user can vote the unlimited number of times.
  • In one session - a user cannot vote twice in the current session (until a browser is re-started, or a session expires).
  • In one session, or with one cookie – at the moment of voting, each voter is given a unique ID recorded in the user's cookie; this option doesn't allow users to vote twice in one session, or with one ID recorded in the cookie.
  • In one session, or with one cookie, or with one IP address – this option doesn't allow users to vote twice in one session, or with one ID, or with one IP-address (please, note that if the user is connected to the Internet via a modem (dial-up connection), he'll be given a new IP address each time an Internet connection is established).
Not to vote twice with one IP-address | If your previous choice was not to vote twice in one session, or with one cookie, or with one IP address, note that users in the local area network of the organization usually have only one external IP address. In other words, if one user in this LAN has already voted, no other user in this LAN will be able to vote. The solution to this problem can be as follows: set the time interval within which the vote module will not allow voting twice from the same IP address.

"Statistics" tab

Field | Description
Register event upon voting | If checked, an event will be registered in the Statistics module each time a voting occurs.
Event1 | The ID of the event type - event1.
Event2 | The ID of the event type - event2.
Event3 | An additional event parameter - event3.


List of questions - Bitrix Site Manager - Content Management & Portal Solutions

List of questions

This form is used to view the list of questions and perform various operations on them.

Filter

To display only the required questions, set the filters according to the search criteria. The following table describes the filter fields.

Parameter | Description
Question* | The text of a required question.
ID* | The ID of a required question.
Active | Specifies to find only active questions.
Displayed in a diagram | Specifies to find only questions included in the diagram, not included or all.

* - in these fields, you can use special logical expressions.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Create | Creates a new question in this poll.
Excel | Exports data from the table to the MS Excel format.

Table of question parameters

Checkbox column | Action menu | ID | Modified | Active | Chart | Sort. | Question
[1] | [2] | [3] | [4] | [5] | [6] | [7] | [8]
Selected: [9] | Checked: [10] |
  1. Used to select questions to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any question opens a menu allowing to:
    • Edit - starts editing the question;
    • Delete - deletes the question.
  3. The ID of the question in the database.
  4. The date the question was last modified.
  5. Indicates the question is active.
  6. Indicates the question is included in the diagram of poll results.
  7. The question sorting index.
  8. The question text.
  9. Number of questions selected from the database.
  10. Number of questions marked in [1].

Possible actions

The action bar contains commands that can be applied to one or more questions. Mark the required questions in the list and select the desired action:

Activate
Moves the selected questions to the active state.
Deactivate
Moves the selected questions to the inactive state.


Creating and editing a question - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a question

This form is used to editing poll questions. Upon making the required changes, do not forget to click Save.

Context bar

Button | Description
List | Opens a list of questions of the current poll (e.g. the poll to which the current question belongs).
Create | Creates a new question in the current poll.
Delete | Deletes the current question.

"Properties" tab

Field | Description
Channel | The channel to which the poll containing the current question belongs.
Poll | The poll to which the current question belongs.
Modified | Date of changing a record in the database.
How many times this question was answered | Number of answers.
Active | Indicates the question is active.
Sorting | The question sorting index.
Include in the result chart | Indicates the question is included in the diagram of poll results.
Result display template | A PHP script file to be used as a template for displaying the resulting diagram for the current question.
Image | An image for the question to be loaded from the local computer in the following formats: jpg, bmp, ,jpeg, jpe, gif, png.

"Question" tab

Field | Description
Question | The text of the question.

"Answers" tab

ID | Message | Field type | Width | Height | Parameters | Sorting | Color | Active | Del. |
[1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | [10] | [11]
  1. The ID of the answer variant in the database.
  2. The text to be displayed beside to the answer.
  3. Field type.
    • radio button – only one variant can be selected from the group of answers;
    • checkbox – more than one variants can be selected;
    • dropdown – a list from which you can select only one variant; all the elements of this type will be displayed as a dropdown list;
    • multiselect – a list from which you can select several variants; all the elements of this type will be displayed in a list;
    • text – a one-string field where you can type your answer;
    • textarea – a multi-string field where you can type your answer.
  4. For different controls, this field has different meaning:
    • radio, checkbox, dropdown, multiselect – not applicable;
    • text – attribute size of the tag <input type=text>
    • textarea – attribute cols of the tag <textarea>
  5. For different controls, this field has different meaning:
    • text, radio, checkbox, dropdown, multiselect – not applicable;
    • multiselect – attribute size of the tag <select multiple>
    • textarea – attribute rows of the tag <textarea>
  6. Additional parameters of the input tag: style, class. For example, style="width:100%".
  7. The sorting index which is used when displaying the answer in the poll form and in the resulting diagram.
  8. Color of a diagram element (to select the required color, click the square box to the right of the field).
  9. Indicates the question is active.
  10. Option: if selected, the answer variant will be deleted upon save.
  11. Popularity of the current answer variant for the poll (used for diagram drawing).


Site visitors - Bitrix Site Manager - Content Management & Portal Solutions

Site visitors

This page contains information on site visitors participating in polls. In this table you will find three identifiers:

  1. The ID issued by the poll module at the moment of voting.
  2. The user ID with which the user has been authorized at the moment of voting.
  3. The visitor ID issued by the statistics module. It helps you track this user's actions in the Statistics module.

Filter

To display only the required visitors, set the filters according to the search criteria. The following table describes the filter fields.

Parameter | Description
User ID, login, first and last names * | Mask for the first and last names of the authorized user, or the user ID.
ID | The ID of the visitor in the Polls module.
First poll date | Range of dates when the sought user first participated in polls.
Last poll date | Range of dates when the sought user last participated in polls.
Visitor ID in the statistics module * | The ID issued by the Statistics module.
IP address * | Mask for the last IP address from which the user voted.
Number of votes | Range of number of replies of the sought user(s).
Poll * | Poll in which site visitors participated.

* - in these fields, you can use special logical expressions.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Excel | Exports data from the table to the MS Excel format.

Table

Checkbox column | Action menu | ID | First | Last | Visitor | IP | Number of votes
[1] | [2] | [3] | [4] | [5] | [6] | [7] | [8]
Selected: [9] | Checked: [10] |
  1. Used to select visitors to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any visitor opens a menu allowing to delete the visitor.
  3. The visitor ID issued by the vote module.
  4. The date of the first vote of the user.
  5. The date of the last vote of the user.
  6. The authorised user ID; first and last names; the visitor ID issued by the Statistics module.
  7. IP address from which the visitor voted the last time. The link follows to the RIPN server where you can obtain additional information on the IP address.
  8. Number of user's votes; the link follows to the vote page with the filter enabled.
  9. Number of records selected from the database.
  10. Number of records marked in [1].


Site visitors' votes - Bitrix Site Manager - Content Management & Portal Solutions

Site visitors' votes

This page contains information on the votes of site visitors. You can use this form to view the results of each vote, select whether the vote is valid or not. If the vote validity option is not checked, its results are not displayed in the resulting diagram.

Filter

To display only the required votes, set the filters according to the search criteria. The following table describes the filter fields.

Parameter | Description
ID* | The ID of the sought vote.
Visitor ID* | The visitor ID issued by the poll module.
Session ID* | The ID issued by the statistics module.
IP address* | Mask for the IP address from which the user voted.
Date | Range of dates for which the votes are to be selected.
Poll* | The poll ID or name.
Valid | Specifies to find only valid votes, invalid ones or all.

* - in these fields, you can use special logical expressions.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Excel | Exports data from the table to the MS Excel format.

Table

Checkbox column | Action menu | ID | Visitor | Session | IP | Date | Poll | Valid
[1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9]
Selected: [10] | Checked: [11] |
  1. Used to select votes to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any vote opens a menu allowing to view of delete the vote.
  3. The ID of the vote in the database.
  4. The visitor ID issued by the Polls module.
  5. The session ID issued by the Statistics module.
  6. IP address from which a visitor voted.
  7. The date the vote occurred.
  8. The ID and name of the poll.
  9. Indicates the vote is active.
  10. Number of votes selected from the database.
  11. Number of votes marked in [1].

View vote results

Viewing the vote results means displaying the vote form with variants of answers selected by the user at the moment of voting. You can select or deselect the checkbox of the vote validity.


Settings - Bitrix Site Manager - Content Management & Portal Solutions

Settings

The Settings form of the Polls module is used to customize the module settings.

"Settings" tab

Parameter | Description
Use an HTML-editor (only for IE 5.0 or FireFox 1.0 or higher): | Use this checkbox to define whether you want to use an HTML-editor to edit the poll description.
Relative path to the question result view templates | Path (relative to the site root) to the templates for displaying the resulting diagrams on every question.

"Access" tab

  • Access denied – no access to the module menus and administrator files.
  • Read – access to menus is granted; one can view administrator files in the read-only mode.
  • Write – full access.

All permissions are inheritable.


Create a new survey - Bitrix Site Manager - Content Management & Portal Solutions

Create a new survey

Creating a new survey (aka poll) involves several stages.

  • Create a poll channel
  • Create a poll
  • Set poll options

Create a poll channel
  1. Open the Poll Channels form and click Create new. A poll channel can have only one active poll (defined by the interval of conducting polls).

  2. Select the Active checkbox and define the sorting order.
  3. Select the interface language for the polls of the channel being created.
  4. The poll channel symbolic name must be specified.
  5. Set access rights for the poll channel being created.

  6. Click Save.

Create a poll
  1. In the Poll channels form, choose the row containing the just created poll channel, and click the plus sign + in the Polls column.
  2. The Active field is selected by default. If you do not want the poll to be accessible right after its creation, deselect this checkbox.
  3. Select Notify by e-mail upon each vote if you want to be notified via the e-mail every time a vote occurs.
  4. Type the poll title (it will be visible in the public section of the site).
  5. Specify the start and end dates and the duration of the poll. The start date is set automatically: its' the end date of the last poll + 1 second. The start date of the new poll should not overlap with the end date of another poll in the same channel.
  6. Specify the poll identifiers. All responses will be recorded as events in the statistics (event 1, 2, 3).

  7. On the Limits tab, specify how the unique visitors should be registered.

    You can choose from:
    • no limitations - site visitors are not tracked; each visitor can vote as many times as they want;
    • within one session - a user can vote only once in the current session, i.e. until a browser is re-started, or a session expires;
    • within one session, or with one cookie – at the voting time, each visitor is given a unique number (just once) recorded in the visitor's cookie; this option doesn't allow the same user to vote twice in the same session, or with the same unique number in the cookie;
    • within one session, or with one cookie, or with one IP address – this option doesn't allow for voting twice in the same session, or with the same unique number, or by using the same IP address (please, note that if the user is connected to the Internet via a modem (dial-up connection), he's most likely to be given a new IP address each time an Internet connection is established).
    If you have selected not to vote twice in one session, or with one cookie, or with one IP, bear in mind that users of the same organization using the same local area network usually have only one external IP-address. In other words, if one user in this LAN has already voted, no other user in this LAN will be able to respond to this poll. That's why you should specify a range of dates within which the vote module will not allow voting twice from the same IP address.
  8. Load an image to be published in the public section of the site in the poll channel.
  9. Add a poll description. You can use an HTML-editor, add an HTML-code or standard text.
  10. Select the templates for the form and poll results. Use the Select link to view a template for forming a poll.
  11. Click Add to save the newly created poll and go to the poll channel. Use the Apply button to save the changes you've made to continue editing a poll.

Set poll options
  1. In the Poll list form, choose the row containing the just created poll, and click the plus sign + in the Questions column.
  2. Specify whether the poll is active or not and define the order of sorting.
  3. Select Add to a results diagram to include responses to this question to the poll results.
  4. Select the template for viewing poll results.
  5. You can load an image to be visible in the public section of the site next to this question.
  6. Type your question and possible answers.

    Types of fields (to select answers to the question):
    • radio-button; you can select only one variant from the group of answers;
    • checkbox – you can select several variants;
    • dropdown – a list from which you can select only one variant; all the elements of this type will be displayed as a dropdown list;
    • multiselect – a list from which you can select several variants; all the elements of this type will be displayed as a dropdown list;
    • text – one-string field where you can type your answer;
    • textarea – multi-string field where you can type your answer.
  7. Click Add.

You can view data on the respondents' answers by clicking Results in the poll channel.

The Visitors section contains information about all the respondents. In Votes, you can view the results of voting of each respondent.


Web Forms - Bitrix Site Manager - Content Management & Portal Solutions

Web Forms

In this topic

  • Functions of the web-forms module
  • Storing the structure of web forms (further "forms")
  • Form questions and fields
  • Form questions
  • Form fields
    •
  • Displaying forms
  • Storing, displaying, filtering and modifying the data collected by forms
  • E-mailing filled forms
  • Assigning user rights to various actions on the forms and form results
    •

    Application

    The Web Forms module can be used for:

    • storing comments or queries of site visitors;
    • storing and searching site visitors’ callback forms;
    • processing of information in forms, etc.

    Samples demonstrating search and storage of site visitors’ review forms are included in the module distribution kit.

    Integration with the Statistics module allows to use the module functions to analyze the dynamics of forms filling and to acquire other information about visitors who fill in forms.

    Integration with the e-Store module allows to organize sale of various goods and services by means of filling out web review forms and transferring the acquired information to the marketing module.

    Functions of the web-forms module

    Storing the structure of web forms (further "forms")

    By using the system administrative interface, you can create the required questions and form fields.

    To create a form, the following data must be specified:

    • Form identifier;
    • Name;
    • Administrative site section menu options providing access to the result table;
    • User access rights for this form (see below) and other.

    You can define the templates for:

    • Displaying the form;
    • Displaying the result;
    • Printing the result;
    • Modifying the result;
    • Defining a mail template designed for e-mailing the result (automatic generation of the mail templates is provided).

    The statistics module maintains the facts of filling and saving the forms through the event registration mechanism. In addition, this allows to track form filling activity dynamics on days and to draw a corresponding graph. To do it, you need to specify event type identifiers for the statistics module in the form settings.

    Form questions and fields

    After form creation questions and fields of the form can be generated.

    The form question is the collection of the question text and input fields for entering the answer to this questions.

    The form field is intended for the storage of the data defined after saving the filled form (after saving the result).

    Form questions

    To create a form question, the following data should be specified:

    • Identifier;
    • Whether an answer is required;
    • Sorting order;
    • Activity checkbox;
    • Question text (including an HTML editor);
    • Comment;
    • Various input fields.

    The following input fields are available:

    • text (single line text);
    • textarea (multi line text);
    • multiselect (multiple selection);
    • dropdown (single selection);
    • Radio buttons set (single choice – alternative);
    • checkbox buttons set (multiply choice);
    • Fields for the file input;
    • Fields for the date with built-in calendar input.

    In addition, you can specify the following:

    • Necessity to display answers to this question in the result table;
    • Parameters and fields of a table filtering by this question.

    The following filter fields types are available:

    • single line text field;
    • range of numbers;
    • range of dates;
    • single choice dropdown list.

    Form fields

    To create a field, specify its identifier, sorting order, heading, service comment and type:

    • text;
    • integer;
    • date.

    You can also specify the following:

    • Necessity to display the data stored in this field in the result table. You can optionally specify whether it's required to display in the filter field for filtering the results by the values stored in this field or not. The filter fields will be selected according to the field type:
    • text type complies with the single line filter text field;
    • integer type complies with the range of numbers;
    • date - type complies with the range of dates;

    Single line filter text allows to use logical expressions. The logical expressions syntax is:

    • & (logical AND);
    • | (logical OR);
    • ~ (logical negation);
    • () - parentheses for conditions grouping.

    Logical operation priorities in filter fields are identical to the ones in mathematic.

    Displaying forms

    To display a form, a standard all-purpose template default.php or personal unique template implementing the required logic (for example, by means of JavaScript) can be used.

    Storing, displaying, filtering and modifying the data collected by forms

    The result is the collection of data collected in the forms and saved in the database. To display the collected results in the public sections of the site, the module API can be used along with samples provided in the distribution kit. The module core is implementing the form results display in the administrative site. You can filter the result fields, form questions and sort result fields when displaying the form results.

    Result fields are:

    • Result ID;
    • Result creation date;
    • Result modification date;
    • Result creator ID;
    • Visitor ID and Session ID, when the result was created (allow to track the visitors’ behavior through the statistics module and obtain additional information about this visitor);
    • Result status.

    E-mailing filled forms

    To e-mail the form results, a special mail template must be specified in the form settings. The Create link in the mail template field generates a mail template. Upon filling and saving the form you can use the CForm::Mail function (included in the module API) for sending the data via e-mail.

    Assigning user rights to various actions on the forms and form results

    The module supports the following access rights types for each form. Each subsequent access right type includes all the previous ones.

    Access right | Description
Access denied | Form and its results are totally inaccessible.
Form filling | Visitor can only fill in and save the form.
Work with the result according to its status | Visitor can operate only with the results according to the rights set for each status.
Work with all the results according to their statuses | Visitor can operate with all the results according to the rights set for each status.
Viewing the form parameters | Visitor gains the opportunity to view web-form parameters.
Full access | Includes all the above-described rights and also the rights to modify the form settings.

    Each form result must have a definite status (for example: accepted to consideration, published, draft and so on). On each web-form you can define the personal statuses set allowing to organize for each result the specific functions of workflow. In the status settings, you can define access rights both for various user groups and for the result creator. There are four actions types for which you can define access rights:

    • The right to view the results in the current status;
    • The right to edit the results in the current status;
    • The right to delete the results in the current status;
    • The right to assign the current status.

    To assign access rights in web form module, complete the following:

    1. Assign the access level for the entire web-form.
    2. Create the list of statuses for the web-form results.
    3. Define access rights for each status.


List of forms - Bitrix Site Manager - Content Management & Portal Solutions

List of forms

In this section

  • Filter
  • Context bar
  • List of forms
    •

    The List of forms page (Services -> Web Forms -> Manage) contains the list of all web forms and allows to:

    • view the table of parameters of existing forms;
    • create new forms;
    • edit form settings;
    • delete forms.

    Filter

    This form is used to find web forms matching the specified criteria.
    Field | Description
Title | The web form title.
ID | The unique ID of the form.
Sites | Sites on which the form is used.
Symbolic identifier | The symbolic code of the form. The field is displayed in the extended editing mode.
Description | The form description.

    To filter web forms by the specified search criteria, click Set filter. To have all web forms displayed, click Cancel.

    Context bar

    Button | Description
Create | Opens a form in which you can create a new web form.
Excel | Exports data from the table to the MS Excel format.

    List of web forms

    Column | Description
    Checkbox column | Selects web forms to which the desired actions are to be applied.
    Action menu
             Actions on the web form:
    • Modify - edits the web form;
    • Copy - copies the web form;
    • Erase - erases all the web form results;
    • Delete - deletes the web form.
    ID | The unique ID of the form.
    Sites | Sites on which the form is used.
    Sort. | The web form sort weight. Defines the form position in lists.
    Title | The web form title.
    Questions | Opens a page containing the list of form questions. The link "+" opens the new question creation form.
    Fields Opens a page containing the list of form fields. The link "+" opens the new field creation form.

    The field is displayed in the extended editing mode.
    Statuses Opens a page containing the list of form statuses. The link "+" opens the new status creation form.

     The field is displayed in the extended editing mode.
    Results | Opens a page containing the list of form results. The link "+" opens the new result creation form.


Creating and editing web forms

In this section

  • Context bar
  • Editing form
  • Properties
  • Description
  • Template
  • Statistics
  • Access
    •
  • Control buttons
    •

    This page is designed to create new web forms and edit the parameters of existing ones.

    The system provides the following two editing modes:

    • simple mode - stipulates the simplified procedure of creating and editing web forms (without using fields, statuses for the web form results and creating the templates for filtering and displaying the list of the web form results);
    • extended mode - provides interface allowing to customise all the web form parameters: create fields, edit web form results, and also connect custom templates for filtering and displaying the list of the web form results.

    You can choose the web form creation and editing mode on the module settings page.

    Context bar

    Button | Description
List | Opens a form containing the list of web forms.
Create | Creates a new web form in this page. The button is displayed when editing the existing form only.
Copy | Duplicates the current web form into a new one.
Clear | Deletes all the web form results. The button is displayed when editing the existing form only.
Delete web form | Deletes the current web form.
Statuses | Opens a form containing the list of web form statuses. The field is displayed in the simple editing mode only.
Questions | Opens a form containing the list of web form questions. The button is displayed when editing the existing form only.
Fields | Opens a form containing the list of web form fields. The field is displayed in the simple editing mode only.
Results | Opens a form containing the list of web form results. The button is displayed when editing the existing form only.

    Editing form

    "Properties" tab
    Field | Description
*Name | The name of the form.
Sorting | The web form sort weight. Defines the form position in lists.
Menu items in admin section | Menu items linked to a form results page. Names of the menu items are specified for all languages of the interface.
Form sites | Sites on which the web form is used.
Send form results by email | Check this box if you want to have the web form results sent by e-mail every time the web form is filled in. After the web form parameters are saved, a new e-mail template will be automatically generated, which will be used to send messages. To view the list of available templates click the [template list] link. The field is displayed in the simple editing mode only.
Button text | The caption to be printed on the button which saves the web form results. For example: Send or Save.

    * - Required fields.

    "Description" tab
    Field | Description
Image | Image used in the form description in the site public section. Click Browse to select image.
Description | The form description text. The created description will be displayed together with the web form in the site public section.
    "Template" tab

    The tab is displayed in the extended editing mode only.

    This form is used for customising templates used with web forms.

    Field | Description
E-mail template | The templates used for sending the result via e-mail.
For the filter of the result table in administrative section | Path to the template used for filtering the web form results in the administrative section.
For result table in administrative section | Path to the template used for displaying the result table in the administrative section.
    "Statistics" tab

    This tab serves to specify identifiers with which the web form filling will be registered in the statistics module.

    Field | Description
Event1 | The event type identifier – event1
Event2 | The event type identifier – event2
Event3 | The auxiliary event parameter.
    "Access" tab

    This form serves for customising the user group permissions to access to the web form.

    Field Description
    [User group] User group access permission for the form. Each subsequent permission includes all previous ones.
    • access denied - form and its results are totally inaccessible;
    • filling in the form - a visitor can only fill in and save forms;
    • edit own result according to its status - a visitor has the right to work only with their results according to the rights set for each status assigned to a result;
    • edit all results according to their statuses - a visitor has the right to work with all results according to the rights set for each status assigned to a result;
    • view form parameters - includes all the above rights and also the right to view web form parameters;
    • full access - includes all the above rights and also the rights to modify form settings.

    Control buttons

    Button | Description
Save | Saves the form parameters. Opens the page with the list of forms.
Apply | Saves the form parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


List of questions - Bitrix Site Manager - Content Management & Portal Solutions

List of questions

In this section

  • Filter
  • Context bar
  • List of questions
    •

    This page displays the list of web form questions. A form question is the aggregate of a question text and input fields accepting an answer.

    Filter

    This form is used to find web form questions matching the specified criteria.

    Field | Description
    Question* | The question text (or a part of it).
    ID* | The ID of the required question.
    Active | Specifies whether the required question is active or not.
    Symbolic identifier* | The symbolic identifier of the question.
    Comment* | The administrator's comment (or a part of it).
    Required | Indicates that the answer to this question is mandatory.
    Included in the result table | Specifies to find only those answers that are displayed in the table of results.
    Included to results table in Excel format | Specifies to find only those answers that are displayed in the Excel table of results.
    Included in filter of the result table | Specifies to find only those answers that are included in the filter of the result table.
    Filter between-field logic The type of logic used when filtering the field values:
    • and: filter result must match all conditions;
    • or: filter result may match only one condition.

    * - in these fields, you can use special logical expressions.

    To filter questions by the specified search criteria, click Set filter. To show all questions, click Cancel.

    Context bar

    Button | Description
Add | Opens a page in which you can create a new question for the selected web form.
Form parameters | Opens a page in which you can edit parameters of the web form whose list of questions is displayed on this page.
Results | Opens a page containing the list of form results.
Excel | Exports data from the table to the MS Excel format.

    List of questions

    Column | Description
    Checkbox column | Selects questions to which the desired actions are to be applied.
    Action menu
             Actions on the question:
    • Question parameters - edits the question parameters;
    • Copy - duplicates the question;
    • Delete - deletes the question.
    ID | The ID of the question.
    Active Specifies whether the question is active or not.

    The field is displayed in the extended editing mode.
    Sort. | The question sort weight. Defines the question position in lists.
    Req. | Indicates that the answer for this question is mandatory.
    Symbolic identifier The symbolic code of the question.

    The field is displayed in the extended editing mode.
    Question | The question text.
    Field type The type of the field for answer.

    The field is displayed in the simple editing mode.
    Comment | The administrator's comment.
    Table | Specifies whether the answers are displayed in the table of results or not.
    Excel | Specifies whether the answers are displayed in the Excel table of results or not.


Question parameters - Bitrix Site Manager - Content Management & Portal Solutions

Question parameters

In this section

  • Context bar
  • Simple editing form
  • Extended editing form
  • Control buttons
    •

    This form is used to create and edit a form question.

    Context bar

    Button | Description
Questions | Opens a page containing the list of form questions.
Create | Opens a form in which you can create a new form question. The button is displayed when editing the existing question only.
Copy | Duplicates the current question into a new one. The button is displayed when editing the existing question only.
Delete | Deletes the current question. The button is displayed when editing the existing question only.
Statuses | Opens a page containing the list of form statuses. The button is displayed in the extended editing mode.
Fields | Opens a page containing the list of form fields. The button is displayed in the extended editing mode.
Results | Opens a page containing the list of form results.

    Simple editing form

    "Properties" tab
    Field | Description
    Form | The form to which the question belongs. The field is displayed when editing the existing question only.
    Modified | The date the question was last modified.
    Active | Specifies whether the question is active or not.
    Sorting | The question sort weight. Defines the question position in lists.
    Image | The image that will be displayed next to the question.
    Question | The question text.
    Required | Indicates that the answer for this question is mandatory.
    Type of answer field The type of the answer field:
    • text - single-line text;
    • textarea - multiple line text;
    • multiselect - the list of multiple choice variants;
    • dropdown - the list of single choice variants;
    • radio - a set of radio buttons (single choice);
    • checkbox - a set of checkbox buttons (multiple choice);
    • image - image field;
    • date - date input field with the embedded calendar;
    • file - file submit field;
    • password - password entry field.
    Size The size of the answer field:
    • Field width; available for the following field types: text, textarea, image, date. Denotes the number of columns.
    • Field height; available for the following field types: textarea, multiselect. Denotes the number of rows.
    Answer The answer variant; used in dropdown, multiselect, radio, checkbox fields; for other field types you must leave this field blank.
    Field | Description
Answer variants | The answer variant.
Sort order | The answer variant sort weight. Defines the variant position in lists.
Default | If checked, this answer will be used by default.
    "Comment" tab

    The administrator's comment to the question. The comment will be displayed only in the administration section.

    Extended editing form

    "Properties" tab
    Field | Description
Form | The form to which the question belongs. The field is displayed when editing the existing question only.
Modified | The date the question was last modified.
Active | Specifies whether the question is active or not.
Sorting | The question sort weight. Defines the question position in lists.
*Symbolic identifier | The answer symbolic code. Only Latin letters can be used here.
Required | Indicates that the answer for this question is mandatory.

    * - Required fields.

    "Question" tab
    Field | Description
Image | The image that will be displayed next to the question.
Question text | The text of the current question.
    "Answer" tab

    This form allows to create fields to be used for entering the answer, or possible answer variants.

    Field | Description
    ID | The ID of the answer field.
    Text
    ANSWER_TEXT     		The answer text; used in dropdown, multiselect, radio, checkbox fields; for other field types, enter a space here.
    Value
    ANSWER_VALUE     		Additional parameter which can be used for a definite answer identification (for example: in lists).
    Field type The type of the answer field:
    • text - single-line text;
    • textarea - multiple line text;
    • multiselect - the list of multiple choice variants;
    • dropdown - the list of single choice variants;
    • radio - a set of radio buttons (single choice);
    • checkbox - a set of checkbox buttons (multiple choice);
    • image - image field;
    • date - date input field with the embedded calendar;
    • file - file submit field;
    • password - password entry field.
    Width | Field width; available for the following field types: text, textarea, image, date. Denotes the number of columns.
    Height | Field height; available for the following field types: textarea, multiselect. Denotes the number of rows.
    Parameters This field can be used to specify input element attributes and styles, and to assign special identifiers:
    • SELECTED – if specified, this attribute causes the option to be selected; available for: multiselect, dropdown, radio, checkbox;
    • NOT_ANSWER - this attribute means that the given option is not an answer, but a plain text; the option will not be considered as the answer to a mandatory question. Available for: dropdown, radio, multiselect, checkbox;
    • NOW_DATE - displays the current date in the date field;
    • NOW_TIME - displays the current time in the date field.
    Sort. | The variant sort weight. Defines the variant position in lists.
    Active. | Specifies whether the field is active or not; if unchecked, the field cannot be viewed in the public section.
    Del. | Check this field and click Apply to delete the answer variant.
    "Results" tab

    The tab serves to customise the parameters of the answer result display.

    Field | Description
Show in the result table | If checked, answers for this question will be displayed in the HTML result table.
Show in the Excel result table | If checked, answers for this question will be displayed in the Excel result table.
Column header in the result table | The text which will be displayed in the result table as a title of the column containing the answers for this question.
    "Filter" tab
    Filter fields
    for entered value Types of the result table filter fields which can be used to find answers typed by users in the following types of fields: text, textarea. The following options are available in the filter:
    • single-line text field;
    • range of numbers;
    • range of dates;
    • answer exists.
    for parameter ANSWER_TEXT Types of the filter fields which can be used to find ANSWER_TEXT parameter values in visitor’s answers. The following options are available in the filter:
    • single-line text field;
    • range of numbers;
    • drop-down list containing all ANSWER_TEXT values;
    • answer exists.
    for parameter ANSWER_VALUE Types of the filter fields which can be used to find ANSWER_VALUE parameter values in visitor’s answers. The following options are available in the filter:
    • single-line text field;
    • range of numbers;
    • drop-down list containing all ANSWER_VALUE values.
    • answer exists.
    Title of the filter field Text that will be displayed beside the selected filter fields in the result table.
    "Comment" tab

    The administrator's comment to the question. The comment will be displayed only in the administration section.

    Control buttons

    Button | Description
Save | Saves the question parameters. Opens the page with the list of questions.
Apply | Saves the question parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


List of fields - Bitrix Site Manager - Content Management & Portal Solutions

List of fields

In this section

  • Filter
  • Context bar
  • List of fields
  • How to create a field
  • How to modify a field
    •

    This page contains the list of additional form fields. The form field implies the storage of various data, provided after the completed form is saved (after saving the result).

    Filter

    This form is used to find web form fields matching the specified criteria.

    Field | Description
    Title* | The field title.
    ID* | The field ID.
    Active | Specifies whether the field is active.
    Symbolic identifier* | The symbolic identifier of the field.
    Comment* | The administrator's comment.
    Included in result table | Specifies whether to find only those field values that are displayed in the result table.
    Included to results table in Excel format | Specifies whether to find only those field values that are displayed in the Excel result table.
    Included in filter of the result table | Specifies whether to find only those field values that are included in the filter of the result table.
    Filter between-field logic Specifies the type of logic used when filtering the field values:
    • and: elements matching all criteria will be displayed;
    • or: elements matching at least one criteria will be displayed.

    * - in these fields, you can use special logical expressions.

    To filter fields by the specified search criteria, click Set filter. To show all fields, click Cancel.

    Context bar

    Button | Description
Add | Creates a new field.
Form parameters | Opens a page in which you can edit web form parameters.
Results | Opens a page containing the list of web form results.
Excel | Exports data from the table to the MS Excel format.

    List of fields

    Column | Description
    Checkbox column | Selects fields to which the desired actions are to be applied.
    Action menu
             Actions on the field:
    • Question parameters - edits the field parameters;
    • Copy - duplicates the field into a new one;
    • Delete - deletes the field.
    ID | The field ID.
    Active | Specifies whether the field is active or not. If the field is inactive, it will not be available in the result table and in the filter of the result table.
    Sort. | The field sort weight. Defines the field position in lists.
    Symbolic identifier | The symbolic code of the field. Only Latin letters are possible here.
    Title | The field title.
    Type The field type:
    • text - the field has the text value;
    • integer - the field has the integer numeric value;
    • date - the field has the date value.
    Comment | The comment describing the field value meaning.
    Table | Specifies the field is to be displayed in the result table.
    Excel | Specifies the field is to be displayed in the Excel result table.

    How to create a field

    To create a new field, click the Add button on the context bar.

    How to modify a field

    To modify a field, click Question parameters in the Action menu of the corresponding field.


Field parameters - Bitrix Site Manager - Content Management & Portal Solutions

Field parameters

In this section

  • Context bar
  • Editing form
  • Properties
  • Results
  • Filter
  • Comment
  • Control buttons
    •

    This form is used to create and modify form fields.

    Context bar

    Button | Description
Fields | Opens a page containing the list of form fields.
Create | Opens a form in which you can create a new form field. The button is displayed when editing the existing field only.
Copy | Duplicates the current field into a new one. The button is displayed when editing the existing field only.
Delete | Deletes the current field. The button is displayed when editing the existing field only.
Statuses | Opens a page containing the list of form statuses.
Questions | Opens a page containing the list of form questions.
Results | Opens a page containing the list of form results.

    Editing form

    "Properties" tab
    Field | Description
    Form | The form to which the field belongs.
    Modified | The date the field was last modified. The field is displayed when editing the existing field only.
    Active | Specifies whether the field is active or not.
    Sorting | The field sort order. Defines the field position in the result table and in filter.
    *Symbolic identifier | The field symbolic code. Only Latin letters can be used here.
    Field type Allows to store data in the specified format, and to select fields in filter:
    • text - the single-line text field in filter;
    • integer - the numeric in filter;
    • date - the date range in filter.
    Title | The field title.

    * - Required fields.

    "Results" tab

    The tab serves to customise the parameters of the field value display.

    Field | Description
Show in the result table | If checked, the field values will be displayed in the HTML result table.
Show in the Excel result table | If checked, the field values will be displayed in the Excel result table.
Column header in the result table | Text, which will be displayed in the result table as a title of the column containing the field values.
    "Filter" tab

    This form serves to customise filter fields which will be used to search records by the field value.

    Field | Description
    Filter fields The types of fields by whose values the elements of the List of forms page will be filtered. The following options are available in the filter:
    • single-line text field;
    • range of numbers;
    • range of dates;
    • field exists.
    Title of the filter field | Text to be displayed beside the selected filter fields in the result table.
    "Comment" tab

    This form allows to create the administrator's comment to the field.

    Control buttons

    Button | Description
Save | Saves the field parameters. Opens the page with the list of fields.
Apply | Saves the field parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


List of statuses - Bitrix Site Manager - Content Management & Portal Solutions

List of statuses

In this section

  • Filter
  • Context bar
  • List of statuses
  • How to create a status
  • How to modify a status
    •

    This page contains the list of form statuses. Each form result can be assigned a definite status, for example: accepted to consideration, published, rejected etc. For each status, you can assign different access rights for user groups and for the result creator, individually.

    Filter

    This form is used to find web form statuses matching the specified criteria.

    Field | Description
ID* | The status ID.
Active | Specifies whether the status is active or not.
Title* | The status title.
Description* | The description of the status.
Results | Range that allows to filter statuses by the number of results.

    * - in these fields, you can use special logical expressions.

    To filter statuses by the specified search criteria, click Set filter. To show all statuses, click Cancel.

    Context bar

    Button | Description
Add | Opens a form in which you can create a new status.
Excel | Exports data from the table to the MS Excel format.

    List of statuses

    Column | Description
    Checkbox column | Selects statuses to which the desired actions are to be applied.
    Action menu
             Actions on the status:
    • Modify - edits the status parameters;
    • Copy - duplicates the status into a new one;
    • Delete - deletes the status.
    ID | The status ID.
    Modified | The date the status was last modified.
    Active | Specifies whether the status is active or not.
    Sort. | The status sort weight. Defines the field position in lists.
    Default | Specifies the status is assigned to all newly created results by default.
    Title | The status title.
    Description | The description of the status.
    Results | The number of results in this status. The link opens the list of these results.

    How to create a status

    To create a new status, click the Add button on the context bar.

    How to modify a status

    To modify a status, click Modify in the Action menu of the corresponding status.


Status parameters - Bitrix Site Manager - Content Management & Portal Solutions

Status parameters

In this section

  • Context bar
  • Editing form
  • Properties
  • Access
  • Control buttons
    •

    This form is used to create and modify statuses.

    Context bar

    Button | Description
Statuses | Opens a page containing the list of form statuses.
New status | Opens a page where you can create a new form status. The button is displayed when editing an existing status only.
Copy | Duplicates the current status into a new one. The button is displayed when editing an existing status only.
Delete status | Deletes the current status. The button is displayed when editing an existing status only.
Questions | Opens a page containing the list of form questions.
Fields | Opens a page containing the list of form fields.
Results | Opens a page containing the list of form results.

    Editing form

    "Properties" tab
    Field | Description
Form | The form with whose results this status is used.
Modified | The date and time when the status was last modified.
Results in this status | The number of results in the current status.
Active | Specifies whether the status is active or not.
*Title | The status title.
Description | The description of the status.
Sorting | The field sort order; can be used, in particular, when displaying the status drop-down list.
Set this status to all new documents by default | Check this field to assign the current status to all new documents, if no status is assigned to them.
CSS class used to display the status title | A CSS style class with which the status title is to be displayed. Can be used in the result table and while viewing or editing statuses using default.php templates.
File handler called upon status change or result deletion | Path to the file handler which is run when a status is changed.
File handler called upon change in status to the current (or adding the result) | Path to the file handler which is run when any status is replaced with the current one. For more information see Status processing.

    * - Required fields.

    "Access" tab

    This form serves for customising the user group permission to access results in the current status.

    Field | Description
Can assign this status to results [MOVE] | The user groups whose members can assign the status being edited to the result. Also, you can assign this right to the result creator, individually. Users must have editing permissions.
Can view results in this status [VIEW] | The user groups whose members can view the result in the current status. Also, you can assign this right to a result creator, individually.
Can edit results in this status [EDIT] | The user groups whose members can edit results in the current status. Also, you can assign this right to a result creator, individually.
Can delete results in this status [DELETE] | The user groups whose members can delete results in the current status. Also, you can assign this right to the result creator, individually.

    Control buttons

    Button | Description
Add | Saves the status parameters. Opens the page with the list of statuses.
Apply | Saves the status parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Form results - Bitrix Site Manager - Content Management & Portal Solutions

Form results

In this section

  • Filter
  • Context bar
  • List of results
  • Editing the result
  • Viewing the result
    •

    This page displays form results.

    Filter

    This form is used to find web form results matching the specified criteria.

    Field | Description
ID* | The result ID.
Created | The date the result was created.
Modified | The date the result was modified.
Registered user | Specifies whether the visitor who filled in the form was registered or not.
Authorised user | Specifies to find results of visitors who was authorized, or not authorized.
User ID* | The ID, login, first and last names of the visitor who filled in the form.
Visitor ID* | The visitor ID as assigned by the Statistics module.
Session ID* | The session ID as assigned by the Statistics module.
Status | The status result.
Status ID | The status result ID.
The form questions field filters

    * - in these fields, you can use special logical expressions.

    To filter the results by the specified search criteria, click Set filter. To show all results, click Cancel.

    Context bar

    Button | Description
Add | Opens a form in which you can create a new result.
Form parameters | Opens a form in which you can edit web form parameters.
Questions | Opens a form containing the list of web form questions.
Excel | Exports data from the table to the MS Excel format.

    List of results

    Column | Description
    Checkbox column | Selects results to which the desired actions are to be applied.
    Action menu
             Actions on the result:
    • View - shows the result details;
    • Modify - edits the result;
    • Delete - deletes the result.
    ID | The result ID.
    Status | The status assigned to the current result.
    Modified | The date the result was modified.
    Modified by | The login, first and last names of the visitor who was the last to create or modify the result. If the visitor is not registered, the appropriate message is displayed.
    Visitor | The visitor ID as assigned by the Statistics module.
    Session | The session ID as assigned by the Statistics module.
    [Form questions] | Answers to form questions.

    Editing the result

    You can edit results by using templates. For example, the default.php template is shipped with the module. After a result is edited, the Modified field gets updated. You can also save the selected template as a default template for editing the results of this form.

    Only those users who have the access permission not lower than "edit all results according to their statuses" and "view form parameters" can edit the result. Users with the "edit personal result" access permission can edit only their result.

    Viewing the result

    You can view results by using templates; e.g. the default.php template. If the a visitor has access permission not lower than "edit all results" and "view form parameters", they can view not only the result itself but also the information concerning the result owner's data for the moment of filling in the form: the visitor and session ID's as assigned by the Statistics module, and other information.


Module settings - Bitrix Site Manager - Content Management & Portal Solutions

Module settings

This form (Settings -> System settings -> Module settings) is intended to alter system parameters of the Web forms module.

"Settings" tab

Field | Description
Use HTML editor (for IE 5.0 or higher) | If checked, the built-in HTML editor is used when editing form questions and properties.
Use simple form edit mode | If checked, stipulates the use of the simple mode for the web form creation (without using the web form result statuses, fields etc.).
Maximum number of database table records fetched in SQL queries | Specifies the maximum number of records displayed in the list of web form results.
Number of results on page | Specifies the maximum number of web form results on a page.
Default permission for new web forms The default rights of user groups for the access to all newly created web forms:
  • access denied - form and its results are totally inaccessible;
  • filling in the form - a visitor can only fill in and save the form;
  • edit own result according to its status - a visitor has the right to work only with their results according to the rights assigned for each status of result;
  • edit all results according to their statuses - a visitor has the right to work with all results according to the rights assigned for each status of result;
  • view form parameters - includes all the above rights and also the right to view web-form parameters;
  • full access - includes all the above rights and also the rights to modify form settings.

"Access" tab

This form serves for customising the user group rights for the access to the Web form module.

Field | Description
Default | Controls the access permission of user groups that have the default permission.
[User group] Controls the access permission of each user group. The following access levels are possible:
  • Access denied - the access to the menu and module administration files is denied;
  • Access granted - the access to the menu and module administration files is granted; further rights are regulated according to the rights specified in forms;
  • Full Access - implies the right to manage the menu and module administration files and to create new forms. Yet, the access to existing forms is regulated according to the rights specified in forms.


How to create a new web form - Bitrix Site Manager - Content Management & Portal Solutions

How to create a new web form

To create a new web form, complete the following:
  1. Open the list of forms in the administrative section (Services -> Web forms – Manage Forms).
  2. Click Create.
  3. Enter a new web form name in Name field.
  4. Enter a form character code into Identifier field. This code will be used in customizing the form display options in the public site section.
  5. Specify the sorting order. The higher is the value, the lower the form will be positioned in the list.
  6. Specify menu options for the administrative site section, which provide access to the results tables. Also specify user groups access rights for this form and other.
  7. Choose the interface language of the web form.
  8. Enter text, which will be displayed on the sending from results button (for example, Save).

  9. Load an image from the local computer. It will be displayed in the public section of the site next to the form name and description.
  10. Enter the web form description, either as the plain text or HTML code.
  11. Click Apply to make new settings effective.
  12. Now you can define templates for:
    • Displaying the form;
    • Displaying the result;
    • Printing the result;
    • Modifying the result;
    • Sending results via the e-mail (e-mail templates can be automatically generated).

    The Create link can be used to generate an e-mail template.

    You can go to the template editing page by clicking the View Template link.

  13. You have the possibility to register the form filling and saving events in the statistics module. Also, this tracks the form filling activity dynamics on daily basis. Specify the event type identifiers for the statistics module in the form settings.

  14. Define user groups access rights for this form. You can specify the following access rights types:
    • Access denied;
    • Form filling;
    • Work with the result according to its state;
    • Work with all results according to their states;
    • Viewing the form parameters;
    • Full access.

    For more information, refer to the Assigning user web forms access rights topic.

  15. Click Save to add a new form and return to the forms list. Press Apply to save all changes and remain on the form editing page. To clear all fields, click Clear.

As soon as the form is created, you can create form questions and fields.


How to create web form questions - Bitrix Site Manager - Content Management & Portal Solutions

How to create web form questions

The form question is the collection of the question text and input fields, intended to enter questions to it.

To create form questions, complete the following:

  1. Open the list of web forms (Services -> Web forms -> Manage Forms).
  2. Click the plus sign + in the Questions column of the form to which you want to add questions.

  3. In the question creation form, select whether the question is active or not.
  4. Select the sorting order.
  5. Enter the question character code into the Identifier field.
  6. Select the Required checkbox, if the question answer is mandatory.

  7. If needed, load the question image from the local computer.
  8. Use plain text or HTML Code to enter the question text. You can use an HTML-editor.
  9. Enter a service comment.
  10. Fill in answer fields. Text - for answer variants (for dropdown, multiselect, radio, checkbox field types). Other fields leave blank.
    Value - additional parameter, which can be used for a definite answer identification (for example in the lists). The field types are:
    • text - single line text;
    • textarea - multi line text;
    • multiselect - multiply selection;
    • dropdown - single selection;
    • radio buttons set - single choice – alternative;
    • checkbox buttons set - multiple choice;
    • fields for image input;
    • fields for date with built-in calendar input.
    Width – answer field width; available for text, textarea, image, date field types;
    Height – answer field heigh; available for textarea, multiselect field types;
    Parameters – this field can be used to display input element style and to assign special identifiers:
    • SELECTED – when assigning this identifier, an input field will be selected; Available for: multiselect, dropdown, radio, checkbox;
    • NOT_ANSWER – when assigning this identifier, if the required checkbox is selected and visitor chooses this answer, it will not be considered as the answer to a mandatory form question. Available for: dropdown, radio, multiselect, checkbox;
    • NOW_DATE – displays the current date in date field;
    • NOW_TIME – displays the current time in date field.
    Sort. (Sorting) – Answer field sorting order;
    Act. (Active) – if deselected, the field can not be observed in the public section of the site;
    Del. (Delete) – field deletion. When working with the fields of text, textarea, date, image type you need to put a space in the Text field.
  11. Select Show in the result table field to display questions for this answer in the result table.
  12. You can enter text, which will be displayed as column heading in the result table, in the Text for result table field. If you leave this field blank, the question text will be used as a heading.
  13. Select Filter fields field to specify how the result table filtering by this question will be conducted and what fields will be used in this filtering. The following field types are provided:
    • single line text field;
    • range of numbers;
    • range of dates
    • single choice dropdown list.
  14. You can enter text, which will be displayed near the selected fields of the filter by result table, into Text for Filter field.


How to create web form fields - Bitrix Site Manager - Content Management & Portal Solutions

How to create web form fields

The form Field is intended for data storage, defined after saving of the filled form (after saving the result). To create a field:
  1. Specify a character code in the Identifier field.
  2. Specify order of sorting.
  3. Enter field heading.
  4. Enter service comment.
  5. Specify this field type:
    • text
    • integer
    • date
  6. Select the Show in result table field to display the data, stored in this field, in result table and to display fields for result filtering by values, stored in this field, in the filter. The filter fields will be selected according to the field type:
    • Text type complies with single line filter text field;
    • Integer type complies with range of numbers;
    • Date type complies with range of dates.
  7. Single line text field allows to use logical expressions. The syntax is:
    • & (logical AND)
    • | (logical OR)
    • ~ (logical negation)
    • () parentheses for conditions grouping
    Logical operation priorities in filter fields are identical to the ones in mathematic.
  8. You can enter text to be displayed as column heading in the result table, in the Text for result table field.
  9. Select the Show in the filter by result table field to choose and display the appropriate field in the filter by result table according to the field type.
  10. You can enter text, which will be displayed next to the selected fields of the filter by result table, into Text for Filter field.


Setting up web form states - Bitrix Site Manager - Content Management & Portal Solutions

Setting up web form states

  1. Open the list of web forms (Services -> Web forms -> Manage Forms).
  2. Click the plus sign + in the Statuses column of the form to which you want to add a new status.

  3. Select the Active checkbox, if you want this state to be displayed in the public section of the site.
  4. Enter the state heading in the Heading field.
  5. Add a state description.
  6. Add the sort order (state display sequence in administrative section and in dropdown states list).
  7. Specify text style for the state heading in the CSS style for the status heading field (for example, in the result table, when displaying or viewing the state by means of default.php type templates).

  8. Specify the user groups, which can assign results to the current state. These users can assign the current state to the result. You can also separately assign this right for the result author. For users to take advantage of this right, they must have the right for editing the result.
  9. Specify the user groups that have the right to view the result in the current state. Members of these groups can view the result in the current state. You can separately assign this right for the result author.
  10. Specify the user groups who will have the right to edit a result in the current state. You can separately assign this right for the result author.
  11. Specify the user groups who will have the right to delete results in the current state. You can separately assign this right for the result author.
  12. To add a new state, click the Add button.


Advertising - Bitrix Site Manager - Content Management & Portal Solutions

Advertising

The advertising management system provides for banner shows on your site by attaching the external banner system code or by using the internal banner rotation system. You can place the banner images or include the banner code in the HTML code of your pages.

You can specify the show period for a banner, number of shows, allow or disallow a banner to show on certain pages and sections of the site.

Each advertising area can show one or more banners. The internal banner rotation system selects random banners to show. You can specify how frequently a banner will show by assigning a weight coefficient (show probability factor) to it. The greater is the weight value, the higher is the banner show probability.

The Advertising module can also handle the site counter shows.

The Advertising module uses the following terms.

Advertising block
is the certain advertising type that is to be shown in one or more advertising areas.
Advertising area
is a banner placeholder in the main template used to show advertising of various types.

The Advertising module interface allows to add both the new advertising and the new advertising block types. To add new advertising areas, you will need to edit the main show template.


Banner and Contract graphs - Bitrix Site Manager - Content Management & Portal Solutions

Graphs

In this section

  • Banner graphs
  • Filter
  • Example of a graph
    •
  • Contract graphs
  • Filter
  • Example of a graph
    •

    • Bitrix Site Manager empowers you with a strong toolset of graphs and diagrams to estimate and analyse the advertising campaign course and results on an individual banner or advertising contract in whole. You can view graphs in the respective sections:

    • Banner graphs: Services -> Advertising -> Reports -> Banner graphs;
    • Contract graphs: Services -> Advertising -> Reports -> Contract graphs.

    The graphs display information on the number of visitors, impressions, clicks and CTR. You can change the advertising data retention duration in the module settings.

    Banner graphs

    Filter

    The filter is used to specify data to render on the graph.

    Field | Description
    Period | The period of time for which to show information.
    Display | Select the kind of information to display on a graph.
    Banners Select here banners whose dynamics you want to display.

    If the drop-down list is available, you can choose between:
    • summary graph - builds a single graph for all selected banners;
    • separate graphs- builds individual graphs for each of the selected banners.

    Click Find to render diagrams. Click Cancel to clear filter values.

    Example of impression graph

    Click on image to enlarge

    Click on image to enlarge

    Contract graphs

    Filter

    The filter is used to specify data to render on the graph.

    Field | Description
    Period | The period of time for which to show information.
    Display | Select the kind of information to display on a graph.
    Contracts Selecting a contract implies that a single graph displays information on all banners of the contract.

    If the drop-down list is available, you can choose between:
    • summary graph - builds a single graph for all selected contracts;
    • separate graphs- builds individual graphs for each of the selected contracts.

    Click Find to render diagrams. Click Cancel to clear filter values.

    Example of a CTR graph

    Click on image to enlarge

    Click on image to enlarge

    See also: Diagrams

    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Banner and campaign Diagrams

Diagrams

In this section

  • Banner graphs
  • Filter
  • Example of an impression diagram
    •
  • Contract graphs
  • Filter
  • Example of a visitor diagram
    •

    • Another strong Bitrix Site Manager visual feature are diagrams. You can view diagrams in the respective sections:

    • Banner graphs: Services -> Advertising -> Reports -> Banner diagrams;
    • Contract graphs: Services -> Advertising -> Reports -> Contract diagrams.

    With diagrams, you can comprehensively perceive and compare information on the number of visitors, impressions, clicks and CTR. You can change the advertising data retention duration in the module settings.

    Banner diagrams

    Filter

    The filter is used to specify data to render on the diagram.

    Field | Description
Period | The period of time for which to show information.
Display | Select the kind of information to display on a graph. If you select multiple parameters, their diagrams will be displayed in tabs.
Banners | Select here banners whose values you want to display. You must select at least 2 banners for building a diagram.

    Click Find to render diagrams. Click Cancel to clear filter values.

    Example of an impression diagram

    Contract diagrams

    Filter

    The filter is used to specify data to render on the diagram.

    Field | Description
Period | The period of time for which to show information.
Display | Select the kind of information to display on a graph. If you select multiple parameters, their diagrams will be displayed in tabs.
Contracts | Select here contracts whose values you want to display.

    Click Find to render diagrams. Click Cancel to clear filter values.


Banners - Bitrix Site Manager - Content Management & Portal Solutions

Banners

In this section

  • Filter
  • Context bar
  • List of banners
    •

    This page displays banners currently existing in the system.

    A banner is a picture or text of advertising nature with a link applied to it. A banner has a definite type, must be attached to a contract and can be included in a banner group. A banner can have one of the following three states:

    • approved – a banner can be displayed on the site;
    • on approval – banners in this state be displayed. This state indicates that a user taking over the advertising module should move the banner to either the approved or rejected state;
    • rejected – when in this state, a banner cannot be displayed.

    When setting the banner state, a user can specify the reason for change in the Comment field.

    Click Through Rate (CTR)
    CTR denotes the percentage of click-throughs to banner views. Expressed as percentage and calculated by formula: (C*100)/S, where C is the number of click-throughs and S is the number of shows. A 10% CTR banner is considered successful.
    Banner Weight
    is a value that affects the probability of choice of the banner for display. When showing a banner in the public section, a contact with the greater weight is chosen first. The more is the contract weight, the more is the probability of choosing it. After the contact is determined, the banner of this contract is selected. The more is the banner weight, the more is the probability of choosing it to show.
    Banner Group
    is the arbitrary name of a group to include the banner.

    Filter

    Parameter | Description
    Search | Specifies to find a banner by the ID, name or HTML code.
    ID | The ID of the required banner.
    Indicator With this field, you can find banners by the indicator:
    • red matches inactive or expired banners;
    • green matches active and non-expired banners.
    The value of this indicator is generally defined by the indicator of a contract under the banner.
    If the contract indicator is red (i.e. inactive), all banners of this contract will have their indicators coloured in red.
    Status | The status of the sought banner.
    Site | Finds banners by the site on which the matching banner is displayed.
    Visitors | Finds banners by the number of views.
    Shows | Finds banners whose number of impressions matches the range.
    Clicks | The range of the number of banner clicks.
    CTR (%) | The range of the CTR values of the matching banner(s).
    Group | The group to which the required banner relates.
    Contract | The banner contract.
    Type | Finds banners of the specified type.
    Name | Finds banners by their name.
    Code | Finds banners by their HTML code.
    Comment | Finds banners by their comment.

    * - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add banner | Opens a menu in which you can select the type of a new banner to create.
Excel | Exports data from the table to the MS Excel format.

    List of banners

    Field | Description
    Checkbox column | Used to select banners to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any banner opens a menu:
    • Edit - opens the banner for editing;
    • View - views the banner parameters;
    • View banner CTR graph - shows the banner CTR graph;
    • Copy - duplicates the banner;
    • Delete - deletes the banner.
    ID | The system banner ID. Clicking the link opens the banner for editing.
    Ind. Indicates the banner state:
  • – the banner is inactive (e.g. expired);
  • – the banner is active.
    •
    Sites | Sites on which the banner can be shown.
    Act. | Yes - the banner is active. No - inactive.
    Weight | The banner sort weight; defines the banner position in lists.
    Name | The banner name.
    Type | The banner type.
    Status | The current banner status.
    Shows | Count of banner impressions.


Creating and editing a banner - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a banner

In this section

  • Context bar
  • Editing form
  • Banner
  • Restrictions
  • Targeting
  • Statistics
  • Comment
    •
  • Controls
    •

    Context bar

    Button | Description
Banner list | Opens a form with a list of banners.
View banner CTR graph | Shows the banner CTR graph.
View banner settings | Displays the banner parameters.
Add new banner | Creates a new banner in this form.
Copy banner | Duplicates the banner being edited.
Delete | Deletes the current banner.

    Editing form

    This form, which is split in several tabs, is used to create new and edit properties of existing banners.

    "Banner" tab

    This tab contains common banner parameters.

    Field | Description
    Banner status Indicates the banner display status:
    • - banner cannot be displayed;
    • - banner can be displayed.
    Created | The time the banner was created. The user who created the banner.
    Modified | The time the banner was last modified.
    Contract | The contract to which the banner relates.
    Active | Denotes the banner is active.
    Show period | The range of dates within which the banner can be displayed. The banner becomes inactive when the period expires.
    Name | An arbitrary name of the banner.
    Group | An arbitrary group to which the banner belongs. If a drop-down list is active, you can select one of the previously created groups.
    Type | The banner type. Defines the banner placement.
    Media
    Image | Click the Browse button to upload an image for the banner from the local computer.
    Tooltip text | Advisory text to appear when a user hovers the mouse over an image.
    Flash banner does not contain link If checked, clicking a Flash banner will open the link specified in Banner URL rather than the link the Flash banner was intended to open. This allows to register clicks in the Statistics module.

    Note!
    Enabling this option affects the intended interactivity of Flash banners. This is because the banner will not receive the mouse input.

    Banner URL | URL of the target page or site to which a visitor will navigate upon click.
    URL target Type of the window to display the target page of the link:
    • _self – specifies to load the link into the same window the link was clicked in.
    • _blank – specifies to load the link into a new blank window. This window is not named.
    • _parent – specifies to load the link into the immediate parent of the document the link is in.
    • _top - specifies to load the link into the full body of the window.
    Banner code You can use both plain text and HTML as the banner code.

    You can use templates #RANDOM1#, #RANDOM2#, #RANDOM3#, #RANDOM4# and #RANDOM5# in your code. These will be replaced with the random numbers at the show time in the public section.

    The following templates are also allowed:
    • #BANNER_NAME# - banner name;
    • #BANNER_ID# - banner ID;
    • #CONTRACT_ID# - contract ID;
    • #TYPE_SID# - banner type.
    Banner status
    Status Allows to set the current banner status:
    • approved – the banner can be displayed on the site;
    • on approval – banners in this state be displayed. This state indicates that a user taking over the advertising module should move the banner to either the approved or rejected state;
    • rejected – when in this state, the banner cannot be displayed.
    Status comment | Comments for the banner state change.
    Notify contract owners | If checked, directs to create and send a message based on the template Banner state change.
    "Restrictions" tab

    These settings can be used to impose additional control over the banner display.

    Field | Description
Weight (priority) | The banner weight. This affects the probability of selecting a banner for the show.
Maximum audience | Maximum number of visitors allowed to view the banner. The number on the right indicates the number of visitors to which the banner was shown. Checking the reset flag resets the counter to 0 upon save.
Maximum shows to one visitor | You can limit the number of shows of the banner to a single visitor. 4 shows is usually the optimum.
Maximum shows | Maximum number of shows that triggers the inactive state of the banner. The number on the right denotes the current number of shows. Checking the reset flag resets the show counter to 0 upon save.
Register clicks on this banner | If the flag is checked, banner clicks are registered in the Statistics module.
Maximum clicks | Maximum number of clicks for the banner. After the counter reaches this value, the banner becomes inactive. The number on the right denotes the current number of clicks. Checking the reset flag resets the click counter to 0 upon save.
Banner CTR (%) | Denotes the percentage of clicks.
Days and time for show | Hours and days of week when the banner is to be shown.
    "Targeting" tab

    This tab contains options which allow additional control over the banner shows.

    Field | Description
Sites | Sites on which the banner can be shown.
Sections and pages to show the banner | You can specify names of section or pages that will only show the banner. Page names allow parameters; each page should start from the new line.
Sections and pages to not show the banner | You can specify names of section or pages that will not show the banner. Page names allow parameters; each page should start from the new line.
User groups | With field, you can choose user groups to whose members the banner will or will not be shown (it depends on the selection between the two options: Show banner to selected groups only and Don't show banner to selected groups).
Keywords | The banner keywords. The banner will be shown much more often on pages containing these keywords.
Show to visitors from countries | Visitors from the selected countries will be only allowed to view the banner.
Show to visitors under advertising campaigns | The module administrators can only edit this field. This field can be used to restrict banner impressions to visitors who entered the site on a specific adv. campaign
Show to visitors | Select the visitor category to show the banner: all; new visitors; returned visitors.
    "Statistics" tab

    Parameters of this tab define how events are registered in the Statistics module. Only administrators can edit these settings.

    Field | Description
    Register events | If checked, events are registered.
    Event1 | Event type identifier event1.
    Event2 | Event type identifier event2.
    Event3 Auxiliary parameter of an event.
    The following templates are allowed in event1, event2 and event3:
    • #BANNER_NAME# - banner name;
    • #BANNER_ID# - banner ID;
    • #CONTRACT_ID# - contract ID;
    • #TYPE_SID# - banner type.
    "Comment" tab

    Here you can type any comment to the banner.

    Controls

    Button | Description
Save | Saves changes. Returns to the list of banners. Displayed when editing an existing banner.
Apply | Applies current changes. Editing continues.
Cancel | Dismisses recent changes. Editing continues.


Contracts - Bitrix Site Manager - Content Management & Portal Solutions

Contracts

In this section

  • Filter
  • Context bar
  • List of contracts
    •

    This page displays a list of the advertising contracts.

    An advertising contract is a set of conditions applied to banner shows. A contract may have users assigned to it; the users may have different permissions for this contract.

    Contract owners are users who have certain permissions for a contract. Users can be assigned to a contract only if they are members of a group given the advertiser permission in the Advertising module settings.

    Click Through Rate (CTR) denotes the percentage of clicks to banner views. Expressed as percentage and calculated by formula: (C*100)/S, where C is the number of clicks and S is the number of shows. A 10% CTR banner is considered successful.

    A contract weight is a value affecting the probability of selecting the contract when choosing a banner for display. When the system selects a banner to be displayed in the public section, the system first selects a contact with the greater weight. The more is the contract weight, the more is the probability of the contract to be selected. After the contact is defined, the system tries to select a banner from this contract. The more is the banner weight, the more is the probability of the banner to be selected.

    Filter

    Parameter | Description
    Find | Specifies to find contracts by the ID, name or HTML code.
    ID | The ID of the required contract.
    Modified | Specifies to find contracts that were modified within the specified period.
    Indicator With this field, you can find contracts by the indicator:
    • red matches inactive or expired contracts;
    • green matches active and non-expired contracts.
    Site | Finds contracts by the site on which the contract banners are displayed.
    Number of banners | Specifies to find contracts having the specified number of banners.
    Visitors | Finds contracts by the number of visitors who viewed banners of the matching contracts.
    Shows | Finds contracts by the number of impressions of banners of the matching contracts.
    Clicks | Specifies the total number of banner clicks of the sought contract.
    CTR (%) | Finds contracts whose banners have the specified CTR.
    Owner ID, login, name | The ID and/or login and/or name of an owner of the required contract.
    Title | The title of the sought contract.
    Description | Specifies an entry in the description of the sought contract.
    Administration comment | Finds contracts by an entry in their comments.

    * - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add contract | Opens a form in which you can create a new advertising contract.
Excel | Exports data from the table to the MS Excel format.

    List of contracts

    Field | Description
    Checkbox column | Used to select banners to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any contract opens a menu:
    • Modify - opens the contract for editing;
    • View - views the contract parameters;
    • View CTR graph - shows the contract CTR graph;
    • Delete - deletes the contract. A default contract (with the ID of 1) cannot be deleted.
    ID | The system contract ID. Clicking the link opens the contract for editing.
    Ind. Indicates the contract state:
  • – the banner is inactive (e.g. expired);
  • – the banner is active.
    •
    Modified | The date and time the contract was last modified.
    Sites | The sites on which the contract is effective.
    Sort | The contract display order.
    Act. | Indicates the contract is active. Only banners of active contracts can be displayed.
    Weight | The contract weight. Defines the probability of selecting this contract for the banner show.
    Title | The contract title.
    Banners | Number of the contract banners. The link opens a list of banners.


Creating and editing an advertising contract - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing an advertising contract

In this section

  • Context bar
  • Editing form
  • Contract
  • Restrictions
  • Targeting
  • Access
  • Comments
    •
  • Controls
    •

    Context bar

    Button | Description
Contracts | Opens a list of advertising contracts.
View contract CTR graph | Shows the contract CTR graph.
View contract settings | Displays the contract parameters.
Add new contract | Creates a new contract in this form.
Delete contract | Deletes the contract being edited. The default contract (with the ID of 1) cannot be deleted.

    Editing form

    This form is used to create new and edit existing advertising contacts.

    "Contract" tab

    This tab contains main parameters responsible for the proper functioning of the contract.

    Field | Description
    Status Indicates the contract status:
  • - the contract is inactive;
  • - the contract is active.
    •
    Created | The date and time when the record was created; a user who created the record.
    Modified | The date and time when the record was last modified; a user who modified the record.
    Active | The flag specifying the contract is active.
    Banner show period | Range of dates during which the contract banners can be displayed. The contract becomes inactive after this period.
    Sort order | The contract sort weight. Defines the position in lists.
    Weight (priority) | The contract weight. Defines the probability of selecting this contract for the banner show.
    Title | The title of the contract.
    Description | The description of the contract.
    Default state for new banners... | The default status assigned to all new banners. This status is also applied when the code or media of the contract banners change.
    Number of contract banners | The table displaying the number of contract banners in their states.
    "Restrictions" tab

    These settings can be used to impose additional control over the display of the contract banners.

    Field | Description
Sites | Select here sites which are allowed to show the contract banners.
Banner types | List of all the existing banner types. The selected types will be available for creating new banners.
Maximum allowable number of visitors to view the contract banners | Allows to limit the number of unique visitors to which the contract banners can be displayed. On reaching the value, the contract will become inactive.
Maximum allowable number of shows of the contract banners | Allows to limit the total number of the contract banner shows. On reaching the value, the contract will become inactive.
Maximum allowable number of clicks of all contract banners | Allows to limit the total number of clicks on the contract banners. On reaching the value, the contract will become inactive.
CTR (%) | The current click through ratio.
Banner show days and time | Hours and days of week when the banner is to be shown.
    "Targeting" tab

    This tab contains options which allow additional control over impressions of the contract banners.

    Field | Description
Sections and pages allowed to show the contract banners | You can specify here the names of section or pages on which the contract banners are only allowed to be displayed. Names can include parameters; each page should start from a new line.
Sections and pages disallowed to show the contract banners | The names of section or pages that must not show the contract banners. Names can include parameters; each page should start from the new line.
Keywords | Keywords for the contract banners. Banners will be shown much more frequently on pages that have these keywords.
    "Access" tab

    This tab contains options with which you can control user permissions to access the contract banners and settings.

    Field | Description
View | This permission allows a user to view the contract parameters, parameters of the contract banners, and the graphs and diagrams of the contract banners.
Manage banners | This permission allows a user to view the contract parameters and create, edit and delete the contract banners.
Edit user permissions | This permission allows a user to edit the contract title and description as well as assign the View and Manage banners permissions for this contract to other users.
    "Comment" tab

    Here you can type any comment to the contract.

    Controls

    Button | Description
Save | Saves changes. Returns to the list of contracts. Displayed when editing an existing contract.
Apply | Applies current changes. Editing continues.
Cancel | Dismisses recent changes. Editing continues.


Banner types - Bitrix Site Manager - Content Management & Portal Solutions

Banner types

In this section

  • Filter
  • Context bar
  • List of banner types
    •

    The Banner types form (Services -> Advertising -> Banner types) displays all banner types currently registered in the system.

    A banner type is a named area in the site HTML template used to display banners. The area name specified in the template is the same as the name of a banner type that are to be displayed in this area.

    Filter

    Parameter | Description
Find | Specifies to find a banner type by the ID, name or HTML code.
ID | The symbolic banner type identifier.
Modified | Allows to find banner types that was modified within this period.
Active | Specifies to find only active banner types, inactive or all.
Name | The name of the required banner type.
Description | Allows to find a banner type by an text entry in its description.

    * - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add type | Opens a form in which you can create a new banner type.
Excel | Exports data from the table to the MS Excel format.

    List of banner types

    Field | Description
    Checkbox column | Used to select banner types to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any banner type opens a menu:
    • Edit - opens the banner type for editing;
    • Parameters - views the banner parameters;
    • CTR graph - shows the banner type CTR graph;
    • Delete - deletes the banner.
    ID | The banner type symbolic identifier.
    Modified | The date and time the banner type was last edited.
    Act. | Indicates whether the banner type is active or not.
    Sort | Relative weight defining the position of the banner type in lists.
    Name | The banner type name as it was specified when creating.
    Description | The banner type description.
    Banners | Number of banners of this type. The link opens a form displaying the list of banners of this type.


Creating and editing the banner type - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing the banner type

In this section

  • Context bar
  • Editing form
  • Controls
    •

    Context bar

    Button | Description
List of types | Opens a form containing a list of banner types.
CTR graph | Displays the CTR graph for banner of this type.
Parameters | Shows the banner type parameters.
Add new type | Creates a new banner type in this type.
Delete | Deletes the banner type currently opened for editing.

    Editing form

    This form is used to create and edit banner types.

    Notes for developers
    After you have created a new banner type, allocate an area where your banners will be displayed by calling $APPLICATION->ShowBanner(...) in the site HTML template.

    Field | Description
Created | The date and time the banner type was created; a user who created the type.
Modified | Modification date; a user who was the last to edit the type.
Active | Specifies whether the type is active or not.
Sort order | The sort weight; used when displaying the type in lists.
Symbolic ID | The symbolic identifier may include Roman letters, digits, underscores (_). This identifier can be further referenced in banner areas when creating the site design.
Name | The arbitrary type name.
Description | The description of the type.

    Controls

    Button | Description
Save | Saves changes. Returns to the list of banner types. Displayed when editing an existing banner type.
Apply | Applies current changes. Editing continues.
Cancel | Dismisses recent changes. Editing continues.


Settings - Bitrix Site Manager - Content Management & Portal Solutions

Settings

In this section

  • Settings
  • Access
    •

    This page (Settings -> System settings -> Module settings -> Advertising and Banners) is used to edit the system-wide settings of the Advertising module.

    "Settings" tab

    The Settings tab contains general module settings.

    Parameter | Description
Use HTML editor (for IE 5.0 and higher only) | Check this option to enable the visual HTML editor for editing the banner code.
Banner dynamics retention period | This parameter allows to limit the period of storing the daily information on clicks and shows.
Graph width | Graph width, in pixels.
Graph height | Graph height, in pixels.
Pie chart diameter | Pie chart diameter, in pixels.
Banner views retention period | This parameter allows to specify the period of storing the information on banner views by a visitor. As long as the information is kept, it is considered that a visitor viewed a banner.
Banner click registration handler | Path to a file containing the banner click registration script. The default script (/bitrix/rk.php) registers clicks in the Statistics module if it is installed. Otherwise, the script attempts to register clicks in the Advertising module.
Subfolder for uploaded banners | The name of the subfolder (relative to /upload/) in which all uploaded banner images are stored.

    Module access permissions

    This form allows to customize the user access permissions for the module.

    Field | Description
    Default | Controls the access permission level of all user groups whose permission level is set to default.
    user group Controls the access permission level for each user group, individually.
    • Deny [D] - any access to the administrative menu and files is prohibited.
    • Advertiser [R] - granted access to the administration menu and files; a user can only view the permitted contracts and contract banners. This permission mode is used for advertisers who publish their advertisement on your site.
    • Banner manager [T] - a user can manage contract banners but cannot edit the contract parameters (for contracts in which the appropriate user group is selected in the Manage banners field).
    • Demo access [V] - a user can view all contracts, banner types and banners as well as build graphs, but cannot modify anything. This permission mode is used in demo mode to allow a user to view information but not modify it.
    • Advertising administrator [W] - full access without restrictions.


Adding a banner - Bitrix Site Manager - Content Management & Portal Solutions

Adding a banner

To add a new banner to the site, do the following.

  1. Open the banner management form (Services -> Advertising -> Banners).
  2. Click Add banner.
  3. Choose the required contract to which a banner is to be added.
  4. Check the Active box so as to enable banner in the public section.
  5. Specify the show period for the banner. Click the button [image] to open the calendar.
  6. Type the banner name (this text is displayed and meaningful in the administration section only);
  7. Specify a group to which the banner relates. You can type the name of a new group, or select an existing group in the list.
  8. Select the disposition of the new banner on a page (type).

  9. Upload the banner image.
  10. Enter the banner tooltip text. This text will appear when a visitor hovers the mouse over the banner.
  11. Enter the link to redirect a visitor upon click. You can use the referer1 and referer2 parameters in the link.
  12. Provide the banner HTML code if necessary. It is generally used in banner exchange.

    If you are a member of a banner exchange system, and want to place a custom banner or banner of some other site that uses HTML code, you have to enter this code here. The HTML code may contain up to 5 random number macros %%RANDOM1%% .... %%RANDOM5%% which can be used to prevent displaying the same banners on a page simultaneously.
  13. Set the banner status:
    • approved – the banner can be displayed on the site;
    • on approval – banners in this state be displayed. This state indicates that a user taking over the advertising module should move the banner to either the approved or rejected state;
    • rejected – when in this state, the banner cannot be displayed.
  14. Click the Restrictions tab to set the banner impression conditions.
  15. Specify banner weight (priority of displaying this banner over other banners; the higher is the value, the higher is the priority).
  16. Specify the maximum number of visitors to whom the banner will be displayed.
  17. Specify the maximum number of the banner impressions to the same visitor.
  18. Specify the maximum number of the banner impressions.
  19. Enable the Register clicks on this banner option if you want to register banner clicks in the Statistics module.
  20. Specify the maximum number of banner clicks which, when reached, deactivates the banner.
  21. Select one or more sites to show the banner.

  22. If required, specify the time and days of week when the banner is to be displayed.
  23. Click the Targeting tab.
  24. Choose sites on which the banner is to be displayed.
  25. If necessary, enter the pathnames of pages on which the banner must be only displayed.
  26. If necessary, enter the pathnames of pages on which the banner must not be displayed.

  27. If required, set the impression restrictions in respect of user groups.
  28. If you want to show the banner only on pages containing the required keywords, specify them.

  29. Specify the geographical targeting. To do so, select countries.
  30. If required, specify the advertising campaign targeting. The banner will be shown to visitors of the specified advertising campaigns.
  31. Customize the visitor advertising targeting (new visitors, returned visitors, all visitors).
  32. Click the Statistics tab to set the banner event registration parameters.
  33. Provide the values: event1, event2, event3. These values define event type identifiers. You can get a detailed description of event types here.

  34. You may leave a comment if necessary.
  35. Click Apply to save changes and continue editing, or click Save to add the banner and go back to the list of banners.


Subscription - Bitrix Site Manager - Content Management & Portal Solutions

Newsletters

The Newsletter (or "subscribe" for use with the system API functions) module is designed for creating mailing lists. Newsletter issues are sent to groups of registered subscribers or site users, which in their turn comprise mailing lists. With the help of newsletters and mailing lists, visitors of your site can obtain the latest information about your company activities. For instance, subscribers can receive e-mail messages with:

  • general news;
  • press releases of your company;
  • messages about changes on the site;
  • information about new goods and services;
  • news headlines;
  • other information.

Glossary

The following terms are used while working with the mailing list module:

Newsletter
A single subject to which site visitors can be subscribed. Users can be subscribed to several newsletters simultaneously.
Subscribers
Site visitors and users subscribed to newsletters. Subscribers can be both registered and anonymous users. Anonymous users are those who are not registered on site.
Issues
Mail messages sent to subscribers. A newsletter issue can be sent to:
  • subscribers of a certain newsletter;
  • users from a group with certain rights;
  • random e-mail addresses.


Subscription issues - Bitrix Site Manager - Content Management & Portal Solutions

Newsletter issues

In this topic

Filter
List of messages
How to create a subscription issue
How to send a subscription issue
How to find a subscription issue

The Newsletter issues form is used to manage newsletters. Using this form, you can:

  • review the existing newsletter issues in the table format;
  • create new newsletter issues from scratch or from the existing issues;
  • edit issues;
  • delete issues;
  • send issues to subscribers.

Filter

The filter is used to set parameters for selecting messages to be displayed in the list. The filter allows you to find any newsletter, whenever it was created. The filter offers the following parameters:

  • message ID;
  • range of dates within which the message could be created;
  • status;
  • recipients;
  • topic;
  • other criteria.

The table below describes the filter fields.

Field | Description
Find | This field can be used to select newsletters by their main parameters: ID, subject or status. This field is visible even if the filter is collapsed.
ID | The ID of the message with which it was registered in the database. This field allows using the query language to create complex conditions.
Modified (DD.MM.YYYY) | This parameter is used to define the range of dates within which the required messages could be changed.
Sent (DD.MM.YYYY) | The range of dates within which the required messages could be sent.
Scheduled time of the issue | This option allows to find automatic messages by the date and time they were send.
Status Used to specify the status of the required message(s) in the database. The following statuses are defined for messages:
  • Sent
  • Partially sent
  • Draft
  • Error
To filter issues by status, you can also use the text field above the status list. You can combine several status values in this field, for example "D|S" or "draft|sent". This field allows to use the query language to create complex conditions.
From | This field is used to specify senders whose messages are required. You can use full or partial e-mail addresses here. The use of the query language is possible.
To This field is used to specify recipients who could receive the sought messages. You can use full or partial e-Mail addresses here. The use of the query language is possible.

For an issue, this field becomes valid after an issue (e-mail message) is sent.
Subject | Specify here the proposed contents of the Subject field of required messages. The use of the query language is possible.
Message type | Allows to filter only those messages that were was created in the HTML or text formats.
Message | You can specify words, parts of words, phrases or part of phrases to find the appropriate messages. It is possible to use a query language to create complex conditions.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Add | Adds a new issue.
Excel | Exports data from the table to the MS Excel format.

List of issues

The list of issues displays newsletter issues according to the specified filter criteria. Right column of the list (Action) contains links for managing the corresponding messages. By using these commands, the messages can be edited, sent or deleted.

The fields of the table are described below.

Field | Description
Checkbox column | Used to select issues to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
 Clicking the action button of any issue opens a menu allowing to:
  • Send - send an issue. This command is available for issues in the Draft status;
  • Stop - stop sending an issue. This command is available for issues in the In progress status;
  • Resume - recommence sending an issue. This command is available for issues in the Stopped status;
  • Modify – edit an issue. This command is not available for issues in the In progress status;
  • Copy – create a new issue by duplicating the selected issue;
  • Delete - delete an issue. This command is available for issues in the Stopped status.
ID | The message ID with which it was registered in the database.
Modified | Modification date of the message.
Subject | Subject of the message.
Type | Type of the message: text or HTML.
Status | Status of the message.
Sent | The date the message was sent.

How to create a newsletter issue

To create a new newsletter, click the Add button, which opens the add/edit a message form.

How to send a newsletter issue

The easiest way to send an issue is to click the Send button in the issue creation form. However, after creating a message you can save it without sending. You can send the issue later by selecting the Send command in the action menu of the appropriate issue.

How to find a newsletter issue

To find the specific issue, you can set its parameters in the filter. For example, you want to find the message with the following subject: new laptop proposal. Enter subject text into the Subject field of the filter and click Set filter. The table will display the required message.


New issue (issue editor) - Bitrix Site Manager - Content Management & Portal Solutions

New issue (issue editor)

In this topic

Form fields
Control buttons

This form is used to create and edit newsletter issues (in fact, e-mail messages) to be sent to subscribers. Depending on whether you create a new message or edit an existing one, some fields can be visible or not.

With this form, you can do the following:

  • create a new or edit an existing issues for sending to subscribers;
  • choose recipients for an issue;
  • choose site visitors who will receive the newsletter issue;
  • add third-party mailing addresses;
  • adjust the issue parameters;
  • send issues to subscribers.

Context bar

Button | Description
List | Opens a report form containing information on all issues in the system.
Add a new issue | Creates a new issue.
Copy issue | Duplicates the current issue.
Delete this issue | Deletes the current issue.

Form fields

"Message" tab

Field | Description
Message status information
Modified The date an issue was last modified.

This field is displayed only in the message editing mode.
Sent The date the issue was sent.

This field is displayed only in the message editing mode, if an issue was sent once.
Delivery report Link to the list of addresses to which the message was sent. This field is displayed if the delivery report can be built (i.e. for the Sent, Partially sent, Error statuses).

This field is displayed only in the message editing mode, if an issue was sent once.
Current status Status of an issue. The status can be one of the following:
  • draft;
  • sent;
  • partially sent;
  • error.

This field is displayed only in the message editing mode, if an issue was sent once.
Move to status This field allows to change the message status. For example, to re-send a message, you can change its status from Sent to Draft and, then send it again.

This field is displayed only in the message editing mode, if an issue was sent once.
Message fields
From | This field contains the message sender address. By default, the sender address specified in the Newsletter module settings is used. This field is mandatory
To | This field is used to specify the message recipient address. By default, the recipient address specified in the Newsletter module settings is used. This field must contain at least one address
Subject | The message subject. This field is mandatory
Message body | The text of the message.
Text / HTML | The format of a message. In the text format, you cannot format text and insert images. The HTML mode allows to use any formatting of a message. At the same time some users might want to receive messages in the text format. In any case, it's up to you to choose the format type.
Use visual editor This option can be used only with the HTML format messages.
If this option is selected, the message can be edited very easily, like in Microsoft Word.
If this options is disabled, and the message was originally created in the HTML format, the HTML code of the message will be displayed.

"Recipients" tab

Field | Description
Addresses of recipients
Topics | A list of existing newsletter topics. You can select the required topics and send the message only to the subscribers of the selected topics.
Format This field allows to restrict the issue sending only to those subscribers who have chosen their desired format of issues. You can choose from the following:
(any)
Send a message to all subscribers regardless of the requested format.
Text
Sent a message to recipients who have chosen to receive messages in plain text.
HTML
Send a message to recipients who have chosen HTML text as the newsletter format.
User groups | In addition to recipients of the selected newsletters, you can send an issue to the site users. Choose the required site user groups from the list by checking the corresponding boxes.
E-mail filter | This field is used to specify a condition that will be applied to e-mail addresses. The issue will be actually sent to matching addresses only. For example, if you want to restrict the issue sending to e-mail addresses registered on the bitrixsoft.com server only, set the following filter: %@bitrixsoft.com
Additional e-mails
Additional e-mail addresses to which the message will be sent. In this field, multiple e-mail addresses must be separated with comma or a carriage return.

"Attachments" tab

Field | Description
File name... | These fields can be used to add files you want to be sent with the message. Click Browse to select and add files.

"Parameters" tab

Field | Description
Encoding | The encoding in which the message will be sent.
Send directly to each recipient | If this option is enabled, each message will be created and delivered individually to each recipient. If this option is disabled, the same message will be sent to all recipients at once, with their addresses in the Blind copy field (BCC). It is recommended to send messages personally to guarantee the reliable delivery to all subscribers.
Send the issue automatically at the scheduled time | Check this box if you want the issue to be sent on the scheduled date and time automatically
Scheduled time of the issue | If you have checked the Send the issue automatically at the scheduled time option, specify here the date and time of the issue sending. By default, this field initially contains the date and time of the issue creation

Control buttons

Button | Description
Creating a new message
Add | Saves the message and switches to the list of messages.
Apply | Saves the message, but does not close the issue editor.
Cancel | Closes the issue editor without save, and switches to the list of messages.
Send | Click this button to send the message.
Editing an existing message
Add | Saves the message and goes to displaying the list of messages.
Apply | Saves the message. Editing of the message is continued.
Cancel | Closes the issue editor without save, and switches to the list of messages.


Subscribers - Bitrix Site Manager - Content Management & Portal Solutions

Subscribers

In this topic

Filter
List of subscribers
How to create a subscriber
How to change subscriber's data

The Subscribers form is used to manage single users subscribed to newsletters. By using this form, you can do the following:

  • review subscriber data in the table form;
  • create new subscribers;
  • edit subscriber parameters;
  • delete subscribers.

Filter

The filter is used to set the criteria for selecting the subscribers to be displayed in the list, which allows to easily find any subscriber. You can use the following parameters in the filter:

  • subscriber ID;
  • range of dates within which the subscriber could have been added to the database;
  • e-mail address;
  • anonymous status;
  • name;
  • other criteria.

The table below describes the filter fields.

Field | Description
ID | The subscriber ID with which the user was registered in the database. You can use the query language in this field to create complex conditions.
Added | Range of dates within which the required subscribers could be added to the database.
Modified | Range of dates within which information of the required subscribers could be changed.
E-Mail | The subscriber e-mail address used to send messages (newsletter issues).
Anonymous This field is used to sort out subscribers for inclusion into the table:
  • anonymous (not registered on site);
  • registered on site;
  • all subscribers.
User ID | The IF of a site User with which he or she was registered on the site. (Compare with ID.) This field is only applicable to registered (not anonymous) users.
Subscriber | Personal user information (ID, login, first and last names). This field is only applicable to registered (not anonymous) users.
Confirmed This field is used to select the following subscribers:
  • whose who have confirmed their subscription;
  • whose who haven't confirmed their subscription;
  • all subscribers.
Active This field allows to pick out subscribers with the following subscription status:
  • active (subscriber receives newsletters);
  • non-active (subscriber is not active);
  • all subscribers.
Format | This field is used to select subscribers by the desired format of messages.
Topics | Using this field, you can select only those users who are subscribed to receive the specified newsletters. To select several subscriptions, press the Ctrl button and click the left mouse button on the required subscription.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Add | Adds a new subscriber.
Excel | Exports data from the table to the MS Excel format.

List of subscribers

The table displays subscribers selected according to the criteria specified in the filter.

The table below describes the table fields.

Field | Description
Checkbox column | Used to select subscribers to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu | Clicking the action button of any subscriber opens a menu allowing to edit information about a subscriber, or delete a subscriber.
ID | The user ID registered in the database.
Added | The date when the subscriber was added to the database.
Address | The e-mail address used for sending messages.
Subscriber | Subscriber details: anonymous / not anonymous, registered/unregistered, the date of registration.
Confirmed | The subscription confirmation status.
Active | Active status of the subscription. If the subscription is active, the subscriber receives newsletter issues. Otherwise, messages are not sent.
Format | The messages format chosen by the subscriber.

How to create a subscriber

To create a new subscriber, use the Add button, which opens the add/change an address form.

How to change subscriber's data

To edit settings of a certain subscriber, double-click the table row of the desired subscriber.


New subscriber (subscriber editor) - Bitrix Site Manager - Content Management & Portal Solutions

New subscriber (subscriber editor)

In this topic

"Subscriber" tab
 "Subscriptions" tab
Control buttons

This form is used to create and edit a single subscriber. Depending on whether you create a new subscriber or edit the existing one, some fields can be present on the form or not.

With this form, you can do the following:

  • create a new or change the existing subscriber;
  • select the subscribers to receive newsletter issues;
  • select the site users to receive newsletter issues;
  • add the subscriber's addresses;
  • edit the subscriber's parameters;
  • send a newsletter issue to subscribers.

Context bar

Button | Description
List | Opens a report form containing information about newsletter subscribers.
Add | Creates a new subscriber.
Delete | Deletes the current subscriber.

"Subscriber" tab

Field | Description
Created | The date the record was added to the database. This field is displayed only when editing the existing subscriber's information.
Modified | The date the subscriber's information was last modified. This field is displayed only when editing the existing subscriber's information.
Subscription confirmed | This checkbox defines whether the subscriber confirms his/her desire to receive newsletters or not.
Subscription confirmation code | The code sent to the subscriber to confirm his desire to receive newsletters. This field is displayed only when editing the existing subscriber's information.
Date of confirmation code generation | The date and time the subscription activation code was generated. This field is displayed only when editing the existing subscriber's information.
Anonymous subscriber | The checkbox defines the subscriber's anonymous status (an anonymous subscriber is not registered on the site).
User (ID) | The ID of a user registered on the site.
Subscription active | The subscription activity status. If the subscription is active, newsletters issues are sent to the subscriber. Otherwise, the subscription is locked.
E-Mail | The subscriber's e-mail address to which newsletter issues are sent.
Send a confirmation code to subscriber... | With this checkbox selected, the subscription confirmation code is sent to the subscriber's address after adding or changing this address.
Send message based on a template of the site | Select site whose template will be used to create and send e-mail messages.

"Subscriptions" tab

Field | Description
Format | Format in which this subscriber receives messages.
Newsletter topics | The newsletter topics whose issues the subscriber is to receive (that is, topics to which the e-mail address is subscribed).

Control buttons

Button | Description
Creating a new subscriber
Add | Adds the new subscriber into the database and goes to the list of subscribers.
Apply | Saves the subscriber's settings. Editing is continued.
Cancel | Closes the subscriber editing form without save.
Editing the existing subscriber
Save | Saves the subscriber's settings and goes to the list of subscribers.
Apply | Saves the subscriber's settings. Editing is continued.
Cancel | Closes the subscriber editing form without save.


Import of addresses - Bitrix Site Manager - Content Management & Portal Solutions

Import of addresses

In this topic

Form fields
Control buttons

This form is used to add destination e-mail addresses, to which your newsletters can be sent, from external files or the form list. You can easily add a large number of e-mail addresses (for example, when replacing old content management system with the Bitrix Site Manager), thus avoiding manual enrollment of addresses.

To import addresses, specify the source (external file or list), set the import parameters and click Import addresses.

Form fields ("Import" tab)

Field | Description
Import from file The path to the local file from which addresses will be imported. In the file, addresses should be separated with comma or new line:

user1@host.com,user1@host.com,user1@host.com,user1@host.com

or

user1@host.com
user1@host.com
user1@host.com
user1@host.com
To find a file from which addresses will be imported, click Browse...
Import from list | As an alternative to importing from a file, you can manually specify addresses in this field by copying them form a text editor and pasting into this field (Ctrl+V). Any other import settings has the same meaning as for importing from file.
Send a subscription confirmation code | If this checkbox is active, a subscription confirmation code will be sent to each imported address.
Mark subscription as confirmed | With this checkbox active, the subscription for each newly added address will be automatically confirmed, even if the subscriber has not obviously confirmed the subscription.
Add subscribers Subscribers can be added as anonymous visitors or registered site users.
  • As anonymous visitors - subscribers will not be registered on the site and no accounts for them will be created.
  • As registered users (creating the account) - subscribers will be registered on the site, and their accounts will be bound to user groups.
Send registration information to users This checkbox is available only if subscribers are added as registered users.

Select this checkbox to send registration information to users (to their e-mail addresses) after enrolling them as site users.
Add users to groups This checkbox is available only if subscribers are added as registered users.

Check this box to added users to user groups. Select groups to which the users should be added. To select more than one group, hold the Ctrl button down while selecting.
Subscribe to... | Select newsletters to which you want to automatically subscribe the users being added.
Format | Select the format of messages in which the subscribers will receive newsletter.
Send emails based on templates of the site | Select the site whose template will be used to create and sent newsletter issues.

Control buttons

Button | Description
Import addresses | Runs the process of importing addresses.


Newsletter topics - Bitrix Site Manager - Content Management & Portal Solutions

Newsletter topics

In this topic

Filter
Form fields

This form is used to create and manage newsletter topics (a newsletter topic is sometimes referred to as a subscription, or even a newsletter, but the correct alias is a mailing list). A newsletter topic, in itself, does not contain subscription issues (messages) or subscribers. Newsletter topics are the convenient way to offer some topics of information to subscribers. For example, you can create a "Company news" newsletter topic and offer your visitors to subscribe to it. If a visitor wants to subscribe to this newsletter topic, their e-mail address will be registered as wanting issues of this newsletter. When creating a newsletter issue (i.e. e-mail message), you can specify that this message should be sent to recipients contained in the "Company news" newsletter topic - the message will be sent to the subscribers of this mailing list.

Filter

The filter is used to set the criteria for selecting newsletter topics to be displayed in the list

Field | Description
ID | The ID of a newsletter topic with which it was registered in the database.
Site | Site to which the newsletter topic is bound.
Active This field allows to pick out mailing lists by the following status:
  • active (users can subscribe to messages of a newsletter topic);
  • non-active;
  • all newsletter topics.
Public | Allows to select only public topics (those that are visible to visitors), not public or both.
Automatic | Allows to select only automatic or non-automatic mailing lists.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Add | Adds a new mailing list (newsletter topic).
Excel | Exports data from the table to the MS Excel format.

Form fields

The form displays existing newsletters. The table below describe the table fields.

Field | Description
Checkbox column | Used to select newsletter topics to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu | Clicking the action button of any newsletter topic opens a menu allowing to edit information about a subscriber, or delete a subscriber.
ID | The newsletter ID with which it was registered in the database.
Name | The newsletter name to be displayed to customers.
Site | Site to which the newsletter is bound.
Sort. | The newsletter sort weight. The more is the value, the higher the newsletter name is positioned in lists.
Active | The newsletter status. If the newsletter is active, visitors can subscribe to it.
Public | Indicates whether the topic is public or not. Public mailing lists can display a link (in the public section of the site) that a visitor can click to subscribe to messages of this mailing list.
Auto | Indicates whether the mailing list is automatic or not. If Yes, messages (issues) of this newsletter topic are generated automatically on the administrator defined schedule.
Generated | If the mailing list is automatic, this field indicates the date and time when a message of this mailing list was last generated. If no messages has been generated so far, this field contains the date and time when the mailing list became automatic.


New topic (newsletter topic editor) - Bitrix Site Manager - Content Management & Portal Solutions

New topic (newsletter topic editor)

In this topic

Form fields
Control buttons

This form is used for creating and editing a newsletter issue.

Context bar

Button | Description
List | Opens a report form containing information about newsletter topics (mailing lists).
Add | Creates a new mailing list.
Delete | Deletes the current mailing list.
Check | Opens a template checking form where you can test your template used to create and send issues of an automatic mailing list. The template checking form displays a message just as the recipients will receive it; as well as message and template parameters. This button is available only for automatic mailing lists.

Form fields

"Subscription" tab

Field | Description
Active | Checking this box enables site visitors to subscribe to the newsletter, and causes the newsletter messages to be actually sent to subscribers
Public | Check this box if you want the newsletter to be visible in the public section so that visitors can subscribe to it.
Site | Choose the site on which the newsletter subscription link is to be displayed.
Name | The name of the newsletter topic (mailing list) just as it will be displayed to subscribers.
Sorting index | The sorting index of the newsletter. The more is this value, the higher is the newsletter positioned in lists.
Description for subscribers | The newsletter description to be displayed to site visitors. Try to compose a brief and concise description.
Automatic | To make a newsletter automated, check this box. For the automated newsletters, sending is carried out as per user-defined schedule.

"Subscription" tab

This section is available only for automated newsletter topics.

Field | Description
Time schedule
Last execution time | In this field, you have to specify the date and time after which the newsletter issues will not be generated. No newsletter issues will be generated and no e-mail messages will be sent after the time specified in this field.
Days of month | If you want the newsletter issues to be generated and sent on the predefined days of month, specify them in this field. For example: 1,2,15-20,25.
Days of week | These options are used to select here days of week when the issues are to be generated and sent. For example, if you want to set up a weekly newsletter which is sent on Mondays, check the box Mo.
Time | Specify here the time when the newsletter issues are to be sent. You can set your newsletter to be generated and sent more than once a day, for example: 8:00, 16:00, 24:00.
Template (this section is available only for automated newsletter)
Templates | In the Template section, select the template that the system will use for the issue generation. If no template exists, the system will display an appropriate message. You can create your templates using the API methods (see CPostingTemplate).
Newsletter fields (this section is available only for automated newsletter)
From | The From field is required to be filled. By default, the sender address specified in the Newsletter module settings is used.

Control buttons

Button | Description
Creating a new newsletter
Add | Adds the newsletter to the database and goes to the list of newsletters.
Apply | Saves the subscription issue parameters. Editing is continued.
Cancel | Closes the editor form.
Editing an existing newsletter
Save | Saves the newsletter parameters and goes to the list of newsletters.
Apply | Saves the newsletter parameters. Editing is continued.
Cancel | Closes the editor form.

See also

Newsletter topics
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Settings - Bitrix Site Manager - Content Management & Portal Solutions

Settings

This form (System settings -> Settings -> Subscription) is designed to set the system-wide parameters of the Subscription module.

Module settings

Parameter | Description
Allow anonymous subscription | With this checkbox selected, users can subscribe to the specified distribution without preliminary registration on the site.
Show authorization links if subscribed anonymously | With this checkbox selected and the anonymous status of the user (the user didn't perform the logon to the system), the hyperlink proposing the user to logon on to the site will be displayed.
Public section containing the subscription edit page | The path to the folder in the public section with the subscription customizing page, relative to the site root path. While setting the path, you can use the #LANG_DIR# macro.
Use visual HTML editor | If this option is enabled, a visual HTML-editor is used by default for creating newsletters.
Interval in seconds for stepwise emailing in the "Direct mail" mode | The delay between newsletters sent to subscribers. The Send a message personally mode is used for sending messages individually to each subscriber with the subscriber's address in the TO field of each message.
Default From e-mail | E-mail address of the sender to be used by default in all messages.
Default To e-mail | E-mail address of the recipient to be used in the TO field of each created message.
Mail message encoding | The list of possible characters codes tables for creating messages.
Allow 8-bit symbols in message header | If this option is enabled, the characters of the extended ASCII encoding (0-255) can be used. Otherwise, such characters (which are usually used for letters of the national alphabet) are displayed in the Base-64 encoding.
Send images as attachments | If this option is enabled, images will be sent as attachments to an e-mail message. Otherwise a message will include only a link to the images.
Days to keep the unconfirmed subscriptions | If the subscriber does not confirm his/her desire to subscribe to the selected distribution (usually, a user can do it by clicking a link and opening a corresponding page from the subscription confirmation message), after the specified number of days this subscription request will be deleted from the database.
Method of automatic sending issues Specifies which method is to be used to schedule the message sending in automated mode:
  • Agent - the automated sending is scheduled using internal facilities of the Bitrix Site Manager;
  • Cron - should be used if the system is installed on a Unix server.
Number of messages to be automatically send by agent during one step in "directly to subscriber" mode | Specifies the number of e-mail messages to be sent at a single run of the agent when sending newsletter messages directly to each recipient.
Method of automatic generation | Indicates the method to be used for the automated generation of newsletter issues.
Check period for the issue generation | Specifies the time interval (in seconds) to elapse before the system checks whether a recurrent newsletter message is to be created.

Module permissions

This form is used to customize the access rights of users in the system, except for the Administrator who always has full access permissions. By setting the "by default" access level, you can easily customize the access policy, for all users with the "by default" access level at once.

You can choose one of the following access levels:

  • denied - access is denied;
  • read - viewing is allowed, any modification is denied;
  • write - both viewing and modification are allowed.
Field | Description
By default | Allows to change the default settings which affects all the user groups with the access level "by default".
[Group of users] | Used to adjust the access settings for a certain group.


Create a subscription list - Bitrix Site Manager - Content Management & Portal Solutions

Create a newsletter

To create a new newsletter, do the following.
  1. Open the List of newsletter form (Newsletter -> Newsletters).
  2. Click the Add button.
  3. Enter the name of the new newsletter to be displayed to users.
  4. Choose the site on which this newsletter will be available.
  5. Specify the newsletter description. It should be brief and concise - using it, site visitors will make a decision whether to subscribe or not.
  6. Select the Active checkbox to immediately activate the newsletter. If it's not active, it will not be displayed in the list of the available newsletters.
  7. Optional step
    You can set the sorting value for a certain newsletter. The more is the value, the higher is the position of the subscription in the list of the available subscriptions.

  8. To save a newsletter, click Add or Apply. (You will returned to the List of newsletters form after clicking the Add button.)


Import the list of subscribers' addresses - Bitrix Site Manager - Content Management & Portal Solutions

Import the list of subscribers' addresses

To add the subscribers' addresses from some external file, first you need to prepare the source file of data.

File preparation

The file containing the subscribers' addresses to import should be properly formatted. Addresses in the file can:

  • be separated with a comma;
  • begin from a new string.

So, a file can look like the following example:

user1@host.com,user1@host.com,user1@host.com,user1@host.com

or

user1@host.com
user1@host.com
user1@host.com
user1@host.com

Import of addresses

  1. Open the Import of addresses form (Newsletter -> Import of addresses).
  2. Click the Browse... button and choose the file with the list of addresses.
  3. If the confirmation code should be sent to the added subscribers, select the Send a confirmation code checkbox.
  4. If it's required to automatically confirm the delivery of the subscription issue to all subscribers, select the Select the subscription confirmation checkbox option.
  5. If you need to register added subscribers on the site and to create a personal account for each subscriber, choose the As users... option in the Add subscribers field.

    If you've chosen the registration of the added subscribers as the site users, then:
    • to send the registration information to each registered user, set the Send registration information... option;
    • choose groups of users which will contain the registered users.
  6. Choose the subscriptions to which the users will be subscribed by default.
  7. Specify the subscription format for sending newsletters to the registered users.
  8. Click the Import addresses button.


Send a message - Bitrix Site Manager - Content Management & Portal Solutions

Send a message

There are several ways of sending messages, depending on their status.

Newly created message

To immediately send the newly created message, click the Send button in the Add issue form.

"Draft" status

If the message was saved in the Add issue form, but was not sent, then you can send it in the following ways:

  • go to the message editing and click the Send button in the Add issue form;
  • click the Send button opposite the message in the List of issues form table.

"Sent" status

To re-send a message, first change its status to Draft.

  1. Open the message for editing by clicking the Edit link opposite the appropriate message.
  2. In the Change status list, choose Draft.
  3. Click Save or Apply.
  4. If you've clicked Save and turned to the List of issues form, click the Send link opposite the required message.
  5. If you've clicked Apply, click Send.


Add a subscriber - Bitrix Site Manager - Content Management & Portal Solutions

Add a subscriber

To manually add a new subscriber, do the following.

  1. Open the List of subscribers form (Suscriptions -> Subscribers).
  2. Click Add.
  3. Fill the form with the appropriate information about the subscriber. You can specify the following data:
    Subscription confirmed
    The checkbox that defines whether the subscriber confirmed his/her desire to receive newsletters or not. You can select theis checkbox obligatorily.
    Anonymous subscriber
    This checkbox defines the subscriber's status of anonymity (the subscriber is anonymous, if he/she is not registered on a site).
    Active subscription
    Select this checkbox, otherwise a subscriber will not receive newsletters.
    E-Mail
    The address to which the subscription issue will be sent.
    Send the confirmation code to a subscriber
    Select this checkbox for the subscriber to receive the subscription confirmation code.
  4. Click Add after the form is completed.


Create a message - Bitrix Site Manager - Content Management & Portal Solutions

Create an issue

To create a new issue, do the following:
  1. Open the List of subscription issues (Newsletter -> Newsletter issues).
  2. Click Add.
  3. Choose the message recipients. You have the following options:
    Subscribers
    Specify the newsletters whose subscribers will receive this issue. When subscribing, the user specifies what newsletters he/she wants to receive; in such a way the newsletter is assigned to the current user. You can narrow the range of the message recipients by specifying a certain subscription format; when sending a message, it will be delivered only to those customers who have specified the appropriate format.
    Site users
    If you want to send the issue to specific site users, you can choose them from this list.
    Additional filtering of addresses
    You can narrow the message recipients list by setting the filter on the e-mail addresses. For example, if needed, you can send an issue only to subscribers from a certain server. You can filter message recipients by their full e-mail address or part of it.
    Additional recipients' addresses
    If you want to send an issue to users not subscribed to any issues and not included into any user groups, you can specify their electronic mail addresses in this field. Use the comma or carriage return as a separator.
  4. Specify the message fields: From, To, Subject. Subscribers which will receive the message will see exactly this text in the corresponded fields.
  5. Finally, enter the text of the message.
    You can select the format of the created message. You cannot format a message in the text mode. The HTML mode allows to use any text formatting of the message body. But some users still prefer to receive messages in the text format. In any case, you can choose the required message format.
  6. Choose the encoding of the message. This field should comply with the encoding used in the created message.
  7. It is recommended to have the Send a message personally to each recipient option enabled.
  8. To save a message, click the Add or Apply button. (You will return to the List of subscription issues form after clicking the Add button.)

    Click Send to send the message immediately.


Helpdesk - Bitrix Site Manager - Content Management & Portal Solutions

Helpdesk

A comprehensive web-portal, no matter whether it's an information site or an online-store, is so stuffed with various features that users may find it hard to navigate it. In addition, many companies would like to quickly respond to clients' questions thus maintaining the company reputation. It's especially important for web-portals tailored at providing to clients online consultations related to software and hardware performance, etc. A properly structured and organized site should be able to promptly react to clients' requests and address them to technical support engineers according to topics.

The technical support module allows organizing on your site the system of making requests to the group of specialists in charge of consulting and providing technical support to the company clients.


Desktop - Bitrix Site Manager - Content Management & Portal Solutions

Desktop

The desktop contains a number of summary reports related to the technical support group operation. These reports are generated by using the following tables consisting of assigned, closed or open tickets:

  • employees of technical support group responsible for tickets;
  • ticket emergency;
  • current state;
  • ticket category;
  • ticket source;
  • reply estimates.

Filter

A filter is used to set the parameters for selecting report components. It allows to find the required ticket for the specific period of time and tickets assigned to specific support group members.

The table that follows describes the filter fields.

Parameter | Description
Range of dates | Range of dates for which tickets and technical support replies should be displayed. You can either select the number of days starting from the current date, or define the range of dates by using calendars.
Sites | Sites for which information should be displayed.
Person responsible | If you have rights of the technical support administrator, you can filter the report by any employee of the technical support group, i.e. include into the report tickets and replies only from some specific person. You can also define the name of the person responsible, either full or partial. For exact search by the search field, select the appropriate checkbox next to the search word or phrase. In this field, you can use special logical expressions. To see the syntax of the expressions, click ? next to the appropriate field.
Show the number of tickets | When selected, this option allows to display the total number of messages in all tickets (column [7]).

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Show messages | Selecting yes in the popup menu adds a Messages column to tables.

Summary reports

All reports display the number of closed and open tickets. Open tickets are ranked according to their source:

- the last message was added by a member of the technical support group;
- the last message was added by a client;
- ticket is closed.

Responsible

This report shows open and closed tickets and the total number of tickets assigned to specific employees of the technical support group. Open tickets are ranked according to the source of the last message in the ticket: support group member or opponent.

Responsible |  |  |  | Open | Total
[1] | [2] | [3] | [4] | [5] | [6]
  1. A member of the techsupport staff whose ticket statistics is displayed.
  2. Number of open tickets to which the last message was added by a techsupport client.
  3. Number of open tickets to which the last message was added by the techsupport staff member.
  4. Number of closed tickets.
  5. Total number of open tickets for which this employee is responsible.
  6. Total number of all tickets for which this employee is responsible.

Emergency

This report shows open and closed tickets in different emergency states. Open tickets are ranked according to their states.

Emergency |  |  |  | Open | Total
[1] | [2] | [3] | [4] | [5] | [6]
  1. Ticket emergency.
  2. Number of open tickets in this emergency level, to which the last message was added by a techsupport client.
  3. Number of open tickets in this emergency level, to which the last message was added by a techsupport staff member.
  4. Number of closed tickets in this emergency level.
  5. Total number of open tickets in this emergency level.
  6. Total number of all tickets in this emergency level.

Status

This report shows open and closed tickets and the total number of tickets in different status. Open tickets are ranked according to the source of the last message in the ticket - technical support member or opponent (client).

Status |  |  |  | Open | Total
[1] | [2] | [3] | [4] | [5] | [6]
  1. Status.
  2. Number of open tickets in this status, to which the last message was added by a techsupport client.
  3. Number of open tickets in this status, to which the last message was added by a techsupport staff member.
  4. Number of closed tickets in this status.
  5. Total number of open tickets in this status.
  6. Total number of all tickets in this status.

Category

The technical support system supports the so called ticket categories, i.e. standard topics to which a ticket can relate. For example, delivery issues, payment issues, etc.

This report shows open and closed tickets and the total number of tickets in the current category. Open tickets are ranked according to the source of the last message in the ticket - support group member or opponent.

Category |  |  |  | Open | Total
[1] | [2] | [3] | [4] | [5] | [6]
  1. Ticket category.
  2. Number of open tickets in this status, to which the last message was added by a techsupport client.
  3. Number of open tickets in this status, to which the last message was added by a techsupport staff member.
  4. Number of closed tickets in this status.
  5. Total number of open tickets in this status.
  6. Total number of all tickets in this status.

Sources

The source of a techsupport ticket can be any communication facility such as a phone, fax, e-mail, ICQ, etc. The technical support system allows to range tickets according to their source.

This report shows open and closed tickets and the total number of tickets from some specific source. Open tickets are ranged according to the source of the last message in the ticket - support group member or opponent.

Source |  |  |  | Open | Total
[1] | [2] | [3] | [4] | [5] | [6]
  1. Ticket source.
  2. Number of open tickets originating from this source, to which the last message was added by a techsupport client.
  3. Number of open tickets from this source, to which the last message was added by a techsupport staff member.
  4. Number of closed tickets from this source.
  5. Total number of open tickets from this source.
  6. Total number of all tickets from this source.

Answer rates

This report shows open and closed tickets and the total number of tickets ranged by the techsupport performance evaluated by clients. Open tickets are ranged according to the source of the last message in the ticket - techsupport member or opponent.

Answer rate |  |  |  | Open | Total
[1] | [2] | [3] | [4] | [5] | [6]
  1. The name of the answer rate.
  2. Number of open tickets with this rate, to which the last message was added by a techsupport client.
  3. Number of open tickets with this rate, to which the last message was added by a techsupport staff member.
  4. Number of closed tickets with this rate.
  5. Total number of open tickets with this rate.
  6. Total number of all tickets with this rate.

Support levels

This report shows open and closed tickets and the total number of tickets by their support level. Support levels are used to rank techsupport client to give them different priorities.

Support levels |  |  |  | Open | Total
[1] | [2] | [3] | [4] | [5] | [6]
  1. The name of the support level.
  2. Number of open tickets in this level, to which the last message was added by a techsupport client.
  3. Number of open tickets in this level, to which the last message was added by a techsupport staff member.
  4. Number of closed tickets in this level.
  5. Total number of open tickets in this level.
  6. Total number of all tickets in this level.


Tickets - Bitrix Site Manager - Content Management & Portal Solutions

Tickets

In this topic

Filter
List of tickets
Operations with tickets

The Tickets form displays users' requests to technical support. This form allows you to do the following:

  • view users' tickets;
  • edit and delete tickets;
  • change states of tickets.

Each ticket, besides having different states and rankings, can be marked as spam.

Filter

To display only the required tickets, set the filters according to the search criteria. The following table describes the filter fields.

Parameter | Description
*Ticket ID | The ticket ID. The required ID's can be separated with commas.
Site | The site where the ticket was created.
Indicator You can choose one or several markers for filtering tickets:
  • - the last message was added by a client (you are responsible);
  • - the last message was added by a client (you are not responsible);
  • - the last message was added by you ;
  • - the last message was added by a technical support staff member;
  • - ticket is closed.
    • Closed/open Closed - ticket is closed;
    Open - ticket is not closed.
    Definitely spam | Defines whether spam, non-spam or all messages should be displayed.
    Probably spam | Same as the previous one but for messages with the "probable spam" state.
    Created | Range of dates within which a ticket could be created.
    Modified | Range of dates within which a ticket could be last modified.
    * Author | An author of tickets to be displayed.
    * Modified by | Search by the name of a techsupport member who changed the required tickets.
    * Responsible | Search by the name of a tech support member responsible for the ticket.
    Problem solving duration | Allows to display tickets that took a definite amount of time (days) to be solved.
    Messages | Range of messages in the tickets to be displayed.
    Category | Category of the tickets to be displayed.
    Emergency | Emergency of the tickets to be displayed.
    State | State of the tickets to be displayed.
    Answer rate | Display tickets with a definite answer rate.
    Source | The ticket source. Select web to display tickets posted from the site.
    * Title | Mask for the title of the tickets to be displayed.
    * Note | Mask for the comment text for the tickets to be displayed.
    * Message text | Mask for the message text for the tickets to be displayed.

    * - these fields allow using logical expressions. You can seen the syntax of expressions by clicking ? next to the appropriate field.

    Context bar

    Button | Description
Add | Opens a form in which you can create a new ticket.
Excel | Exports data from the table to the MS Excel format.

    List of tickets

    Column | Description
    Checkbox column | Used to select tickets to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any ticket opens a menu allowing to:
    • Modify - edit the ticket;
    • Open - moves the previously closed ticket to the open state;
    • Mark as a possible spam;
    • Mark as spam;
    • Mark as spam and delete;
    • Delete - delete the ticket.
    ID | The ID of the ticket. Click the ID to open the ticket editing form.
    Indicator The ticket status indicator:
  • - the last message was added by a client (you are responsible);
  • - the last message was added by a client (you are not responsible);
  • - the last message was added by you ;
  • - the last message was added by a technical support staff member;
  • - ticket is closed.
    • Subject | The ticket subject.
    Author | Person who created the ticket, and the time when it was created.
    Modified by | Person who last modified the ticket.
    Msg. | Number of messages in the ticket.
    Level | The level of the ticket.
    Responsible | Person who is in charge of this ticket.
    Selected | Number of tickets selected to display.
    Checked | Number of tickets marked.

    Operations with tickets

    The action bar allows to perform various operations on several tickets simultaneously. To apply an action to a number of tickets, select them in the left column of the table. To notify site users with the access right technical support administrator about the changes, select a command with the notify instruction.

    The following actions are available.

    Close
    Closes a ticket.
    Open
    Opens a ticket. Open tickets allow to create new tickets.
    Deselect the probable spam checkbox
    Deselects the probable spam checkbox of the ticket.
    Mark as probable spam
    Selects the probable spam checkbox of the ticket.
    Mark as spam
    Identifies the tickets as spam.
    Mark as spam and delete
    Identifies the ticket as spam and deletes it.
    Delete
    Deletes a ticket.


Diagrams - Bitrix Site Manager - Content Management & Portal Solutions

Diagrams

This form displays a technical support load graph and diagrams illustrating the quality of technical support operation.

Filter

The filter is used to set the parameters for selecting elements for building graphs. By using the filter, you can significantly reduce the amount of information displayed on graphs. The following table describes the filter fields.

Parameter | Description
Period | Defines for which period of time the data is to be displayed on graphs. To set the required range of dates, you can use either a list with the number of days or calendar fields.
Sites | Sites containing data which will be used for building graphs.
Responsible This field allows to build graphs only for the specified persons. To use this field, you need the techsupport administrator's permissions.

In this field, you can use special logical expressions. You can see the syntax of expressions by clicking ? next to the field.
Support level | Filters data by the ticket support level.
Category
Emergency
Status
Answer rate
Source 		Instructs to display information on tickets:
  • of the specified category;
  • having the specified emergency level;
  • having the specified status or answer rate;
  • originating from the specified source.
Elements to be displayed on graphs This field allows you to specify which graphs should be displayed:
  • open tickets;
  • closed tickets;
  • all tickets;
  • messages;
  • overdue messages.

Click Set filter to activate the filter. To display all information, click Cancel.

Graphs

Graph of technical support load

This graph displays the number of tickets and messages in the technical support system. This reflects the technical support service load for the specified date and can be used for decision making related to the technical support group performance.

Example of graph

Click on image to enlarge

Click on image to enlarge

Diagram of problem solution length

This graph displays an average number of days required to resolve technical support problems.

Diagram displaying the number of messages required to resolve a problem

This diagram displays the percentage of the number of messages in closed tickets.


New ticket (ticket editor) - Bitrix Site Manager - Content Management & Portal Solutions

New ticket (ticket editor)

This form is designed to add tickets manually in the technical support service.

If a ticket is being created by a person who is not a member of the techsupport service, the person in charge can be appointed automatically depending on the category, emergency or source of the ticket. If the person in charge has not been appointed, and if the parameter Default person in charge is set in the module settings, the default responsible person will be set. After the ticket is added to the database, the person in charge will be notified by e-mail. In case the person in charge has not been selected, the notification will be sent to e-mail addresses of all users having the technical support administrator permission (including users of the group #1).

If a person who is responsible for the ticket changes the latter, the ticket author will be notified. If the ticket is changed by its author, the person in charge or the support administrator will be notified. If a new person in charge is being appointed, both the ticket author and the new person in charge will be notified. If you deselect the Hide a message, not notify an author checkbox, the author of the ticket will not be notified.

Changing a ticket means:

  • changing its category, emergency, state or ranking answers;
  • appointing a new person responsible for the ticket;
  • adding a new ticket;
  • closing or opening a ticket.

Context bar

Button | Description
List | Opens the list of tickets.
Create | Creates a new ticket.
Close | Closes the current ticket.
Delete | Deletes the current ticket.
Spam Opens a context menu with commands allowing to:
  • Mark the ticket as possible spam;
  • Mark the ticket as doubtless spam;
  • Mark the ticket as doubtless spam and delete.

"Ticket" tab

Field | Description
Site | The site where the ticked was created.
Author | Source and author of the ticket.
Created The date and time when the ticket was created; name of the user who created a ticket.

This field is displayed only in the ticket editing mode.
Modified The date and time when the ticket was last modified; person who modified the ticket.

This field is displayed only in the ticket editing mode.
Closed The date and time when the ticket was closed.

This field is displayed only in the ticket editing mode.
Discussion

This section is displayed only in the ticket editing mode.
  • # - ticket number. Defines the order in which tickets are displayed in the discussion.
  • Author - author of the ticket.
  • Created - the time when the ticket was created.
  • [Quote] – if clicked, inserts the selected text enclosed in quotation tag.
  • [Original] - link to the original e-mail message in the Mail module (if the message was created in the e-mail module).
  • [Change] – edits the message. Available to administrators only.
  • [Delete] – deletes a message. Available to administrators only.
Image and message body
Hide a message, do not notify author Select this checkbox to create a message as hidden from the ticket author (if he doesn't belong to the support group). Any changes being made at the moment will not be e-mailed to the author; the technical support group will be notified about these changes.

This field is displayed only in the ticket editing mode.
Do not change ticket status | When editing the ticket, this option prevents the ticked status from changing.
Source / Author | In this group, a technical support engineer can specify the message source and author. If the support engineer is entitled with the Read right for the main module, users can be selected in an additional window (button "..."). In addition, when the user ID is entered, information about this user (login, name) will be displayed next to it.
Message template In the drop-down list, the administrator or the person responsible can select the reply template.

This field is displayed only in the ticket editing mode.
Message | Field for entering a new message.
Attach files | Field for inserting an image of the new message.
Status | Ticket state.
Responsible | User responsible for the message.
Emergency | Ticket emergency.
Answer rate Estimate of replies provided by the ticket author.

This field is displayed only in the ticket editing mode.
Category | Ticket category.
Support level | The techsupport level required for this ticket.
Close if no reply occurs within | Number of days to wait before auto-closing the ticket.
Close Checkbox that allows to open or close a ticket.

This field is displayed only in the ticket editing mode.
Comments Any comments. Visible only to the techsupport group members.

This field is displayed only in the ticket editing mode.

If you are a technical support group member , you can specify any author and source of the ticket when you create or add a new message to it. By default, all operations will be performed on your behalf. The default source is <web>.

If you are a site administrator or a person responsible for the ticket, the following fields for modification are available to you:

  • Ticket category;
  • Person responsible for the ticket;
  • Ticket state;
  • Close a ticket;
  • Administrator note.

If you are an author of the ticket, the following fields for modification are available to you:

  • Ticket emergency;
  • Answer rate.

"Edit message settings" tab

Direct message editing is available only to the site administrator or the technical support administrator.

Field | Description
Source / Author | Message source and author.
Created | The date and time the message was created.
Number | Message serial number used to display the message in the discussion. This field is displayed only in the ticket editing mode.
Spam mark | Allows to mark the message as spam or potential spam.
Hidden | Specifies the message will not be visible to a techsupport client.
Log | Specifies to keep log of this message.
Message was overdue | Indicates that a reply to this message was not given in proper time.
Message | Message body.
Attach new files | These fields allow to attach files to the message (e.g. images).
ID of initial external source | The ID of the message source, e.g. e-mail message ID.
Additional field of initial external source | Any additional information about the external source (e.g. e-mail message headers).


Categories (technical support dictionary) - Bitrix Site Manager - Content Management & Portal Solutions

Categories (technical support dictionary)

In this topic

Filter
Dictionary records
How to create a dictionary record
How to change a dictionary record

This form is designed to customize the technical support dictionaries. These are used to display categories, emergencies, states, estimates, ticket sources and frequent replies.

By default, the form for customizing technical support dictionaries shows the dictionary selected in the left part of the administrative section (categories, emergencies, etc.) by automatically selecting the Type field of the filter by some specific dictionary. You can simultaneously display all the dictionaries by clicking Clear.

Filter

Parameter | Description
Find | This field is the shortcut to finding the desired record by the most frequently used parameters: title or description.
* ID | Lookup records by their ID.
Site | Display only dictionary records for a specific site.
* Title | Title of the dictionary records to be displayed.
* Description | Search a record by the description text.
* Mnemonic code | The mnemonic code of the required dictionary type.
* Responsible | A techsupport member responsible for new tickets. Used with categories and emergencies.
Default | Defines whether the default, non-default or all dictionaries should be displayed.

* - these fields allow special logical expressions.

Context bar

Button | Description
Add | Adds a new dictionary record of the type that can be selected in the pop-up menu.
Excel | Exports data from the table to the MS Excel format.

Dictionary records

The table below displays records of the selected dictionary. To sort the table by a desired field, click on the corresponding column header.

Checkbox column | Action menu | ID | Sort. | Sites | Title | Responsible
[1] | [2] | [3] | [4] | [5] | [6] | [7]
Selected: [8] | Checked: [9] |
  1. Used to select records to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any ticket opens a menu allowing to:
    • Modify - edit the record;
    • Delete - delete the record.
  3. The ID of the dictionary record in the database.
  4. The sorting index that is applied to a ticket when it changes.
  5. The site where this record should be visible.
  6. The record title.
  7. A techsupport member responsible for the record.
  8. Number of records selected from the database.
  9. Number of records marked in [1].

How to create a dictionary record

To create a new record in the dictionary, click Add. In the Dictionary record editor form, set the parameters of the new record.

How to change a dictionary record

To edit an existing dictionary ticket, double-click a row of the desired record. In the Dictionary record editor form, set the parameters of the ticket.


Urgency levels (technical support dictionary) - Bitrix Site Manager - Content Management & Portal Solutions

Urgency levels (technical support dictionary)

In this topic

Filter
Dictionary records
How to create a dictionary record
How to change a dictionary record

This form is designed to customize the technical support dictionaries. These are used to display categories, emergencies, states, estimates, ticket sources and frequent replies.

By default, the form for customizing technical support dictionaries shows the dictionary selected in the left part of the administrative section (categories, emergencies, etc.) by automatically selecting the Type field of the filter by some specific dictionary. You can simultaneously display all the dictionaries by clicking Clear.

Filter

Parameter | Description
Find | This field is the shortcut to finding the desired record by the most frequently used parameters: title or description.
* ID | Lookup records by their ID.
Site | Display only dictionary records for a specific site.
* Title | Title of the dictionary records to be displayed.
* Description | Search a record by the description text.
* Mnemonic code | The mnemonic code of the required dictionary type.
* Responsible | A techsupport member responsible for new tickets. Used with categories and emergencies.
Default | Defines whether the default, non-default or all dictionaries should be displayed.

* - these fields allow special logical expressions.

Context bar

Button | Description
Add | Adds a new dictionary record of the type that can be selected in the pop-up menu.
Excel | Exports data from the table to the MS Excel format.

Dictionary records

The table below displays records of the selected dictionary. To sort the table by a desired field, click on the corresponding column header.

Checkbox column | Action menu | ID | Sort. | Sites | Title | Responsible
[1] | [2] | [3] | [4] | [5] | [6] | [7]
Selected: [8] | Checked: [9] |
  1. Used to select records to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any ticket opens a menu allowing to:
    • Modify - edit the record;
    • Delete - delete the record.
  3. The ID of the dictionary record in the database.
  4. The sorting index that is applied to a ticket when it changes.
  5. The site where this record should be visible.
  6. The record title.
  7. A techsupport member responsible for the record.
  8. Number of records selected from the database.
  9. Number of records marked in [1].

How to create a dictionary record

To create a new record in the dictionary, click Add. In the Dictionary record editor form, set the parameters of the new record.

How to change a dictionary record

To edit an existing dictionary ticket, double-click a row of the desired record. In the Dictionary record editor form, set the parameters of the ticket.


States (technical support dictionary) - Bitrix Site Manager - Content Management & Portal Solutions

States (technical support dictionary)

In this topic

Filter
Dictionary records
How to create a dictionary record
How to change a dictionary record

This form is designed to customize the technical support dictionaries. These are used to display categories, emergencies, states, estimates, ticket sources and frequent replies.

By default, the form for customizing technical support dictionaries shows the dictionary selected in the left part of the administrative section (categories, emergencies, etc.) by automatically selecting the Type field of the filter by some specific dictionary. You can simultaneously display all the dictionaries by clicking Clear.

Filter

Parameter | Description
Find | This field is the shortcut to finding the desired record by the most frequently used parameters: title or description.
* ID | Lookup records by their ID.
Site | Display only dictionary records for a specific site.
* Title | Title of the dictionary records to be displayed.
* Description | Search a record by the description text.
* Mnemonic code | The mnemonic code of the required dictionary type.
* Responsible | A techsupport member responsible for new tickets. Used with categories and emergencies.
Default | Defines whether the default, non-default or all dictionaries should be displayed.

* - these fields allow special logical expressions.

Context bar

Button | Description
Add | Adds a new dictionary record of the type that can be selected in the pop-up menu.
Excel | Exports data from the table to the MS Excel format.

Dictionary records

The table below displays records of the selected dictionary. To sort the table by a desired field, click on the corresponding column header.

Checkbox column | Action menu | ID | Sort. | Sites | Title | Responsible
[1] | [2] | [3] | [4] | [5] | [6] | [7]
Selected: [8] | Checked: [9] |
  1. Used to select records to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any ticket opens a menu allowing to:
    • Modify - edit the record;
    • Delete - delete the record.
  3. The ID of the dictionary record in the database.
  4. The sorting index that is applied to a ticket when it changes.
  5. The site where this record should be visible.
  6. The record title.
  7. A techsupport member responsible for the record.
  8. Number of records selected from the database.
  9. Number of records marked in [1].

How to create a dictionary record

To create a new record in the dictionary, click Add. In the Dictionary record editor form, set the parameters of the new record.

How to change a dictionary record

To edit an existing dictionary ticket, double-click a row of the desired record. In the Dictionary record editor form, set the parameters of the ticket.


Answer rates (technical support dictionary) - Bitrix Site Manager - Content Management & Portal Solutions

Answer rates (technical support dictionary)

In this topic

Filter
Dictionary records
How to create a dictionary record
How to change a dictionary record

This form is designed to customize the technical support dictionaries. These are used to display categories, emergencies, states, estimates, ticket sources and frequent replies.

By default, the form for customizing technical support dictionaries shows the dictionary selected in the left part of the administrative section (categories, emergencies, etc.) by automatically selecting the Type field of the filter by some specific dictionary. You can simultaneously display all the dictionaries by clicking Clear.

Filter

Parameter | Description
Find | This field is the shortcut to finding the desired record by the most frequently used parameters: title or description.
* ID | Lookup records by their ID.
Site | Display only dictionary records for a specific site.
* Title | Title of the dictionary records to be displayed.
* Description | Search a record by the description text.
* Mnemonic code | The mnemonic code of the required dictionary type.
* Responsible | A techsupport member responsible for new tickets. Used with categories and emergencies.
Default | Defines whether the default, non-default or all dictionaries should be displayed.

* - these fields allow special logical expressions.

Context bar

Button | Description
Add | Adds a new dictionary record of the type that can be selected in the pop-up menu.
Excel | Exports data from the table to the MS Excel format.

Dictionary records

The table below displays records of the selected dictionary. To sort the table by a desired field, click on the corresponding column header.

Checkbox column | Action menu | ID | Sort. | Sites | Title | Responsible
[1] | [2] | [3] | [4] | [5] | [6] | [7]
Selected: [8] | Checked: [9] |
  1. Used to select records to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any ticket opens a menu allowing to:
    • Modify - edit the record;
    • Delete - delete the record.
  3. The ID of the dictionary record in the database.
  4. The sorting index that is applied to a ticket when it changes.
  5. The site where this record should be visible.
  6. The record title.
  7. A techsupport member responsible for the record.
  8. Number of records selected from the database.
  9. Number of records marked in [1].

How to create a dictionary record

To create a new record in the dictionary, click Add. In the Dictionary record editor form, set the parameters of the new record.

How to change a dictionary record

To edit an existing dictionary ticket, double-click a row of the desired record. In the Dictionary record editor form, set the parameters of the ticket.


Frequent answers (technical support dictionary) - Bitrix Site Manager - Content Management & Portal Solutions

Frequent answers (technical support dictionary)

In this topic

Filter
Dictionary records
How to create a dictionary record
How to change a dictionary record

This form is designed to customize the technical support dictionaries. These are used to display categories, emergencies, states, estimates, ticket sources and frequent replies.

By default, the form for customizing technical support dictionaries shows the dictionary selected in the left part of the administrative section (categories, emergencies, etc.) by automatically selecting the Type field of the filter by some specific dictionary. You can simultaneously display all the dictionaries by clicking Clear.

Filter

Parameter | Description
Find | This field is the shortcut to finding the desired record by the most frequently used parameters: title or description.
* ID | Lookup records by their ID.
Site | Display only dictionary records for a specific site.
* Title | Title of the dictionary records to be displayed.
* Description | Search a record by the description text.
* Mnemonic code | The mnemonic code of the required dictionary type.
* Responsible | A techsupport member responsible for new tickets. Used with categories and emergencies.
Default | Defines whether the default, non-default or all dictionaries should be displayed.

* - these fields allow special logical expressions.

Context bar

Button | Description
Add | Adds a new dictionary record of the type that can be selected in the pop-up menu.
Excel | Exports data from the table to the MS Excel format.

Dictionary records

The table below displays records of the selected dictionary. To sort the table by a desired field, click on the corresponding column header.

Checkbox column | Action menu | ID | Sort. | Sites | Title | Responsible
[1] | [2] | [3] | [4] | [5] | [6] | [7]
Selected: [8] | Checked: [9] |
  1. Used to select records to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any ticket opens a menu allowing to:
    • Modify - edit the record;
    • Delete - delete the record.
  3. The ID of the dictionary record in the database.
  4. The sorting index that is applied to a ticket when it changes.
  5. The site where this record should be visible.
  6. The record title.
  7. A techsupport member responsible for the record.
  8. Number of records selected from the database.
  9. Number of records marked in [1].

How to create a dictionary record

To create a new record in the dictionary, click Add. In the Dictionary record editor form, set the parameters of the new record.

How to change a dictionary record

To edit an existing dictionary ticket, double-click a row of the desired record. In the Dictionary record editor form, set the parameters of the ticket.


Sources (technical support dictionary) - Bitrix Site Manager - Content Management & Portal Solutions

Sources (technical support dictionary)

In this topic

Filter
Dictionary records
How to create a dictionary record
How to change a dictionary record

This form is designed to customize the technical support dictionaries. These are used to display categories, emergencies, states, estimates, ticket sources and frequent replies.

By default, the form for customizing technical support dictionaries shows the dictionary selected in the left part of the administrative section (categories, emergencies, etc.) by automatically selecting the Type field of the filter by some specific dictionary. You can simultaneously display all the dictionaries by clicking Clear.

Filter

Parameter | Description
Find | This field is the shortcut to finding the desired record by the most frequently used parameters: title or description.
* ID | Lookup records by their ID.
Site | Display only dictionary records for a specific site.
* Title | Title of the dictionary records to be displayed.
* Description | Search a record by the description text.
* Mnemonic code | The mnemonic code of the required dictionary type.
* Responsible | A techsupport member responsible for new tickets. Used with categories and emergencies.
Default | Defines whether the default, non-default or all dictionaries should be displayed.

* - these fields allow special logical expressions.

Context bar

Button | Description
Add | Adds a new dictionary record of the type that can be selected in the pop-up menu.
Excel | Exports data from the table to the MS Excel format.

Dictionary records

The table below displays records of the selected dictionary. To sort the table by a desired field, click on the corresponding column header.

Checkbox column | Action menu | ID | Sort. | Sites | Title | Responsible
[1] | [2] | [3] | [4] | [5] | [6] | [7]
Selected: [8] | Checked: [9] |
  1. Used to select records to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
  2. Clicking the action button of any ticket opens a menu allowing to:
    • Modify - edit the record;
    • Delete - delete the record.
  3. The ID of the dictionary record in the database.
  4. The sorting index that is applied to a ticket when it changes.
  5. The site where this record should be visible.
  6. The record title.
  7. A techsupport member responsible for the record.
  8. Number of records selected from the database.
  9. Number of records marked in [1].

How to create a dictionary record

To create a new record in the dictionary, click Add. In the Dictionary record editor form, set the parameters of the new record.

How to change a dictionary record

To edit an existing dictionary ticket, double-click a row of the desired record. In the Dictionary record editor form, set the parameters of the ticket.


Creating and editing a dictionary ticket - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a dictionary record

This form is designed to create and edit tickets in the technical support dictionary such as:

  • categories;
  • emergencies;
  • states;
  • answer rates;
  • ticket sources;
  • frequent answers.

The table below describes the fields to fill when editing dictionary tickets.

Context bar

Button | Description
Dictionary | Opens the dictionary for the current type of record.
Create a new record | Creates a new record of the current type.
Delete record | Deletes the current record.

"Record" tab

Field | Description
Type | Dictionary ticket type.
Sites | Sites on which the current record should be displayed. This field is not used with frequent replies.
Sorting index | Sorting order in which tickets are displayed.
Title | Ticket name.
Mnemonic code | The CTicket::SetTicket function accepts not only the dictionary ticket type ID's, but also the mnemonic codes thus simplifying programming. You can enter the desired code here.
Description | For types such as category, emergency, rates and status, this field is used for the tooltip. For the "frequent answer" type, this field is used to enter the answer text.
Set as default... | If checked, the current record will be set as the default selection in the new ticket creation form.
Responsible | Person responsible for the ticket. Values in this field can be modified only for the following types: category and emergency.

"Statistics" tab

Field | Description
event1 | The event1 ID of the event type for the statistics module.
event2 | The event2 ID of the event type for the statistics module.
event3 | Additional parameter of the event for the statistics module.

Control buttons

Control button | Description
Save | Saves the dictionary ticket parameters in the database.
Apply | Save the subscriber's parameters. Editing goes on.
Clear | Clears all the data after the form opening.


Support levels (SLA)

In this section

  • Filter
  • Table

    • This form can be used to create and edit support levels. Support levels are used to range and identify priorities of different users to receive support services.

    Filter

    Parameter | Description
*Name | Filters levels by their names.
*ID | Specifies to display levels by their ID's.
Site | Specifies to display levels of the specified site.
*Description | Filters levels by their description.

    * - these fields allow using logical expressions. You can seen the syntax of expressions by clicking ? next to the appropriate field.

    Context bar

    Button | Description
Add | Click to add a new support level.
Excel | Exports data from the table to the MS Excel format.

    Table

    The table below displays site users. To sort the table by a desired field, click on the corresponding column header.

    Column | Description
    Checkbox column | Used to select levels to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any level opens a menu allowing to:
    • Modify - edits the level;
    • Delete - deletes the level.
    ID | The level ID.
    Priority | The service priority weight.
    Site | The site on which the level is effective.
    Name | The name of the service level.
    Response time | Maximum period of time within which replies to tickets are to be given, for this support service level.
    User groups | User groups for which the support level is effective.
    Responsible | The default person responsible for tickets of this level.
    Selected | Number of records selected from the database.
    Checked | Number of records marked.


Settings (Helpdesk) - Bitrix Site Manager - Content Management & Portal Solutions

Settings

This form (System settings -> Settings) is intended for customizing the system settings for the Helpdesk module.

Parameter | Description
Technical support directory (#LANG_DIR# - site directory) | Path to the technical support scripts in the public section of the site.
Max size of images loaded (Kb) | Maximum size of loaded images for users not belonging to the technical support group.
Display data about users that viewed the ticket for the last (sec.) | Timeframe (sec.) after expiration of which information about the user that viewed the ticket will not be displayed.
Default value for the checkbox "Hide a message, not notify an author" | If you set this parameter while editing the ticket, the checkbox "Hide a message, not notify an author" will be selected by default.
Default person responsible for new tickets | If a new ticket is created by a a non-engineer of technical support, the person in charge may be selected depending on the ticket category, emergency or source (these parameters can be set in the technical support dictionary). If the person in charge is not defined, the default person responsible for it will be selected in this field.

You can set the following access rights on the form of access rights editing:

Access denied
Access to menus and administrative files of the module is denied; users cannot create tickets.
Technical support client
Access to the administrative menu Tickets is granted; it's allowed to create and edit tickets in the administrative and public files.
Technical support engineer
Access to all menu items and module pages is granted. The user can operate on all tickets he's responsible for.
Demo access
The user can view all tickets.
Technical support administrator
The user can edit the technical support dictionary and any tickets.

All the rights mentioned above are heritable.


Forum - Bitrix Site Manager - Content Management & Portal Solutions

Forum

A well-organized web-portal allows its users to communicate with each other, ask questions which can be addressed to both visitors and the site administration. The main mean of such communication is a forum which, to a certain extent, can be used as an addition to a usual technical support service. Besides, the forum is the best SEO tool to attract new visitors to the site, as search engines usually index the forum message text in addition to the main site contents.

The forum module serves to create and manage site forums. The main features of this module enable you to:

  • Build and easily modify the forum public section using the module API's high-level functions and classes;
  • Create the required number of forums;
  • Flexibly regulate the user access permissions for reading and posting forum messages;
  • Create the moderated or post-moderated forums;
  • Assign the forum moderator status to a group of employees;
  • Assign ranks to users according to the number of points given to a user according to his/her forum messages. Also these points can be given to a user by other forum users;
  • Customise forum settings;
  • Perform many other operations.


Forum management - Bitrix Site Manager - Content Management & Portal Solutions

Forums

In this section

  • Filter
  • Context bar
  • List of forums
    •

    The Forums form (Services -> Forums -> List of forums) contains information about the existing forums and allows to create new forums and manage the existing ones.

    Filter

    The filter is used to select the forums matching the parameters specified.

    Field | Description
Site | A site to which the forum belongs.
Active | Filters forums by the active state.
Forum group | A group to with the forum belongs.

    To filter forums by the specified search criteria, click Set filter. To have all forums displayed, click Cancel.

    Context bar

    Button | Description
New forum | Opens a form in which you can create a new forum.
Excel | Exports data from the table to the MS Excel format.

    List of forums

    Column | Description
    Checkbox column | Selects the forums to which the desired actions are to be applied.
    Action menu
             Actions on a forum:
    • Modify forum settings;
    • Delete forum.
    ID | The ID of the forum in the system.
    Active | The flag indicating the forum is active. If No, the forum is unavailable in the public section.
    Site | Site(s) to which the forum belongs.
    Sort. | The forum sort weight. Defines the forum position in lists.
    Name | An arbitrary name of the forum.


Creating and editing a forum - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a forum

In this section

  • Context bar
  • Editing form
  • Forum
  • Settings
  • Access
    •
  • Control buttons
    •

    This form can be used to create a new forum and edit existing forums.

    Context bar

    Button | Description
Forums | Opens a page containing the list of forums.
New forum | Creates a new forum in this form. The button is displayed when editing the existing forum only.
Delete forum | Deletes the forum being edited.

    Editing form

    "Forum" tab

    This tab is used to specify the forum parameters.

    Field | Description
    Active | Specifies whether the forum is active or not. Inactive forums are available only to those users who have full access to them.
    Forum Group | The group to which the forum belongs. None is possible (i.e. the forum does not belong to any group).
    *Sorting index | The forum sort weight. Defines the forum position in lists. The higher the field value is, the lower is the forum position in lists.
    *Forum name | The arbitrary forum name.
    Description | The forum description. The description will be displayed in the public section below the forum title.
    Sites where this forum is available / Path template to forum message
    Site | Sites on which the forum will be available.
    Path template The template of the path to the forum messages of this site. The field is used when sending e-mails from the forum and indexing the forum messages in the Search module.

    Example of path template:
    /en/forum/read.php?FID=#FORUM_ID#&TID=#TOPIC_ID#&MID=#MESSAGE_ID##message#MESSAGE_ID#.

    Variables #FORUM_ID#, #TOPIC_ID# and #MESSAGE_ID# are automatically replaced with the real forum ID, topic ID and message ID when the template is used.

    * - Required fields.

    "Settings" tab
    Field | Description
    Use HTML | Allows or disallows the use of HTML code in the message text. It is not recommended to use an arbitrary HTML code in the forum needlessly, as this greatly affects the forum security.
    Convert new line into <br>
    (HTML)     		Replaces carriage returns (new lines) with a <br> tag. In the HTML mode the message text is displayed “as is”, i.e. without any transformations.
    Allow links | Allows hyperlinks in messages.
    Allow B, U and I tags | Allows bold, italic and underline text highlighting.
    Allow images | Allows images in the message text. Images are to be located on the third-party sites. Only references to these images are used in the message text.
    Allow lists | Allows creation of lists.
    Allow quotations | Allows quoting messages of other users.
    Allow code | Allows code tag in messages.
    Allow fonts | Allows to modify the font and colour of the text.
    Allow smileys | Allows smileys in messages.
    Allow upload Allows uploading and inserting the specified files in messages. Possible values are:
    • no - upload is forbidden;
    • images - upload only images (gif, jpg, png, jpe, jpeg);
    • files with the specified extensions - upload files with the extensions from the Allowed extensions of loaded files field;
    • any files - upload any files. Do not permit uploading the scripts and executable files needlessly as this can let malicious persons completely destroy your site.
    Allowed extensions of loaded files | Files extensions permitted to be uploaded to the site (for more details, see the description of the previous field).
    Premoderated | Turns on the pre-moderated mode: the user messages will be published on the site only after being
    Ask unregistered user for E-Mail | Defines whether an unregistered user will be asked for an e-mail address while trying to post a message or not.
    Use CAPTCHA | Specifies to use special mechanism to prevent unauthorised automated posts.
    Sort by | Default sorting of the topics within a forum in the site public section. Choose the sorting type and direction. For example, if you choose descending sorting by the last message date, the new posts will be displayed higher than the old ones.
    Sort direction | Sorting direction for the specified sort type.
    New message registration in the Statistics module
    This section is used to specify identifiers that are used to register creating a new forum message in the Statistics module.
    event1 | The event type identifier event1.
    event2 | The event type identifier event2.
    event3 | The additional event type identifier event3.
    "Access" tab

    This field group is used to define forum access rights for each registered user group. The rights have the following default values.

    Field Description
    [A user group]

    The forum access level assigned to this user group:

    • No access - prohibits the access to the forum;
    • Read - allows reading the forum messages without the right to create new topics;
    • Reply - allows to take part in discussions without the right to create new topics;
    • New topic - allows both to discuss the existing topics and to create new ones;
    • Moderate - allows to moderate the forum, i.e. make various actions, which will not cause the real data loss. For example, moderators can hide or show a message, but cannot edit or delete it. Members of this group receive all forum message copies via the e-mail.
    • Modify - allows managing messages of other forum users;
    • Full access - allows full access to the forum, including access to the forum settings and to the access right settings;

    Note!
    Higher rights inherit lower rights (i.e. if a group has the right to moderate the forum, it surely has the right to read and reply messages, create new topics, but has no right to edit messages). If a user belongs to several groups, highest of their rights is assigned when defining their access right.

    Control buttons

    Button | Description
Save | Saves the forum parameters. Opens the page with the list of forums.
Apply | Saves the forum parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Forum moderating - Bitrix Site Manager - Content Management & Portal Solutions

Forum moderating

Forums can be moderated from within the site public section. When a forum message is read by a user who has the right to moderate messages of this forum, the Show/Hide button is displayed near the message. Using this button, the moderator can hide the message from other users of the forum, or make the message available for reading.

If the forum is pre-moderated, all newly created messages of this forum are hidden. To make these messages available to the forum users, the forum moderator (or the site administrator) has to unhide these messages.


Forum groups - Bitrix Site Manager - Content Management & Portal Solutions

Forum groups

In this section

  • Context bar
  • List of forum groups
    •

    The Forum groups page (Services -> Forums -> Groups) contains the list of existing groups and allows to create and modify new ones.

    Groups are used to classify forums in the site public section. For example, you can group all the forums regarding one specific product or topic: the Licensing forum, the Usage forum etc.

    Each forum can be bound to one of the forum groups or not.

    Context bar

    Button | Description
New forum group | Opens a form in which you can create a new forum group.
Excel | Exports data from the table to the MS Excel format.

    List of forum groups

    Column | Description
    Checkbox column Selects the groups to which the desired actions are to be applied.
    Action menu
             Actions on a forum group:
    • Modify group settings - edits forum groups;
    • Delete group - deletes forum groups. Deleting a group will not incur deleting the forums which belong to this group.
    ID | The unique ID of the forum group.
    Sort | The forum group sort weight. Defines the group position in lists. The lower is the value, the higher the group will be positioned in lists.
    Name | The name of the group displayed in the site public section.


Creating and editing a group - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a group

In this section

  • Context bar
  • Editing form
  • Control buttons
    •

    This form is used to create and edit forum groups which are used to classify forums in the site public section.

    Context bar

    Button | Description
Forum groups | Opens a page containing the list of forum groups.
New group | Creates a new forum group in this form. The button is displayed when editing the existing group only.
Delete group | Deletes the current forum group.

    Editing form

    Field | Description
ID | The ID of the forum group in the system. The field is displayed when editing the existing forum group only.
Sorting | The forum group sort weight. Defines the group position in lists. The lower is the value, the higher the group will be positioned in lists.
[Site]
*Name | The name of the group displayed in the public section. The name is to be specified for each language used in the system.
Description | Arbitrary description of the group for each language.

    * - Required fields.

    Control buttons

    Button | Description
Save | Saves the forum group parameters. Opens the page with the list of forums.
Apply | Saves the forum group parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Statuses - Bitrix Site Manager - Content Management & Portal Solutions

Ranks

In this section

  • Context bar
  • List of ranks
    •

    The Ranks page (Services -> Forums -> Ranks) contains information about the existing ranks. Here, you can create new and edit the existing ranks.

    User ranks depend on the number of points a user has. Points can be given for posting messages as well as by other users' voting.

    To enable this functionality, the corresponding option must be selected in the forum module general settings.

    Context bar

    Button | Description
New rank | Opens a form in which you can create a new rank.
Excel | Exports data from the table to the MS Excel format.

    List of ranks

    Column | Description
    Checkbox column | Selects the ranks to which the desired actions are to be applied.
    Action menu
             Actions on a rank:
    • Modify score parameters - edits a rank;
    • Delete - deletes a rank.
    ID | The ID of the rank in the system.
    Minimum number of points | Number of points required to obtain this rank.
    Name | The name of the rank as it is displayed on the forum.
    Votes | Number of votes required to obtain this status.


Create and edit a status - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing ranks

In this section

  • Context bar
  • Editing form
  • Control buttons
    •

    This form can be used both for creating and editing forum user ranks.

    Context bar

    Button | Description
Ranks | Opens a page containing the list of ranks.
New rank | Creates a new rank in this form. The button is displayed when editing the existing rank only.
Delete rank | Deletes the current rank.

    Editing form

    Field | Description
ID | The rank ID.
*Minimum number of points to give the score | Number of points required to obtain this status.
Mnemonic code | The mnemonic rank code. Can be used by developers only.
Number of votes | Number of votes required for obtaining this status.
[Site]
*Name | The name of the rank as it is displayed on the forum. Specified for each language individually.

    * - Required fields.

    Control buttons

    Button | Description
Save | Saves the rank parameters. Opens the page with the list of ranks.
Apply | Saves the rank parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Points for posting messages - Bitrix Site Manager - Content Management & Portal Solutions

Points for posted messages

In this section

  • Context bar
  • List of points for messages
    •

    The Points for posted messages form (Services -> Forums -> Points for message) controls the number of points assigned to a forum user for each posted message. This form helps to setup the points collection cumulative system; i.e. the number of points for each new message will increase according to the total number of the posted messages.

    Context bar

    Button | Description
New record | Adds a new record describing the number of points for message.
Excel | Exports data from the table to the MS Excel format.

    List of points for messages

    Column | Description
    Checkbox column | Selects the records to which the desired actions are to be applied.
    Action menu
             Actions on a points-for-message record:
    • Modify record - edits a record;
    • Delete - deletes a record.
    ID | The ID of the record in the system.
    Min number of messages Number of messages which, when reached, indicates that a number of points specified in Points for message will be added for each subsequent message.

    For example, the field value is 10. It means that, when a tenth message is posted, the user will be assigned a new (specified in Points for message) number of points for each subsequent message.
    Points for message | Number of points to be assigned for a message when the number of messages specified in Min number of messages is reached.


Edit a message threshold - Bitrix Site Manager - Content Management & Portal Solutions

Editing the points for message settings

In this section

  • Context bar
  • Editing form
  • Control buttons
    •

    This form can be used both for creating new records containing the number of points for message and for editing the existing ones.

    Context bar

    Button | Description
Records | Opens a page containing the list or records containing the number of points assigned for a message.
New record | Creates a new record in this form. The button is displayed when editing the existing record only.
Delete record | Deletes the current record.

    Editing form

    Field | Description
ID | The ID of the record in the system.
*Minimum number of messages | Number of messages which, when reached, indicates that a number of points specified in Points for message will be added for each subsequent message.
Points for message | Number of points assigned for a message when the number of messages specified in Min number of messages is reached.

    * - Required fields.

    Control buttons

    Button | Description
Save | Saves the record parameters. Opens the page with the list of records.
Apply | Saves the record parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.

    Note!
    When the record parameters are modified, the number of user's points will be re-counted after a user posts a subsequent forum message or the next time this user is voted for.


Forum smileys - Bitrix Site Manager - Content Management & Portal Solutions

Forum smileys

In this forum

  • Context bar
  • List of smileys
    •

    The Forum smileys form (Services -> Forums -> Smileys) serves to extend the available set of smileys and icons. If you add a smiley or a icon of the non-standard size, check the appearance of the forum public section. Probably, you will have to make some changes.

    Context bar

    Button | Description
New smiley | Adds a new smiley.
Excel | Exports data from the table to the MS Excel format.

    List of smileys

    Column | Description
    Checkbox column | Selects the records to which the desired actions are to be applied.
    Action menu
             Actions on a record:
    • Modify smiley settings - edits a smiley;
    • Delete smiley - deletes a smiley.
    ID | The unique ID of the smiley in the system.
    Sorting | The smiley sort weight. Defines the smiley position in lists.
    Type | The image type: smiley (emotion expression) or icon (opinion token).
    Name | The name of the image displayed in the public section of the forum.
    Typing | The image symbolic equivalent.
    Image | The image of a smiley or icon.


Frequently asked questions (FAQ) - Bitrix Site Manager - Content Management & Portal Solutions

Frequently asked questions (FAQ)

Questions

  • How to create a topic in the forum?
  • Can I use HTML?
  • How to edit a message text if HTML is not allowed
  • Can I insert pictures?
  • What are smileys?
  • Why do I need to register?
  • How do I edit my preferences?
  • I want to receive new messages by e-mail!
    •

    How to create a topic in the forum?

    Click an appropriate button or link in the list of forum topics or in the window of a specific topic. Possibly you will have to register before posting a message.

    Can I use HTML?

    It depends on whether it is allowed by the administrator or not. If HTML is allowed, it is more likely that only several tags will be available. This is for the sake of security to prohibit the use of tags which can cause damage to the proper operation of the site.

    How to edit a message text if HTML is not allowed

    The following pseudo-tags may be allowed by the administrator:
    Tag | Description | Synonyms | Comment
    <a href="link"> Link. [URL]link[/URL]
    [URL=link]
    <b>, <u>, <i> | Bold, underline or italic text. | [b], [u], [i] | Both the start and end tags (</b>, </u>, </i>) are required.
    <img src="address"> | Image. | [img]address[/img] | Embeds an image into the text message. Address is the full path to the image located on any public site.
    <ul>, <li> | Bullet list. | [ul], [li]
    <quote> | Special tag to set apart a quotation in text. | [quote] | Both the start and end tags (</quote>) are required.
    <code> | Special tag to specify a code sample. | [code] | Both the start and end tags(</code>) are required.
    <font color=>,
    <font size=>         		Font color and size. [color=], [size=] Both the start and end tags (</font>) are required.

    Can I insert images?

    You can insert images in messages if it is allowed by the administrator. You must specify a link to the picture on the public server, for example: [img]http://www.bitrix.com/images/logo_bitrix.gif[/img] or <img src="http://www.bitrix.com/images/logo_bitrix.gif">.

    What are smileys?

    Smileys, or emoticons, are small pictures that can be used as an expression of various emotions. For example: :) means joy, happiness, :( means sadness, grief. The full list of smileys can be accessed in the message creation form. But do not use too many emotions – they can make the message unreadable, and moderator will have to edit it, or even delete it from the forum.

    Why do I need to register?

    You may not need to do it. It depends on the forum settings: whether you need to register to post messages on this forum or not.

    How do I edit my preferences?

    If you are registered, all your preferences are stored in the database. To edit them, go to the Profile section (the link to this section is located at the top of the forum). You can edit all your preferences there. The access to the Profile section is granted only after registration.

    The page for editing the user profile consists of three sections: changing the registration information, changing the personal data and changing forum profile.

    • In the registration information editing section, you can change your first and last names, login and user password.
    • In the personal data editing section, you can specify your job title, ICQ number, date of birth, photo, address and other personal information.
    • In the forum profile editing section, you can change your appearance on the forum:
      • Show name. When posting a message, the author’s first and last names (if they are not empty) are used. Otherwise the author's login is used. If unchecked, this checkbox forbids the display of the first and last names no matter whether these fields are filled or not;
      • Description - an author description which is displayed under the author’s name. It is forbidden to use admin, moderator, support words as descriptions. Violators will be removed from the forum without warning;
      • Signature - a text to be automatically added below each message of the particular user. You can use all tags allowed on this forum in the signature;
      • Avatar - an image, which is displayed below the author’s name. The image size and resolution must not exceed 10 kb and 90x90 pixels.

    I want to receive new messages by e-mail!

    You can subscribe to receive new messages from the whole forum or a specific topic. Subscription requires that you are registered on the server. If you want to subscribe to receive messages from the whole forum, use the Subscribe link in the forum menu. If you want to subscribe to receive new messages of a specific topic, use the Subscribe link in the upper right corner of the topic.

    There is another subscription type – subscribe only to new topics (i.e. to the first message of each new topic). All the three subscription types are accessible in the forum menu. You can also access your subscription settings from the forum menu.

    To manage your subscription, click the Edit subscription link in your profile.


Create a new forum - Bitrix Site Manager - Content Management & Portal Solutions

Create a new forum

  1. Open the forum management page (Services -> Forums -> List of forums).
  2. Click New forum.
  3. Select the Active checkbox.
  4. Select the sites on which this forum should be accessible, and specify the path templates to the forum messages on each of these sites (for generation of links in messages from the forum and for indexation in the search module).
  5. Choose the sorting order. The higher the sorting order value, the lower the forum will be displayed in the forums list.
  6. Enter the forum title in the Forum title field.
  7. Prepare a brief description of the forum to be displayed in the forums list in the site public section.

  8. If needed, select the following checkboxes:
    • Allow HTML – HTML code usage in the message text;
    • Allow references (<a href=...>) – hyperlinks usage in the message text;
    • Allow B, U, I (<b> <u> <i>) tags – select the text style: bold, underline, italic;
    • Allow images (<img src=...>) – images usage in the message text;
    • Allow lists (<ul><li>) – lists creation;
    • Allow quoting (<quote>) – allows to quote other user’s messages;
    • Allow codes (<code>) – code usage in the text message;
    • Allow fonts (<font color=...>) – allows font modifying in the message text (font color and face);
    • Allow smileys - smileys usage in the message text.
  9. Selecting the Premoderating checkbox will turn on the premoderation mode: user messages will be posted on the site only after they have been checked by the moderator (site administrator or a user with the appropriate rights).
  10. Choose the sorting type and direction. If descending sorting by the last message date is chosen, the new posts will be displayed higher than the old ones.
  11. Define the forum access rights for various user groups.
  12. Click the Save button.

Users with moderator rights can view the IP and ID of the forum message author (user ID is available for viewing only if the statistics module is installed and the user has the right to use it). The information about the author is located to the left of the forum text message. Using this information, you can obtain detailed information about the user and track his activity on the site by means of the statistics module.


Mail module - Bitrix Site Manager - Content Management & Portal Solutions

Mail module

The process of site management envisions communication via e-mail with a number of people related to the operation of your web-portal. Among these respondents are the following groups:

  • visitors, customers;
  • contractors, suppliers;
  • employees responsible for the site contents;
  • other groups.

Of course, you can continue using traditional software for reading e-mail messages (an E-Mail client program) such as The Bat, Outlook, Eudora or any other. However, the system Bitrix Site Manager proposes another efficient approach to manage you E-Mail messages. Note that using this solution doesn't mean you'll have to give up your usual tools for reading e-mail messages. By installing the mail module, you gain the following advantages of e- mail management:

  • centralized storage of e-mail messages related to the site functioning;
  • unlimited number of mail boxes that you can create;
  • creating and applying rules for incoming messages in the automatic and manual modes;
  • self-training spam filtering system;
  • delivering e-mail messages without deleting them from the mail server and many other features.


E-mail messages - Bitrix Site Manager - Content Management & Portal Solutions

Messages

In this topic

Filter
List of e-mail messages
How to check a mail box for new messages
How to delete messages or apply rules (actions) to messages

The Mail messages form displays messages coming from the existing (created by you) mail boxes. Using this form you can:

  • view information about the received messages in the table form;
  • view incoming messages;
  • apply rules and actions to the messages (e.g. delete or print messages, mark messages as SPAM and so on).

The Mail messages form contains two main areas: filter and mail messages list, and also additional areas such as Receive mail and Process mail.

Filter

The filter is used to define the selection parameters of the messages to be displayed in the list. To do so, the filter supports the following message search parameters:

  • mail box;
  • sender and recipient;
  • other criteria.

The table below describe the filter fields.

Field | Description
Everywhere | Words or phrases that the sought messages may contain in any field.
ID | The ID of the sought message.
Mail box | The name of a mail box from which the sought messages have been received.
Marked as SPAM | Selects all messages, those marked as SPAM or not marked as SPAM.
Read messages | Selects all messages, read messages or non-read messages.
From | Sender of the sought messages.
To | Recipient of the sought messages.
Subject | Subject of the sought messages.
Text | Words or phrases that the sought messages may contain in their body.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Receive mail | Allows to check all or selected mailboxes for new messages.
Excel | Exports data from the table to the MS Excel format.

List of e-mail messages

Field | Description
Checkbox column | Used to select messages to which the desired rules or actions are to be applied. Available rules and actions can be found in the action bar below the table.
Subject | Subject of the message.
From | Sender of the message. This field displays the sender name as defined by the message author.
Date | Date when the message has been received.
Mail box | The name of the mail box from which the message was received.
Size | Size of the message in bytes.
SPAM coeff. | Ratio indicating the probability of the message being spam.
Attach. | Number of attachments in this message. Note Messages in the HTML format always have at least one attachment - the message itself in the HTML format.
Selected | Number of messages selected from the database.
Checked | Number of messages marked.

Note
The table can be sorted by any field by clicking on a header of the desired column.

How to check a mail box for new messages

To check whether there are new mail messages in the existing mail boxes, select the required mail box (or all mail boxes) in the context bar, and click OK.

Processing status and the number of messages received will be displayed for each mail box in the Check for new mail form.

In case any errors occurred during processing, the mailbox context toolbar will show the Mailbox settings button. Click it to edit the mail box properties (e.g. correct the user password).

How to delete messages or apply rules (actions) to messages

To apply any action or rule to a message or a group of messages, do the following.

  1. Select the required messages by marking them in the Checkbox column. To select all messages, select the checkbox in the table header.
  2. In the action bar, specify whether to apply the rule to all messages or only to selected ones.
  3. Select the required action, (for example: Mark as SPAM).
  4. Click the Apply button.


Viewing mail message - Bitrix Site Manager - Content Management & Portal Solutions

Viewing mail messages

The Message view form displays the text and properties of the selected message. The form fields are described below.

Mail message view form ("Message" tab)

Field | Description
Date | The date when the message was received.
From | The sender of the message.
To | The recipient of the message.
Subject | The subject of the message.
Attachments | Files attached to the message (attachments).
Message status Mnemonic status of the message and probability that this message is SPAM.

- message has no status;
- message was read and not SPAM;
- message was read and is SPAM;
- message wasn't read, no status;
- message wasn't read, not a SPAM;
- message wasn't read, SPAM.
Train | If you want to instruct the system how to handle messages similar to this one, select the desired action and click Apply.
Apply manual rules | Allows to select rules marked as Manual, and apply them upon saving.
Delete messages after processing | Checking this box will delete the message upon saving.

Mail processing log

This box contains rules and actions applied to the message. The field is intended for information purposes only.


Mail processing log file - Bitrix Site Manager - Content Management & Portal Solutions

Mail processing log

In this topic

Filter
Log file

The Mail processing log file form displays all events related to the mail module functioning and message receiving:

  • system requests to a mail server;
  • mail server replies;
  • applying rules and actions.

Filter

A filter is used to define the selection parameters of the events to be displayed in the log file. The filter fields are described in the table below.

Field | Description
Message | Selects messages with the certain text.
Message: show column | Displays the column containing the message summary.
Mail box | The name of a mail box for which the events should be displayed.
Rule | Selects all messages or only the ones to which a certain rule was applied.
Rule: show column | Displays the column containing the rule name.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Excel | Exports data from the table to the MS Excel format.

Log file

Field | Description
Time | Time when an event occurred.
Text | The event description. Server requests are highlighted with green. Server replies are highlighted with blue. Errors description is rendered in red.
Mail box | The mailbox in which the event occurred.
Rule (depends on filter settings) | The rule applied to the message.
Letter (depends on filter settings) | The summary of the message.


Mail processing rules - Bitrix Site Manager - Content Management & Portal Solutions

Mail rules

In this topic

Filter
List of rules
How to add a rule
How to edit rule parameters

The Mail rules form displays rules that can be applied to messages.

Filter

A filter is used to set the parameters for selecting the rules to be displayed in the list. The table below describes the filter fields.

Field | Description
Name | Allows to select rules with a certain name.
ID | The ID of the sought rule.
Mail box | The name of the mail box whose rules are to be displayed.
Act. | Tells to display all rules, only active or non-active ones.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
New rule | Click this button to add a new mail processing rule. In the menu, select the type of rule to add.
Excel | Exports data from the table to the MS Excel format.

List of rules

Field | Description
Checkbox column | Used to select mail rules to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
 Clicking the action button of any rule opens a menu allowing to:
  • Modify - edit the rule;
  • Log - view the rule history log;
  • Delete - delete the rule.
ID | The ID of the rule in the database.
Modified | The date the rule was last modified.
Name | The name of the rule and the list of actions performed by the rule.
Act. | The rule activity indicator.
Sorting | The rule sorting value; used for displaying the rule in lists.
Box | Name of the mailbox to which this rule can be applied.

How to add a rule

To add a new rule, click New rule on the context bar choose the predefined template for the new rule:

  • manual settings (or without selection) - all rule parameters are available for editing;
  • adding message to techsupport - a special template used to create a rule for filtering messages destined to the technical support service.

Click the Add button. In the New rule form, set the rule parameters and save it.

How to edit rule parameters

To modify the rule parameters, double-click a row of the desired rule.


New rule (rule editor) - Bitrix Site Manager - Content Management & Portal Solutions

New rule (rule editor)

This form is used to create or edit rules for new mail messages. To create a new rule, you need to fill in the form fields and click the Save button.

Rule parameters

"Parameters" tab

Field | Description
ID The ID of the rule under which the rule was saved.

The code is displayed while editing the existing rule.
Modified The date and time when the rule was last changed.

It is displayed while editing the existing rule.
Mail box | The mailbox to which this rule is to be applied. You can create a new mailbox by clicking the Create link.
Act. If checked, the rule is active and can be applied to messages. If not checked, the rule does not apply.

See also the Apply to events field.
Name | The name of the rule.
Description | The description of the rule. You can enter any description here.
Sorting | The rule sorting value; used when displaying rules in lists.
Apply to events Types of events with which this rule should be applied:
  • When receiving a message - with this checkbox selected, the rule will be applied to every message when receiving messages from the mailbox for which the rule is created. If the checkbox is not selected, the rule will not be applied to the incoming messages;
  • When processing rule manually - if the checkbox is selected, the rule can be applied only manually.

"Conditions" tab

Field | Description
Groups of condition fields | These groups of fields are used to create conditions which define whether the rule can be applied to messages or not; in other words, these fields define the preliminary filtering conditions for messages before the rule is applied. For more information about groups of fields, see the notes below.
Spam probability | Indicates that the rule will be applied only to messages whose SPAM index satisfies this condition. For example, if this condition is set to "more than 90%", the rule will be applied only to the messages with the spam index is more than 90%.
Message size | Indicates that the rule is to be applied only to the messages whose size satisfies this condition.
PHP condition | Optional PHP script. The script is executed by the system and should return true or false. For more information about groups of fields, see the notes below.
Settings (adding a message to technical support) This group of settings is displayed only for rules created using the "adding message to techsupport" template
Identify registered user by e-mail | If this condition is set to yes..., upon receiving a new message, the rule will try to find a registered user with the specified address in the database and assign the message to this user. Otherwise, messages in the technical support module will be created as anonymous.
Add a new message to existing ticket | This condition defines addresses messages from which can be added to an open ticket of the technical support module. If you select the as hidden... checkbox, only members of the technical support service will have access to the message.
Subject templates... | Regular expressions applied to incoming messages. This field is intended for developers; it is not recommended to change this value.
Link a new trouble ticket to the site | Specifies the site to which the newly created ticket is to be added.
Add a new ticket to a category | Specifies the ticket category to which the new ticket will be linked.
New ticket emergency | Allows to set the default emergency of the new ticket.

"Actions" tab

Field | Description
Set read status | Marks all messages processed with this rule as read.
Mark as spam | Marks all messages processed with this rule as spam.
PHP script action | Optional PHP script which is executed when the rule is applied to the message.
Delete message | Deletes the messages to which the rule is applied.
Do not process with other rules | After applying this rule to a certain message, other rules will not be applied to it, even if this message meets the appropriate rule conditions.

Notes

Groups of condition fields

The first dropdown list of the group contains text message properties used as an information source for the filter (operand).

The second dropdown list contains comparative operators that define the type of the compare operation applied to the text of the property selected in the first list at filtering. You can select the Regular expression item as a functional operator. The syntax of the regular expressions corresponds to the PCRE specification. The syntax description can be found here: http://php.net/manual/en/reference.pcre.pattern.syntax.php.

The input text field is intended for a sample text which is compared to the property text of the first list.

Example

To apply a rule to all incoming messages with the word Order in the Subject field, set the following field values:

  • Operand - Subject;
  • Operator - Contain;
  • Sample - Order.

PHP script condition

In most cases the features available are sufficient for setting the message selection conditions. However, if standard rules do not allow to implement the required message selection conditions, you can create the user-defined selection conditions. The script for these conditions should be written in the PHP programming language. When running the condition script, the validity of the message fields array $arMessageFields is guaranteed.

The conditional PHP-script should return true if the condition is implemented and can be applied to a message; otherwise, false is returned..

Example
if ($arMessageFields["FIELD_PRIORITY"] > 3 ||
    strpos($arMessageFields["FIELD_FROM"], "@bitrix") > 0)
   return true;
return false;


Mail boxes - Bitrix Site Manager - Content Management & Portal Solutions

Mail boxes

In this topic

Filter
List of mail boxes
How to add a mail box
How to customize the mail box parameters

The Mail boxes form displays your e-mail accounts used to send and receive e-mail messages.

Filter

A filter is used to define the selection parameters of the E-Mail accounts to be displayed in the list. The filter fields are described in the table below.

Field | Description
Name | Allows to select accounts whose names contain text entered in this field.
ID | The ID of the sought mail box.
Act. | Displays all mail boxes, only active or non-active ones.
Site | The site on which the sought box is active.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Add | Opens a form in which you can create a new mailbox.
Excel | Exports data from the table to the MS Excel format.

List of mail boxes

Field | Description
Checkbox column | Used to select mailboxes to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
 Clicking the action button of any mailbox opens a menu allowing to:
  • Rules - display rules applicable to this mailbos;
  • Add rule - add a new rule that can be applied to this mailbox;
  • Log - view event log of this mailbox;
  • Messages - view all messages in this mailbox;
  • Edit - edit mail account parameters;
  • Delete - delete the mailbox.
ID | The ID of a mailbox in the database.
Modified | The date the mailbox parameters was last modified.
Name | The name of the mailbox and link to editing its parameters.
Act. | The mailbox activity checkbox.
Site | The site on which this mailbox is active.

How to add a mail box

To create a new mail box, click the Add button. Set the parameters of a new e-mail account in the mailbox properties form.

How to edit the mail box parameters

To modify the mailbox parameters, double- click a row of the desired mailbox.


New mailbox (mailbox editor) - Bitrix Site Manager - Content Management & Portal Solutions

New mailbox (mailbox editor)

The Mailbox properties form is designed to create a new e-mail account or edit the existing one from which messages will be received. To create a new mail box, fill in the appropriate form fields and click the Save button.

Context bar

Button | Description
Mailbox list | Opens the
Add a new mailbox |
Delete mailbox |

Mailbox editing form ("Mailbox" tab)

Field | Description
Site | The site on which this mailbox is active.
Active | The mailbox active state flag. If the mailbox is inactive, it will not be checked for new messages.
Name | Any name of an e-mail account.
Description | The mailbox description.
Mail server (POP3) / port | The address of a mail server to be used for receiving messages, and the port used for connection (usually 110).
Logon name | The name of an e-mail account on the mail server.
Password | The password used to log in to the mail server.
Use safe (MD5) authorization | Specifies the use of a secure authorisation protocol (MD5). Not all mail servers support this feature.
Check interval | Time interval, in minutes, between automatic attempts to check for new messages on the server.
Maximum number of messages received at a single connection | This field sets a limit for the number of messages to be received in one connection session. If there are more messages on the server than is specified in this parameter, other messages will be received during the next session.
Delete received messages from server | If this option is enabled, messages will be deleted from a mail server after they are received and saved in the system. This is the way that the most e-mail softwares function. If you want to receive messages using your e-mail client as well (e.g. for back-up purposes), do not enable this option.


e-Store - Bitrix Site Manager - Content Management & Portal Solutions

e-Store

Introduction

Modern business stepped over beyond offices and stores a long time ago. We can even assert that it gone out of the window, and it will not be overestimation, for million of users, who are your potential customers, spend their time on searching products and services in the Internet by studying proposals in browser windows. Expand your business, offer your products and services - you can do it is very easily with Bitrix Site Manager!

Bitrix Site Manager will help you create an e-Store to sell products and services right on the site. The e-Store includes the following sections:

  • shopping cart to which you can add any products and services;
  • ordering procedure;
  • customer personal section where the customer can review the ordered products and services and manage the profile;
  • administrative section for store parameters settings and for customers order management.

You can set the e-Store parameters in the e-Store menu section and also on the modules settings pages (Settings).

e-Store features

Localizability
All e-Store elements depend on the site. For example, the list of delivery services displayed to the customer can be different on various sites.
Module independence
The e-Store does not depend on other modules and can accept products from any module or static pages into the cart. The commercial catalogue module has the set of functions for convenient operation with the e-Store.
Fully featured cart of products and services
Each item placed in the cart can be described by an arbitrary number of parameters (properties). If an item adding callback function is defined, availability of an item is checked while performing various actions with the cart. The callback function is set automatically if an item is added from the commercial catalogue.
Support of many currencies
The system allows to flexibly manage the price currencies. The currency list is defined by the administrator. You can set exchange rates for each currency (with possible loading of the exchange rates from the Central Bank of Russia site) and the display format for the site.

For each site a single currency is assigned for price conversion. Thus, regardless of which currency is used for product prices, delivery costs, discounts and so on, this currency will be converted into the main site currency when displaying a cart and completing the order. Thus, for the UK English language you can define the currency GBP - pounds. In the UK English interface, all the prices set in the foreign currency (for example, USD), will be converted to pounds using the established exchange rate.

You can customize the currency settings for the site and, in particular, for an e-Store in the currency module.
Discounts system
Discount management system allows to create several discount levels depending on the total order cost. Discounts can be defined both in percentage and fixed values. The discount is calculated according to the total order cost without the delivery cost.
Delivery
Delivery system allows to set parameters for defining the delivery cost. Calculation of delivery cost respects preferences of different locations
which are specified by the e-Store administrator. For example, the delivery zones can be divided by cities, regions, countries, etc. The number of zones is not limited. Moreover, the delivery cost can be also defined according to the total order cost and weight.
Automatic calculation of the order cost
The total order cost consists of the following components: the total item cost in the order (sum of costs compositions at the moment or making an order to the quantity of the ordered items), delivery cost (money for post or express delivery). The discount (if any) is taken away from the order cost. If the taxes are defined in the system, they are also taken into account at the order cost calculation.
Payment systems
The payment system allows to build an interface for initializing the order payment procedure by electronic means or for printing the required documents for payment by using other (non electronic) means. The number of payment systems templates is not limited. The range of pre-set payment system templates is supplied with the e-Store installation program and included support for the Assist (plastic cards, Yandex-money, WebMoney) payment system, printing Savings Bank of Russia receipts, etc. All the payment system templates require customization before being used.
Order properties
At ordering, the system prompts customer to provide a certain set of parameters (order properties) required for setting, registering ot delivering the ordered items or services. The set of properties can be fully defined by the site administrator and depends on the customer type selected in the first step of the order procedure.

For example, an order can have the following properties for the Personal customer type:
  • first and last names;
  • delivery address;
  • E-Mail;
  • other properties.
At the same time, an order can have different properties for the Legal person customer type:
  • organization name;
  • legal address;
  • tax payer ID;
  • E-Mail;
  • other properties.
Some properties can be stored as the customer profile and used for making the repeated orders.
Customer personal section
In this section the customer can view all his orders, call off the new order, copy orders for making recurring orders, print the required documents or repeat a payment procedure by electronic means, review the order statuses, review and change the saved customer profiles.
Administrative section for order processing
Orders are processed by the checkboxes Paid, Cancelled, Delivery accepted and statuses (Accepted, In process, Shipped, Delivered, etc). The list of statuses list can be arbitrarily set for a site.

Checkboxes and statuses can be set independently from each other. For example, it's possible that the order is not paid yet but its delivery is already accepted, or an order can be paid but its delivery is not yet accepted. The order status is intended for informing the customer and the e-Store employee about the current state of the order.

It is possible to automatically inquire the payment system status for orders paid by electronic means. If the payment system says that the order is paid and the payment sum is equal to the order cost, the Paid checkbox of the order will be automatically replaced with Yes.
Mail messages
Creating new orders, changing the existing ones and cancelling orders are accompanied by sending mail messages to the customer and to e-Store sale department the E-Mail address of which is defined in the e-Store settings.


Module settings (e-Store)

In this topic

  • Settings form
  • "Settings" tab
  • "Credit cards" tab
  • "Permissions for orders" tab
  • "Access" tab
    •
  • Controls
    •

    After you have installed the e-Store module, you have to configure it before you start working with it. To do so, switch to the global settings page (menu System settings -> Settings, select e-Store in the drop-down list).

    Settings form

    "Settings" tab

    This form (tab) provides interface for customizing the main parameters of the module.

    Parameter | Meaning
Sales department e-mail | The e-mail to which the messages from the module will be sent.
Default registration e-mail | Only the registered users are allowed to make purchases in the e-Store. If a customer has not been previously registered in the system, they are prompted to register at the check-out time. This field contains the e-mail address that will be used as the customer's e-mail address for registering such users by default. If an order has an e-mail property filled in, its value will be used instead of the default e-mail address (see Order properties).
Keep basket information (days) | The period of time (days), during which the customer's shopping cart will be preserved.
Path to custom payment systems processing files | If you use custom payment system(s), you have to create the payment system handler file and specify the path to the file in this field.
File containing custom order viewing form | You can use custom forms for viewing the information about orders. This field is used to set the pathname to such a file. A custom order viewing form can be created similarly to the information block element editing form.
Fix Catalog module (catalog) as a catalog of products | Check this option if you plan to sell products from the context of the e-Store module only. This will restrict products that can be added to a user's shopping cart to those containing in the e-Store module.
Default currency | When creating an order, product prices and the total amount will be displayed in the default currency. If the price of any product was set in some other currency, the price will be recalculated using the rate specified in the Currency module.

    "Credit cards" tab

    This tab is used to control the credit card number are encrypted before transmitting via the Internet.

    Field | Description
    Path to key file | Full path to the file containing the encryption password. For example: d:/projects/siteman/bitrix/modules/sale/install/data.php.
    Encryption algorithm The required encryption algorithm:
    • RC4;
    • AES (Rijndael) (requires the Mcrypt PHP module);
    • 3DES (Triple - DES) (requires the Mcrypt PHP module).

    Important!
    These algorithms are mutually incompatible. You must not change the algorithm if there are any encrypted information in the system.

    "Permissions for orders" tab

    This tab controls users' access to customers' orders.

    Additional site parameters
    Site | The name of the site for which the settings are displayed.
    Currency | The currency used in the public section of the given site. When ordering, all prices and the resulting total order sum will be displayed in this currency. If the price of a specific product is stored in a different currency, the price will be recalculated using the rate of exchange provided by the Currency module.
    Groups allowed to access orders of the site | Groups of users who can access orders of the given site.
    Permissions to change order state
    State The order state:
    • Paid - an order has been fully paid;
    • Canceled - an order has been canceled;
    • For delivery - order items can be delivered.
    User groups | User groups who are granted permission to move orders to the respective state.

    "Access" tab

    This tab allows to configure the access permissions of user groups for the module.

    Field | Description
    Default | Changes the default permission. This affects all user groups that have the default access permission.
    [User group] Changes the permission of a specific user group. The following access permissions apply to the e-Store module:
    • deny - any access is denied;
    • read-only - users can only view files and settings of the module;
    • manage orders - users can process orders placed by customers;
    • full access - full read and write access to module files and settings, including order processing and managing access permissions of other user groups.

    Controls

    Button | Description
Save | Saves the performed changes.
Reset | Cancels current changes and restores parameters to their original values.
Restore defaults | Resets module settings to their default values.


Customizing your e-Store

The e-Store settings page (e-Store -> e-Store settings) presents quick shortcuts to customizing parameters, settings and operations of your e-shop. This page contains links to forms in which you can configure parameters of the e-Store for its proper operation.

Delivery
The Delivery services form is used to create, delete and configure delivery services.
Payment systems
The Payment systems form is used to add payment systems and edit their parameters.
Payer types
The Payer types form is used to add, edit or delete different types of payers who can order products and services on the site. Each payer type has own set of properties (fields) which a payer ought to fill in when placing an order. Additionally, payer type has a private set of payment system processors which can be used to pay orders.
Order properties
The Order properties form is used to define order properties (fields) that a customer has to fill in when placing orders. Properties depend on the payer type chosen by a customer.
Groups of properties
The Groups of properties form is used to manage groups of order properties. Grouping is used to define the layout of the order form, for better usability. Property groups depend on the payer type chosen by a customer.
Locations
The Locations form helps manage locations which will further be used by customers to select the location to deliver the ordered products to. The selected location will be used as a reference point to display available delivery services and calculate delivery cost. Location is a part of an actual shipment address.
Groups of locations
The Groups of locations form is used to classify locations. It facilitates managing delivery services.
Statuses
The Order statuses form is used to define the required order statuses. Order statuses serve to inform customers and the e-store staff about the current order state.
Taxes
The Taxes form serves to define taxes used in calculations.
Tax rates
The Tax rates form is used to define tax rates, depending on the customer location and payer type.
Exemption from taxes
The Tax exemption form is used to define tax-exempt customers.


Delivery - Bitrix Site Manager - Content Management & Portal Solutions

Delivery

In this topic

  • Filter
  • Context bar
  • Delivery services

    • The Delivery services form is used for setting up the delivery services. This form allows to:

    • view the available delivery services in the table form;
    • change the delivery service parameters;
    • delete delivery services.

    The Delivery services form contains two main areas: filter and messages list.

    Filter

    The filter is used to set the parameters for selecting delivery services to be displayed in the list.

    Field | Description
Location | Filters results by the location to where products are delivered by the service.
Site | Finds delivery services by the site on which the service is operating.
Weight | Range of the total order weight applicable to the required delivery services.
Order cost | Range of order amount applicable to the required delivery services
Activity | Specifies to display all services, only active or only non-active ones. Non-active services are not offered for delivery.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
New delivery service | Opens a form in which you can provide parameters of a new delivery service.
Excel | Exports data from the table to the MS Excel format.

    Delivery services

    Field | Description
    Checkbox column | Used to select delivery services to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any delivery service opens a menu allowing to:
    • Edit parameters - edit the delivery service settings;
    • Delete - deletes the delivery service.
    ID | The ID of the delivery service.
    Name | The name of the delivery service as it will be displayed to customers.
    Site | The site on which this delivery service is available. Depending on the site, different delivery services are offered to customers.
    Weight | Range of the order weight that can be handled by the delivery service.
    Order price | Range of the order amount within which the choice of this delivery service is possible. If the currency of the range differs from the order currency, the value is automatically converted into the order currency at the current exchange rate.
    Sort. | The delivery service sort weight; used when displaying the service in lists.
    Active | Defines whether the delivery service is active or not. Inactive services are not offered to customers.
    Price | A value to be added to order price to pay the delivery. If its currency differs from the order currency, the value is automatically converted into the order currency at the current exchange rate.

    See also

    Creating and editing a delivery service
    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Creating and editing a delivery service - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a delivery service

In this topic

  • Context bar
  • Fields
    •

    This form serves to set parameters of a delivery service used to deliver products to customers.

    Context bar

    Button | Description
Delivery services | Opens a list of delivery services.
Add new | Creates a new delivery service in this form.
Delete | Deletes the current delivery service.

    Fields

    Field | Description
ID | The delivery service ID.
Name | The delivery service name as it will be displayed to customers.
Site | Site on which this delivery service is operating. Depending on the site, different delivery services are offered to customers.
Shipping periods | Specifies the period of time within which the order will be handled to a client.
Weight | Range of the order weight that can be handled by the delivery service. Weight should be defined in the same units as the weight of products in the cart (by default, in grams). You can specify only one of the two bounds (for example, if the From field is 100 and the To field is empty or is 0, the delivery service can be offered for orders whose total weight is more than 100 grams).
Order price | Range of the order amount within which the choice of this delivery service is possible. If the currency of the range differs from the order currency, the value is automatically converted into the order currency at the current exchange rate. Similarly to Weight, you can specify only one of the two bounds.
Active | Defines whether the delivery service is active or not.
Price | A value to be added to order price to pay the delivery. If its currency differs from the order currency, the value is automatically converted into the order currency at the current exchange rate.
Description | A text informing customers about special conditions of delivery.
Location | The locations where this service can deliver orders, at the conditions and price specified. You can choose one or more locations. For more information about locations, see here.
Location group | Group of locations where this service can deliver orders, at the conditions and price specified. For more information about groups of locations, see here.

    See also

    Delivery
    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Payment systems

In this topic

  • Filter
  • Payment systems
    •

    The Pay system form is designed for defining the payment systems to be used by the store customers to pay for their orders.

    Filter

    The filter is used to set the parameters for selecting the payment systems to be displayed in the messages list.

    Field | Description
Site | Specifies to display all systems or only those active on certain sites.
Currency | Specifies whether to display all systems or only those supporting certain currencies.
Activity | Specifies whether to display all systems, or only active/inactive.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
New payment system | Shows a menu where you can select a site to which a new payment system will be added.
Excel | Exports data from the table to the MS Excel format.

    Payment systems

    Field | Description
    Checkbox column | Used to select payment systems to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any payment system opens a menu allowing to:
    • Modify - edits the payment system parameters;
    • Delete - deletes the delivery service.
    ID | The payment system ID.
    Name | The name of the payment system.
    Site | The site on which the payment system is available. Depending on the site, different payment systems can be offered to customers.
    Currency | The currency that is valid for this payment system.
    Active | Defines whether the payment system is active or not.
    Sort. | The sort weight; used when displaying the service in lists.
    Selected | Number of records selected from the database.
    Checked | Number of marked records.


Creating and editing a payment system

In this topic

  • Context bar
  • Editing form
  • "Payment system" tab
  • "<payer type>" tab
  • Controls
  • Handler files
    •

    This form is used to provide parameters of a new or existing payment system.

    Context bar

    Button | Description
Payment system list | Switches to a form containing a list of payment systems.
Add a payment system | Creates a new payment system in this form.
Delete payment system | Deletes the current payment system.

    Editing form

    "Payment system" tab
    Field | Description
ID | The payment system ID.
Site | The site on which the payment system is available. Depending on the site, customers are offered different sets of payment systems.
Currency* | Currency in which the payment system functions.
Name* | The name of the payment system to display in the administrative section.
Active | Indicates the payment system is active.
Sorting index | Sort weight of the location. The more is the value, the higher the payment system is positioned in lists.
Description | Short text (up to 250 symbols) devoted to inform customers of the payment system special features.

    * - Required fields.

    "<payer type>" tab

    Here you can set the payment system parameters for the given payer type.

    Field | Description
Applicable to this payer type | Defines whether the payment system is available for this payer type or not.
Name* | Name of the payment system to display to payers of this type, in the public section.
Handler* | Select here the file handler to process payments performed using this payment system.
Open in new window | If checked, the results of processing the payment with the selected handler will be displayed in the new browser window.
Handler properties | If the selected handler offers settings to configure, this section displays them.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of payment systems. Displayed when editing an existing payment system.
Apply | Applies changes performed on this page without switching to the list of payment systems.
Reset | Cancels current changes and restores parameters to their original values.

    Handler files

    Payment system file handlers are used as follows.

    • Handler file is called immediately after an order is placed, and also if a customer chooses to repeat payment, in the personal section. This file can contain script displaying the required payment means, or a form that can be used to dispatch payment information to the payment system. For details, please see Handling payment systems.
    • Result handler is called by the system to request parameters of order payment from the payment system. If the payment system does not return any results, the result handler is not required.


Handling payment systems - Bitrix Site Manager - Content Management & Portal Solutions

Handling payment systems

In this section

  • Handler file example
  • The processing results
  • Predefined templates
    •

    The integration of an e-store with payment systems is implemented by the payment system processing files. These files are created individually for each payment system and called after order completion and also when the customer chooses the order repeat function in the personal section. This file can contain a script which will display the required payment paper, or the form for sending data to the payment system.

    The following are the steps required to integrate handler files:

    • copy the required handler file templates from /bitrix/modules/sale/payment to /bitrix/php_interface/include/payment;
    • edit files in /bitrix/php_interface/include/payment so that their functionality satisfy your expectations, and meet requirements of the corresponding payment systems. The typical changes are: replacing the test payment system numbers and passwords with the real numbers and password obtained upon registration in the payment system; adding the stamp and signature images to the bill; changing the form appearance according to the site design etc;
    • add more processing files of other payment systems, if needed;
    • enter/change paths to the processing files of payment systems in the Payment systems form.

    Handler file example

    A typical Handler file looks as follows (for http://www.secpay.com).

    <form name="secpay" action="https://www.secpay.com/java-bin/ValCard" method=POST>

<!-- You code in the system -->
Merchant Id
<input type="hidden" name="merchant" value="secpay">

<!-- Unique transaction number -->
Transaction Id
<input type="hidden" name="trans_id" value="Invoice_<?echo $ORDER_ID ?>">

<!-- Sum -->
The Amount
<input type="hidden" name="amount" value="<?echo $arOrder["PRICE"]?>">

<!-- Transition addresses according to the successful and unsuccessful payment -->
The Callback
<input type="hidden" name="callback"
value="http://www.mysite.com/successcallback.html;http://www.mysite.com/failcallback.html">

<!-- Test request indication -->
<input type=hidden name="options" value="test_status=true,dups=false">

<!-- Additional parameters -->
<input type=hidden name="font_face" value="Arial">
<input type=hidden name="bgcolor" value="white">
<input type="submit" value="Submit Order">

</form>

    You need to specify the syntax (communication interface) of the payment system in the technical support service of this payment system.

    The processing results

    The ability to automatically receive the result and order payment parameters from a payment system depends on the specific payment system. You can use the two basic methods to receive response from a payment system.

    • If a payment system allows to request the order processing status, you can create a result acquisition script. For example, the assist.ru payment system offers this feature. The result handler file is to request the payment system about the order status and parameters and, after that, store the required information. The result handler file will be called by the Update status command of the Orders form in the site control panel (administration section). For an example, see the assist.ru payment system file: bitrix/php_interface/include/payment/assist_res.php. The path to the result handler should be specified in the Payment systems form.
    • If a payment system returns a result right after processing an order request, the handler code should be inserted into the payment system handler file. For example, see the ibill.com payment system processing file: /bitrix/php_interface/include/payment/ibill_f.php.

    Predefined templates

    These templates are located in /bitrix/modules/sale/payment/. Copy the required templates to /bitrix/php_interface/include/payment before editing them.

    File | Description
assist.php | Handler file for credit card payments using the assist.ru system.
assist_rapida.php | Handler file for credit cards payments using the Rapida system via assist.ru.
assist_res.php | Result acquisition script for use with the assist.ru system.
betaling.php | Handler file for credit card payments via http://betaling.viborgnet.dk.
bill.php | Handler file for the bank transfers (bill print-out).
bill_body.php | Help file for use with bill.php.
ibill.php | Handler file for credit card payments by using the ibill.com system.
ibill_f.php | Handler file for credit card payments via ibill.com with the result acquisition.
paycash.php | Handler file for payments by using the Yandex.Money system.
paypal.php | Handler file for credit card payments via paypal.com.
post.php | Handler file for the postal orders payment.
sberbank.php | Handler file for payments via the Savings Bank of Russia.
webmoney.php | Handler file for payments via Webmoney.


Payer types - Bitrix Site Manager - Content Management & Portal Solutions

Payer types

In this topic

  • Filter
  • Context bar
  • List of payer types
    •

    The Payer type form is designed to manage the list of payer types that are allowed to make orders on the site. For each payer type, you have to specify:

    • a separate set of properties which customers are to fill them in while completing an order;
    • payment system handlers with which a customer can pay for their orders.

    Filter

    The filter is used to set the parameters for selecting payer types to be displayed in the list.

    Field | Description
Site | The site for which payer types are be displayed.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
New payer type | Opens a form in which you can create a new payer type.
Excel | Exports data from the table to the MS Excel format.

    List of payer types

    The following values are used in the list of payer types.

    Field | Description
    Checkbox column | Used to select payer types to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any payer type opens a menu allowing to:
    • Edit - edits the payer type;
    • Delete - deletes the delivery service.
    ID | The payer type ID.
    Site | The site on which this payer is effective. Different sites offer different payer types to clients.
    Name | The name of the payer type as it will be displayed to the store customers.
    Sort. | Defines the position of the payer type in lists.
    Properties | Number of order properties assigned to the payer type. The link opens a list of order properties.


Creating and editing a payer type

In this topic

  • Context bar
  • Payer type editing form
  • Controls

    • This form is used to create or edit a payer type.

    Context bar

    Button | Description
Payer types | Opens a form containing the list of payer types.
Create a new payer type | Creates a new payer type in this form.
Delete payer type | Deletes the current payer type.

    Payer type editing form

    Field | Description
ID | The existing payer type ID.
*Site | The site on which this payer is to be available. Different sites offer different payer types to clients.
*Name | The name of the payer type.
Sort index | Relative weight which defines the payer type position in lists.

    * - Required fields.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of payer types. Displayed when editing an existing payer type.
Apply | Applies changes performed on this page without switching to the list of payer types.
Cancel | Cancels current changes and restores parameters to their original values.


Order properties - Bitrix Site Manager - Content Management & Portal Solutions

Order properties

In this topic

  • Filter
  • List of order properties
  • Context bar
    •

    The Order properties form serves to define order properties which are to be filled in by a customer when making an order. The list of order properties depends on the customer payer type.

    Filter

    To display only orders with a certain set of parameters, set the appropriate filters for the list of orders.

    Field | Description
Payer type | Filter report by the registered payer type.
Property type | Finds properties with a certain type.
Included in profile | Defines whether to display properties which can be stored in the customer profile, or all properties.
Group of properties | Displays all properties or only those belonging to specific groups.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
New property | Shows a menu where you can select a payer type for which a property is to be created. Then, opens a property creation form.
Excel | Exports data from the table to the MS Excel format.

    List of order properties

    The list of order properties contains the following values.

    Field | Description
    Checkbox column | Used to select order properties to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any order property opens a menu allowing to:
    • Modify - edits the order property settings;
    • Delete - deletes the order property.
    ID | The order property ID.
    Payer type | Customers who choose this payer type will be offered to fill in the corresponding property.
    Name | The name of the property as it will be displayed to customers.
    Type The property type. The following values are available:
    • CHECKBOX - checkbox;
    • TEXT - string;
    • SELECT - drop-down list where one can select only one option;
    • MULTISELECT - multiple choice list;
    • TEXTAREA - text;
    • LOCATION - location;
    • RADIO - radio button.
    Required | Defines whether the field must be filled in or not. Properties whose "Use as ..." settings are active are mandatory regardless of the value in this field.
    Group | Property groups to which this property belongs. Property groups are used for usability only.
    Profile Defines whether the property is included in the user profile or not.

    If a customer made orders in the store some time ago, one can avoid filling all the properties included in their profile. A customer can choose one of the stored profiles to automatically fill in the order properties.

    A customer can edit their profiles on the personal page. It is recommended to include in the profile only those properties which are not changed from order to order, or those with a small list of variants (for example, the delivery address is usually constant and can be included into the profile, but the order contents varies; it is senseless to include it in the profile).


Creating and editing an order property - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing an order property

In this topic

  • Context bar
  • Form fields (property settings)
  • Controls
    •

    This form is used to create or edit order properties.

    Context bar

    Button | Description
Order properties list | Opens a form with a list of order properties.
Create a new property | Creates a new property in this form.
Delete property | Deletes the current property.

    Form fields (property settings)

    Field | Description
    ID | The property ID.
    Payer type | Clients who choose this payer type will be offered this property to fill in.
    Name | The name of the property as it will be displayed to customers.
    Mnemonic code The code which uniquely identifies the property. It is used to identify the "order property" object.

    Note
    This field is for use by developers.

    Type The property type. It can have one of the following values:
    • CHECKBOX - checkbox;
    • TEXT - string;
    • SELECT - dropdown list where you can select one variant from several ones;
    • MULTISELECT - list from which you can select several values;
    • TEXTAREA - text;
    • LOCATION - locations;
    • RADIO - radio-button.
    Required | Defines whether this field is required or not. Properties whose "Use as ..." settings are active are mandatory regardless of the value in this field.
    Default value | The value which will be set in the field by default.
    Sorting index | Relative weight of the property. Defines the position in the list.
    Include in profile Defines whether the property is included in the user profile or not.

    If a customer made orders in the store some time ago, one can avoid filling all the properties included in their profile. A customer can choose one of the stored profiles to automatically fill in the order properties.

    A customer can edit their profiles on the personal page. It is recommended to include in the profile only those properties which are not changed from order to order, or those with a small list of variants (for example, the delivery address is usually constant and can be included into the profile, but the order contents varies; it is senseless to include it in the profile).
    Property group | The property group to which this property belongs. Property groups are used for usability only.
    Size 1 Depends on the field type:
    • field length for properties of the TEXT type;
    • dropdown list size for the SELECT, MULTISELECT and LOCATION properties;
    • number of columns in the TEXTAREA properties.
    If the field is not set or zero, the default values are used.
    Size 2 | Number of rows in the TEXTAREA properties. If this field is not defined, the default size is used.
    Property description | Text informing users about how to fill this field. This text is displayed beside the input field.
    Use as location The value of the property will be used as the customer location to calculate the delivery cost. This checkbox can be selected only for the LOCATION properties.

    Define a property with the Use as location option active for each payer type, otherwise the delivery service processing will not function.
    Use as taxation location The value of the property will be used as a customer location for calculating tax rates. This checkbox can be selected only for LOCATION properties.

    Define a property with the Use as a location for taxes option active for each payer type; otherwise the tax rates will not be defined.

    A field with this checkbox can be titled as Location, Shipping Address, Billing Address etc.
    Use as e-mail Value of this field will be used as the e-mail address for registering new users. All e-mail messages will be sent to this e-mail address.

    If a property with the Use as E-Mail option active is not be defined, all unregistered users of this type will be registered with the default e-mail of the e-Store module settings.
    Use as a profile name Value of this property will be used as the user profile name.

    If a property with the Use as the profile name option active is not defined, all new profiles will be titled as Profile <date>. For example, the Last name of a customer can be the profile name.
    Use as a payer name | Denotes the payer's name is to be used in the payment papers.
    List items

    If the property type is SELECT, MULTISELECT or RADIO, you have to specify possible values (options) to include in the control.

    Field | Description
Code | A mnemonic code of the property value.
Name | The title (property value) to be displayed to users.
Sort. | Relative weight of the value. Defines the position of values in the list.
Description | The value description (meaningful only for RADIO properties).
Delete | Specifies values that will be deleted upon clicking Apply.

    For example, the SELECT Sex property can be assigned the following values:

    • "N / don't know / 50";
    • "M / male / 100";
    • "F / female / 150".

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of properties. Displayed when editing an existing property.
Apply | Applies changes performed on this page without switching to the list of properties.
Cancel | Cancels current changes and restores parameters to their original values.


Property groups - Bitrix Site Manager - Content Management & Portal Solutions

Property groups

In this topic

  • Filter
  • Context bar
  • List of property groups
    •

    The Property groups form is designed to define groups of order properties. The grouping is used only for the convenient display of properties in forms. The group of properties depends on the payer type, so each payer type has its own set of property groups.

    Filter

    To display groups for a certain payer type, set the appropriate filters.

    Field | Description
Payer type | Filter by the registered payer type.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
New group | Opens a property group creation form.
Excel | Exports data from the table to the MS Excel format.

    List of property groups

    The following values are used in the list of property groups.

    Field | Description
    Checkbox column | Used to select property groups to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any order property group opens a menu allowing to:
    • Modify - edits the property group settings;
    • Delete - deletes the property group.
    ID | The ID of the property group.
    Name | The property group name which will be displayed to customers.
    Payer type | The payer type to which the property group is bound.
    Sort. | Relative weight of the property group. Defines the position of property groups in the list. Within the group, properties are sorted according to their sorting value.
    Properties | Number of properties in this group. The link opens a list of properties.


Creating and editing a property group

In this section

  • Context bar
  • Editing form
  • Controls
    •

    Context bar

    Button | Description
Property groups | Opens a form with a list of property groups.
Create new group | Creates a new property group in this form.
Delete property group | Deletes the current property.

    Editing form

    Field | Description
ID | The ID of the property group.
Payer type | The payer type to which the group is bound.
Name | The property group title as it appears to customers.
Sort index | Relative weight of the property group. Defines the position in the list.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of property groups.
Apply | Applies changes performed on this page without switching to the list of property groups.
Cancel | Cancels current changes and restores parameters to their original values.


Locations - Bitrix Site Manager - Content Management & Portal Solutions

Locations

In this topic

  • Filter
  • Context bar
  • List of locations
  • Loading locations from file
  • "Import locations" tab
  • Example of a location file
    •

    • The Locations form is used to define location areas from which a customer will choose an order delivery destination. Turther, this location will be used for displaying a list of the available delivery services, calculation of delivery cost and as a part of the physical delivery address.

    Filter

    The filter is used to set the parameters for selecting locations to be displayed in the list.

    Field | Description
Country | A list of countries from which you can select the country to display in the list.
Country | Allows to use complex searches with country names.
City | The name of city to display.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
New location | Opens a form in which you can create a new location.
Excel | Exports data from the table to the MS Excel format.

    List of locations

    Field | Description
    Checkbox column | Used to select locations to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any location opens a menu allowing to:
    • Modify - edits the location parameters;
    • Delete - deletes the location.
    ID | The location ID.
    Country | The location country.
    City | The location city. The city should conform the location country.
    Sort. | Sorting value of location. The more is the value, the higher is the location position in lists.

    How to load locations from file

    You can load locations from a special file. To do so, use functions of the Import locations tab. Existing locations can be erased automatically by enabling the Clear existing locations option.

    "Import locations" tab
    Field | Description
File | A file containing locations. Click Browse to select a file on your computer.
Clear existing locations | This option erases all the existing locations before importing new ones from the file. Note! This options will kill all locations, even those specified in addresses of existing active orders.
    Example of a location file
    en
S,en,Russian Federation,ru,Russia
T,en,Moscow,ru,Moscow
T,en,Kaliningrad,ru,Kaliningrad
S,en,Ukraine,ru,Ukraine
T,en,Kiev,ru,Kiev
S,en,Estonia,ru,Estonia

    The first string (en in the example) contains the site whose name will be displayed in the administration section and used for search when importing.

    Other file lines must contain the data to import. First, the country is specified (the string starts with "S"), then all the cities in this country (strings start with "T"), then the next country and so on.

    Each string has the following format (below is an example; lines must not break in a real file):

    <Country/City tag (S/T)>,
<Site (language of name)>,<name for defined before site>,
<Site (language of name)>,<name for defined before site>...

    Names should be defined for all sites. If some of sites do not exist, they will be ignored.

    If a country already exists in the system, it will not be loaded but the existing record will be used. Cities are always loaded, regardless of whether such names are present or not.


Creating and editing a location

In this topic

  • Context bar
  • Fields
  • Controls
    •

    This form is used to provide parameters of a new or existing location. Locations define rules stipulating shipping order items to customers.

    Context bar

    Button | Description
Locations | Switches to a form with the list of locations.
Add a new location | Creates a new location in this form.
Delete location | Deletes the current location.

    Fields

    Field | Description
ID | The location ID.
Sorting index | Sort weight of the location. The more is the value, the higher is the item position in lists. If two or more locations share the same sorting index, they are sorted alphabetically.
Country
Country | Select here the country of this location. If you cannot find the desired country in the list, select <New country> and fill the New country form. If you select any existing country, do not fill the New country form.
New country (used to specify parameters of the new country)
Full name | Type here the full name of the country for each language used in the system.
Short name | Type here the short name of the country for each language.
City
No city | Check this option if the location does not define a specific city. If you provide a new country and do not check this option (i.e. enter both country and city), two locations will be created: a country without a specific city, and a country with the city specified. Please ensure that for every country, there are location without a city. This will allow customers to select this location and type the city manually in case the pair "country - city" is not available.
Full name | Type here the full name of the city for each language in the system.
Short name | Type here the short name of the city for each language.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of locations. Displayed when editing an existing location.
Apply | Applies changes performed on this page without switching to the list of locations.
Reset | Declines recent changes and restores parameters to their original values.


Groups of locations - Bitrix Site Manager - Content Management & Portal Solutions

Location groups

In this topic

  • Filter
  • Context bar
  • List of location groups
    •

    You can use the Location groups form to join locations into groups. This simplifies handling delivery services making it more efficient and convenient. You can create a location group and make all delivery services (handling items to locations of this group) linked to this group.

    If a new location is created, or delivery service rates change for some location, you can just add or delete the location from the appropriate group instead of changing the delivery service for each location in this group.

    Filter

    The filter is used to set the parameters for selecting location groups to be displayed in the list.

    Field | Description
Location | Location of the displayed group.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
New group | Opens a form in which you can create a new location.
Excel | Exports data from the table to the MS Excel format.

    List of location groups

    Field | Description
    Checkbox column | Used to select location groups to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any location group opens a menu allowing to:
    • Modify - edits the location group parameters;
    • Delete - deletes the location group.
    ID | The group ID.
    Name | The name of the location group.
    Sorting | The group sort weight. The more is the value, the higher is the position in lists.


Creating and editing a location group

In this topic

  • Context bar
  • Fields
  • Controls
    •

    This form is used to provide parameters of a new or existing location group.

    Context bar

    Button | Description
Location groups | Switches to a form with the list of location groups.
New location group | Creates a new location group in this form.
Delete location group | Deletes the current location group.

    Fields

    Field | Description
ID | The ID of the location group.
Sort index | Sort weight of the location group. The more is the value, the higher the group is positioned in lists.
Locations in group | Select here locations to be included in the group. To select more than one location, press and hold the Ctrl button while selecting.
Name | Type here the full name of the group for each language in the system.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of location groups. Displayed when editing an existing group.
Apply | Applies changes performed on this page without switching to the list of location groups.
Reset | Cancels current changes and restores parameters to their original values.


Statuses

In this topic

  • Types of order status
  • List of order statuses
  • State statuses
    •

    The Order statuses form is used to configure statuses in which an order can be. Statuses are used to inform clients and the e-Store staff about the current order state and operations currently being performed on the orders.

    Context bar

    Button | Description
New status | Opens a form in which you can create a new status.
Excel | Exports data from the table to the MS Excel format.

    List of order statuses

    Field | Description
    Checkbox column | Used to select statuses to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any status opens a menu allowing to:
    • Modify - edits the status parameters;
    • Delete - deletes the status.
    ID | The status ID.
    Sort. | Sort weight of the status. The more is the value, the higher the status is positioned in lists.
    Name | The name and description of the status. This text is displayed to clients in the public section.
    The following two statuses are preset and cannot be deleted:
    • N - initial status (the default name is Accepted), indicates that the order has been received by the e-store;
    • F - final status (the default name is Delivered), indicates that the order items has been paid and delivered to the customer.


Creating and editing an information status

In this topic

  • Context bar
  • Fields
  • Controls

    • This form is used to provide parameters of a new or existing order information status.

    Context bar

    Button | Description
Statuses | Switches to the form displaying the list of statuses.
New status | Creates a new status in this form.
Delete status | Deletes the current location group.

    Fields

    Field | Description
Code* | The unique code of the status. Must be specified as one Latin letter.
Sorting index | Sort weight of the status. The more is the value, the higher the status is positioned in lists.
Can move orders to this status | Select user group(s) which are allowed to move orders to this status.
Can edit and save orders in this status | Select user group(s) which are allowed to edit and save orders in this status.
Name* | Type here the name of the status for each language in the system.
Description | Type here the description of the status for each language in the system.

    * These fields are required.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of statuses. Displayed when editing an existing information status.
Apply | Applies changes performed on this page without switching to the list of statuses.
Reset | Cancels current changes and restores parameters to their original values.


Taxes - Bitrix Site Manager - Content Management & Portal Solutions

Taxes

In this topic

  • List of taxes
  • How to create a tax

    • The Taxes form serves to add or edit taxes which are used by the system to calculate the order price. The page displays a list of taxes currently existing in the system. Each tax is bound to a specific site. For example, an English site will consider only taxes established for this site.

    List of taxes

    Field | Description
    Checkbox column | Used to select taxes to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any tax opens a menu allowing to:
    • Tax settings - edits the tax parameters;
    • Delete - deletes the status.
    ID | The tax code in the system.
    Modified | Date of the last modification of a tax.
    Site | The site on which the tax is used. Depending on the site, various taxes can be used.
    Name | The name of a tax.
    Mnemonic code | The symbolic code of the tax (Latin letters only).
    Rates | Number of rates specified for this tax. The link opens a form containing a list of tax rates.

    See also

    Tax management

    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Creating and editing a tax

In this topic

  • Context bar
  • Forms
  • Controls
    •

    This form is used to provide parameters of a new or existing tax.

    Page menu

    Button | Description
Taxes | Switches to the form displaying the list of taxes.
New tax | Creates a new tax in this form.
Delete | Deletes the current tax.

    Forms

    Field | Description
ID | The ID of the tax. Displayed when editing an existing tax.
Modification date | The date when the tax was last modified. Displayed when editing an existing tax.
Site | Select here a site where tax is to be applicable. Different sites use different taxes.
Name | The descriptive name of the tax.
Mnemonic code | Special code uniquely identifying the tax object in the system. Note This field is generally for use by developers.
Description | Arbitrary description of the tax.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of taxes. Displayed when editing an existing tax.
Apply | Applies changes performed on this page without switching to the list of taxes.
Reset | Cancels current changes and restores parameters to their original values.


Tax management - Bitrix Site Manager - Content Management & Portal Solutions

Tax management

In this topic

  • Tax settings
  • Adjusting tax rates
  • Example of the order cost calculation
  • Exemption from taxes
    •

    If any tax is specified in the system, it will be used for calculating the order price. The e-Store module adheres to the following tax structure.

    • Taxes are set independently for each site. The number of taxes is unlimited;
    • Tax rates can depend on the payer type and the payer location. Rates are defined in percents. The number of rates is not limited. Tax rates can be included in price;
    • Some customers can be set as exempt from tax. For such cases, you should set the tax exemption parameters for groups to which the customers belong.

    Tax settings

    Taxes can be defined on the tax settings page (e-Store -> e-Store Settings -> Taxes). On this page, you can add taxes to be used on your sites. Each tax is bound to a specific site. For example, the English site will use only taxes that are defined for this site.

    Adjusting tax rates

    Tax rates are defined on the Tax rates page (e-Store -> e-Store Settings -> Tax rates). On this page you can enter rates of taxes according to the customer location and payer type (providing the payer type is optional).

    To calculate taxes for a certain order, the system will select tax rates that meet the following requirements:

    • the tax is bound to the site on which the order is being made;
    • the location specified by the customer in the property for which the Use as taxation location option is enabled, should be included in the list of locations where this rate is valid;
    • the payer type defined for this rate is the same as the payer type selected by the customer at the ordering time (or no payer type is defined for the current rate);
    • the tax rate is active.

    If a country stipulates several locations, and you need to define the tax rate for the whole country, you are recommended to create a location group including all the country locations, and specify this group when defining a tax rate.

    If more than one tax rate is specified for the order, taxes rates are applied in the following sequence:

    • Rates of taxes are applied according the Tax priority index field, starting with the rate with the least priority value.
    • A tax rate is applied to the amount in which all taxes with the lesser value of the
      Tax priority index field are already included. In other words, the compound percents are in effect.
    • If the values of the Tax priority index fields are equal, they are summed up and then applied to the amount.
    Example of the order cost calculation

    Let us assume that we are purchasing items to the amount of €25. A discount for the sum exceeding €20 is 2%. Also, assume that the following tax rates exist for this order:

    • tax rate 1 with the rate of 18.5% and the priority index of 100;
    • tax rate 2 with the rate of 2.7% and the priority index of 100;
    • tax rate 3 with the rate of 3% and the priority index of 200.

    The discounted price of the purchased items will be €24.5 (25 - 25 * 2% / 100).

    Tax rate 1 makes €4.53 (24.5 * 18.5% / 100).
    Tax rate 2 makes €0.66 (24.5 * 2.7% / 100).
    After Tax rate 1 and Tax rate 2 are applied, the order amount makes up €29.69 (24.5 + 4.53 + 0.66).

    Tax rate 3 makes €0.89 (29.69 * 3% / 100).

    After applying the discount and all of the taxes, the order cost will be €30.58 (29.69 + 0.89). The delivery cost is to be added to this value.

    Exemption from taxes

    You can use this feature if there are customers which can be partially exempted from taxes. Create a special group of customers, select it on the page of exemption from taxes (e-Store -> e-Store Settings -> Tax exemption), and indicate taxes that should not be applied to members of this group.

    Upon receiving documents confirming the right to be exempted from taxes from a customer, add this customer to the created user group. After that, this customer will be able to choose: whether to use tax exemption, or complete the order using common rules. If the customer chooses tax exemption, the taxes specified on the Tax exemption page of the tax exempt user group will not be added.


Tax rates - Bitrix Site Manager - Content Management & Portal Solutions

Tax rates

In this topic

  • Filter
  • Context bar
  • List of tax rates
    •

    The Tax rates form is used to specify rates for taxes depending on the location and the payer type (optional).

    Filter

    The filter is used to set the parameters for selecting tax rates to be displayed in the list. The table below describes the filter fields.

    Field | Description
Tax | Mask of the name of the required tax rates.
Site | The site on which the required rate is active.
Payer type | Payer type whose tax rates are to be displayed.
Location | The location whose tax rates are to be displayed.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
New tax rate | Opens a form in which you can create a new tax rate.
Excel | Exports data from the table to the MS Excel format.

    List of tax rates

    Field | Description
ID | The ID of the tax rate.
Modified | The date and time the tax rate was last modified.
Name | The name of the tax rate.
Payer type | The payer type for which this tax rate is applied.
Rate | The tax rate value.
Included in price | Indicates that this tax is already included in product price.
Tax priority index | Defines the tax application order. If the values of the Tax priority index fields are equal, they are summed up and then applied to the amount.

    See also

    Tax management

    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Creating and editing a tax rate

In this topic

  • Context bar
  • Forms
  • Controls
    •

    This form serves to edit parameters of a new or existing tax rate.

    Context bar

    Button | Description
Tax rates | Switches to the form displaying the list of tax rates.
New tax rate | Creates a new tax rate in this form.
Delete | Deletes the current tax rate.

    Forms

    Field | Description
ID | The ID of the tax rate. Displayed when editing an existing tax rate.
Modified | The date when the tax rate was last modified. Displayed when editing an existing tax rate.
Tax* | The tax to which this rate is bound.
Active | Indicates whether the rate is active or not. Inactive rates cannot be used in calculations.
Payer type | Payer type to which this tax rate can be applied.
Rate* | The tax rate value.
Included in price | Indicates whether the tax rate is included in the price of products.
Tax priority index* | Tax rates with the equal priority indexes are added. Tax rates having different priority values form compound percents.
Locations** | Specify here location(s) to which this tax rate can be applied.
Location groups** | Select here location group(s) to whose locations this tax rate can be applied.

    * - Required fields.
    ** - You have to select a value in at least one of these fields. That is, you have to select either location or location group. You can also select the desired values in both fields.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of tax rates. Displayed when editing an existing tax rate.
Apply | Applies changes performed on this page without switching to the list of tax rates.
Reset | Cancels current changes and restores parameters to their original values.


Tax exemption

The Tax exemption form displays user groups for which the tax exemption rules can be applied.

Report table

Field | Description
Action menu
Clicking the action button of any location group opens a menu allowing to:
  • Modify tax exemption - edits the tax exemption parameters for the respective group.
Modified | The date the tax exemption parameters was last edited.
User group | The user groups for which tax exemption can be applied.
User Group description | The user group description.
Taxes | The taxes from which the user group is exempted.

See also

Taxes management

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Editing tax exemption settings

In this topic

  • Context bar
  • Form fields
  • Controls
    •

    This form serves to edit the database record describing from which taxes the user group is exempted.

    Context bar

    Link | Description
User group list | Switches to the form displaying the list of tax exemption records.

    Forms

    Field | Description
ID | The tax exemption record ID.
User Group Name | The user group to which the tax exemption rule is applicable.
User Group Description | The user group description.
Tax exemption | Select here taxes from which the user group is exempted. Hold the Ctrl button down to select more than one tax.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of tax exemptions. Displayed when editing an existing tax exemption.
Apply | Applies changes performed on this page without switching to the list of tax exemptions.
Reset | Cancels current changes and restores parameters to their original values.


Orders - Bitrix Site Manager - Content Management & Portal Solutions

Orders

In this topic

  • Filter
  • List of orders
  • Order operations
  • How to print order documents
  • How to view full order information
  • How to pay for an order
    •

    The Orders form serves for managing orders of the store customers. By using this form, you can:

    • view orders for products and services;
    • delete and cancel orders;
    • change the order state and statuses.

    Filter

    To view orders with certain parameters, set the appropriate filters for the list of orders. The table below describes the filter fields.

    Field | Description
    Order date | Specifies the range of dates within which the required orders occurred.
    Order ID | Finds orders by the order ID.
    Site / Currency | Specifies the site whose orders are be displayed, and the currency of the required orders.
    Order status Allows to find orders by one or more status in which the required orders are, e.g.:
    • Accepted;
    • In process;
    • Shipped;
    • Delivered.
    Date of status modification | Allows to display orders whose status changed within the specified range of dates. To define the range of dates, you can use either the list with the number of days or calendars.
    Paid | Displays paid, unpaid or all orders.
    Delivery allowed | Displays orders whose delivery allowed, not yet allowed, or all orders.
    Payment is authorized in PS | Displays all orders or only those with a certain status of authorization in the payment system.
    Payment system | Finds orders that were paid using a required payment system.
    Cancelled | Displays cancelled, non-cancelled or all orders.
    Customer | The "Customer" filter field selects orders by the customer's first name, last name or e-mail address. If don't have the exact information, you can use wildcards % and ? (for example, if you know that the e-mail of the customer starts with "orders", you can enter "orders%" in this field).
    Product ID (in order) | Allows to find orders by the ID of a product in the order.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Excel | Exports data from the table to the MS Excel format.

    List of orders

    The list of orders displays the following values.

    Field | Description
    Checkbox column | Used to select orders to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any order opens a menu allowing to:
    • Order details- views the order details; some parameters can be edited;
    • Print- prints the order papers;
    • Edit order - opens the order editing form;
    • Delete - deletes the order.
    ID | The ID of the order; the date it was created.
    Paid | Indicates whether the order has been paid or not.
    Canceled | Indicates whether the order has been canceled or not.
    Status | The current order status (e.g. accepted, paid etc.).
    Sum | Total amount of the order, including discounts, extras, taxes and delivery.
    Customer | The ID, name and last name of the customer as registered in the system. The link on the ID opens the user editing form.
    Payment system | The payment system preferred by the customer.
    PS response | If the payment system allows obtaining the payment status, this field displays it (e.g. succeeded, failed).
    Items | The order contents.

    Order operations

    The system offers a set of operations which can be applied to each order in the list. To do so, select the required orders by checking the boxes in the Checkbox column, and then select the desired action in the Action bar below the list.

    Select the action of your choice and click Apply.

    Action | Description
Update payment system statuses | Queries the payment systems for the new status information on the selected orders.
Export to Excel | Exports information about the selected orders to a XLS file.
Export to CSV | Exports information about the selected orders to a CSV file.
Export to CommerceML | Exports information about the selected orders to a CML file.

    How to print order documents

    To print documents for a certain order, select Print in the Action menu to open the printing documents form.

    How to view full order information

    To view the full order information, select the Order details in the Action menu to display the form with the full information.

    How to pay for an order

    To pay an order (in other words, change the Paid field value to Yes), select Order details in the Action menu (which opens the order details form), and change the payment status in the Payment section (the Order tab) .


Order details - Bitrix Site Manager - Content Management & Portal Solutions

Order details

In this topic

  • Context bar
  • Order information
  • "Order" tab
  • "Order items" tab
  • "Transactions" tab
  • Operation on orders
    •

    Context bar

    Button | Description
Orders | Opens the list of orders.
Edit order | Opens a form in which you can edit the order.
Print order | Opens a form allowing to get the printed order documents.
Delete order | Deletes the current order.

    Order information

    The full information about a certain order is displayed in the detailed order review form.

    "Order" tab

    This tab contains the main order parameters.

    Field | Description
    Order ID (the date when the order was placed)
    Last modification date | The date the order was last edited or modified in any other way.
    Order site | The site on which the order was placed.
    Current status The order status. The following statuses are available:
    • Accepted;
    • In progress;
    • Shipped;
    • Delivered.
    Order amount | Total order amount to be paid (includes taxes, delivery and so on).
    Cancelled | Indicates whether the order was cancelled or not.
    User account
    User | The real customer name.
    User login | The registered name of the customer
    User e-mail | The e-mail address of the customer.
    Order parameters
    Payer type | The payer type. One of the types registered in the system (physical body, legal entity, etc.)
    Package
    Package | A package chosen by the customer when ordering.
    Delivery address
    E-Mail | The e-mail address of the order recipient.
    Location | The name of the location to which the order will be delivered.
    Zip | Zip.
    Postal code, address (without a city) | The order delivery address.
    Contact person | The person who is to receive the order.
    Customer comments | Additional information provided by the customer when ordering.
    Payment
    Payment system | Payment system used for paying the order.
    Paid | The payment status.
    Delivery service
    Delivery service | The name of the registered delivery service.
    Delivery permitted | Status indicating the order can be delivered; the person who permitted the delivery.
    Comment
    Comment | Comment provided by the e-Store staff.
    "Order items" tab

    This tab shows the order contents.

    Field | Description
Name | The name of the product.
Properties | Product properties to be passed to the order (ID, colour, size etc.).
Price type | Type of the price by which the customer buys the product.
Quantity | Number of product items.
Price | Total price of this order entry.
Discount | Total amount of discounts applied.
Tax | Total amount of taxes.
Delivery | Cost of delivery of this order.
Total | Total order amount.
    "Transactions" tab

    This tab displays the flow of the client's fund in the context of the current order.

    Field | Description
    Date | The date and time the transaction was performed.
    User | The ID, first and last names of the user who carried out the transaction.
    Amount The transaction amount.
    • Negative values (with "-") means debiting funds from the client's account.
    • Positive values (with "+") means placing funds to the client's account.
    Description | Standard description of the transaction.
    Comment | Any comment posted.

    Order operations

    In the detailed order review form, you can can perform the following actions.

    Operation | Action
Cancel or restore the order | Use the Change status link beside the Canceled field.
Pay or cancel the payment | Use the Change status link beside the Paid field.
Confirm or cancel the delivery permission | Use the Change status link beside the Delivery allowed field.
Change the order status | Use the Change status link beside the Current order status field.
Add comments to the order | Use the Add comment link beside the Comment field. This can be any text describing the order flow, which will available only for the e-Store staff.


Printing order papers - Bitrix Site Manager - Content Management & Portal Solutions

Printing order papers

In this section

  • Context bar
  • "Print documents" tab
  • Control buttons
  • Notes for administrators
    •

    The Print order papers form serves to print the documents (bills, invoices etc.) related to the orders made by the store customers. By using this form, you can print documents using both the predefined and your own templates.

    Context bar

    Button | Description
Orders | Opens a list of orders.
Edit order | Opens a form in which you can edit the current order.
Order details | Opens a form with the detailed information about the current order.

    "Print documents" tab

    The Print documents tab displays the order summary.

    Order
    Order no. | The order number (ID) in the system.
    Order date | The date the order was placed or last modified.
    Site of order | The site on which the order was placed.
    Status | The current status of the order.
    Canceled / Paid / Delivery allowed | The current order state.
    This section contains the list of order items.
    Include | Name | Quantity | Price | Amount
[1] | [2] | [3] | [4] | [5]
    Field | Description
[1] | Specifies whether this item is included in the print-out or not. Some templates permit only a part of order items to be printed. This field allows to specify items that are to be printed. If a template is not enabled for partial print-outs, all items will be printed.
[2] | The name of an order item (product).
[3] | Number of product units purchased.
[4] | Price of unit including discounts.
[5] | Total value of this order item.
    [tax] | Taxes applied to the order, and their amounts.
    Delivery | Cost of delivery of the order.
    Total | Total order amount (including taxes and delivery).
    Document template | Choose here the templates that are to be used for printing documents.

    Control buttons

    Button | Description
Print | Click Print to generate the print-out form. The forms are opened in new windows. Some templates generate a special kind of forms in which some text can be edited (date, number etc.). When in the print-out form window, press Tab to highlight the editable fields.

    Notes for administrators

    Scripts containing the user templates should be stored in /bitrix/admin/reports/.

    Scripts containing the predefined templates should be stored in /bitrix/modules/sale/reports/.

    The system enumerates all the .php files from the above directories, and offers them as the print templates. If a user template has the same name as one of the predefined templates, the user template is used. The inner text of the <title> tag is displayed as the template name.

    If you are not satisfied by any of the predefined templates, copy it to the user template folder and correct it according to your goal. You can create as many user templates as you wish.

    Editable text areas in the print-out forms are the common input fields (input type="text") with no borders.

    Document template

    The document template is a PHP script. The following variables are available in scripts.

    Variable | Description
    $ORDER_ID | The ID of the current order.
    $arOrder | An array of order parameters (ID, delivery, cost, creation date, etc). For your version, you can obtain the contents of this array with the following call in the document template: print_r($arOrder).
    $arOrderProps An array of order properties. Order properties are defined on the order properties page of the e-Store module. Values of order properties are typed by customers when placing an order. The array has the following structure:
    array(
    "mnemonic code (or ID,
     if the mnemonic code is empty)
     of property" =>
    "property value"
)
    $arBasketIDs | An array of the order items (codes of the corresponding cart items) selected for printing. Developers are free to use or not use this array.
    $arQuantities | An array of quantities of items in the order selected for printing. Elements of this array correspond to the $arBasketIDs array (that is, an item with the code $arBasketIDs[$i] has the quantity of $arQuantities[$i]). Developers are free to use or not use this array.

    The template display name is taken from the <title> tag. If the <title> tag has an optional attribute langs, the document template will be displayed only on sites whose names appear in the value of this parameter. For example, if the template has a string:

    <title langs="ru,en">Invoice</title>

    the template will have the name Invoice, and will be displayed only on the ru or en sites.


Internal user accounts

In this topic

  • Filter
  • Context bar
  • List of accounts
    •

    The Internal user accounts form (e-Store -> Customer accounts -> Accounts) displays a list of internal user accounts and shows their balance.

    Filter

    The filter is used to define one or more parameters to select accounts that are to be displayed in the list.

    Field | Description
    User | Searches for an account by the first and last names, e-mail address of the account owner. You can use wildcards here.
    ID | The ID of the required user who owns an account.
    User login | Searches for an account by the login of the account owner.
    Currency | Currency of an account.
    Locked Searches for an account by its active state:
    • yes - display only inactive accounts;
    • no - display only active accounts;
    • all - display all accounts.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add a new account | Opens a form in which you can create a new internal account.
Excel | Exports data from the table to the MS Excel format.

    List of accounts

    Field | Description
    Checkbox column | Used to select accounts to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
             Clicking the action button of any account opens a menu allowing to:
    • Edit account parameters- edits the internal user account;
    • Delete account - deletes the account.
    ID | The ID of the account in the system.
    User | The ID, name, login and e-mail address of an account owner.
    Balance | Current account balance.
    Locked | Indicates whether the account is active or not. Inactive accounts does not allow transactions to be performed. To unlock an account, mark it in the checkbox column, select the Unlock action in the action bar below, and click Apply.
    Transactions | Number of transactions on this account. Click the link to view the list of account transactions.
    Selected | Number of records (accounts) selected from the database.
    Checked | Number of marked records.
    [Total] | The total amount of all user accounts, separately for each currency.


Creating and editing an account

In this topic

  • Context bar
  • Form
  • Controls

    • This form is used to create and edit the internal user accounts.

    Context bar

    Button | Description
Accounts | Opens a form containing a list of internal user accounts.
Create a new account | Creates a new account in this form.
Delete | Deletes the current account.

    Form

    Field | Description
ID | The ID of the account in the system.
Last modification date | The date the account was last edited.
User | The ID of a user who owns the account. When creating a new account, you can select the user ID from the list by clicking [...].
Account amount | Specify here the amount of the account, and the currency of the amount.
Notes | An arbitrary comment to the account.
Reason to change the amount | Specify here the description why the amount is being changed.

    Controls

    Button | Description
Add | Saves the new account and switches to the list of internal user accounts. Displayed when creating a new account.
Save | Applies changes performed on this page and switches to the list of internal user accounts. Displayed when editing an existing account.
Apply | Applies changes performed on this page without switching to the list of internal user accounts.
Reset | Cancels current changes and restores parameters to their original values.


Transactions

In this topic

  • Filter
  • Controls
  • List of transactions

    • The Transactions form (e-Store -> Transactions) displays a list of all transactions performed on the client's account (e.g. placing or debiting funds).

    Filter

    The filter is used to define one or more parameters to select transactions that are to be displayed in the list.

    Field | Description
    User ID | The ID of the registered user on whose account the transaction was performed.
    User login | Searches for transactions by the login of the user.
    User | Searches for transactions by the first and last names, e-mail address of the user. You can use wildcards here.
    Currency | Finds transactions by their currency.
    Transaction date Searches for transactions by the transaction date. The date can be specified in one of the following ways:
    • days since the last transaction;
    • range of days within which the transaction was performed.
    Order no | Searches for transactions by the number of order in whose context the transaction was performed.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Controls

    Button | Description
New transaction | Switches to the transaction creation form.
Excel | Exports data from the table to the MS Excel format.

    List of transactions

    Field | Description
ID | The unique ID of the transaction in the system.
Transaction date | The date the transaction was performed.
User | The ID, first and last names, e-mail address of the user on whose account the transaction was performed.
Amount | Amount of the transaction.
Order | Number of order in whose context the transaction was performed. You can click the order number to open the order details page.
Type | Type of the transaction.
Description | The ID, first and last names, login of the user who performed the transaction.


Performing a transaction

In this topic

  • Context bar
  • "Transaction" tab
  • Controls
    •

    This form serves to create and execute a new transaction on a user's account.

    Context bar

    Button | Description
Transactions | Switches to the form displaying the list of transactions.

    "Transaction" tab

    Field | Description
User | The ID of the registered user on whose account the operation (transaction) is to be performed. You can select the user ID from the list by clicking [...].
Transaction date | The date and time of the transaction. If you specify the forthcoming date and time in this field, the transaction will be fulfilled at the due date and time.
Amount | The transaction amount.
Currency | Currency of the transaction.
Record type | The required type of the transaction.
Order ID | If the transaction is to be performed in the context of a certain order, specify the order ID in this field.
Notes | Arbitrary comment to the transaction.

    Controls

    Button | Description
Save | Saves the transaction and switches to the list of transactions.
Reset | Cancels current changes and restores parameters to their original values.


Subscription renewal

In this topic

  • Filter
  • List of renewals
  • Controls
    •

    The Subscription renewal form (e-Store -> renewal) displays list of renewals. Renewals are used to prolong the user's permission to access paid content.

    Filter

    The filter is used to define one or more parameters to select records that are to be displayed in the list.

    Field | Description
    User | Specifies to find renewals by the first and last names, or the e-mail address of the account owner. You can use wildcards here.
    User ID | Searches by the identifier of a user for whom the subscription was renewed.
    User login | Searches for renewals by the login of a user for whom the subscription was renewed.
    Canceled Searches for renewals by its active state:
    • yes - match only canceled renewals;
    • no - match active renewals;
    • all - match all renewals.
    Last renewal date Searches for renewals by the date when the subscription was last renewed. The date can be specified in one of the following ways:
    • number of days elapsed from the last renewal;
    • range of days within which the renewal took place.
    Next renewal date | Finds renewals whose scheduled update date match this range.
    Base order ID | Searches for renewals applied to the order with this ID.
    Renewal succeeded Searches for renewal by its result state:
    • yes - search only successful renewals;
    • no - search only unsuccessful renewals;
    • all - search only all renewals.

    Click Set filter to activate the filter. To display all information, click Cancel.

    List of renewals

    Field | Description
    Checkbox column | Used to select renewals to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
             Clicking the action button of any renewal opens a menu allowing to:
    • Edit renewal - edits the subscription renewal parameters;
    • Delete- deletes the subscription renewal.
    ID | The renewal ID.
    User | The ID, name, login and e-mail address of a user for whom the subscription renewal was established.
    Canceled | Indicates whether the renewal is valid or not. Yes - the subscription renewal is invalid (i.e. canceled).
    Previous renewal | The date and time when the subscription was last renewed.
    Next renewal | The date and time of the next subscription renewal.
    Payment succeeded | Indicates the subscription renewal was paid successfully.
    Selected | Number of records selected from the database.
    Checked | Number of marked records.

    Controls

    Button | Description
Add | Switches to the renewal creating and editing form.
Save | Applies changes performed on this page.
Reset | Cancels current changes and restores parameters to their original values.


Creating and editing a renewal

In this topic

  • Context bar
  • Fields
  • Controls
    •

    This form is used to subscribe a user for access to a site resource, or edit the existing subscription parameters.

    Context bar

    Button | Description
Renewals | Switches to the form displaying the list of subscription renewals.
Add | Creates a new renewal in this form. Visible if only editing an existing renewals.
Delete | Deletes the current renewal.

    Fields

    Field | Description
ID | The renewal ID. Displayed when editing an existing renewal.
User* | The ID of the registered user for whom the renewal is to be created. You can select the user ID from the list by clicking [...].
Canceled | Indicates whether the renewal is valid or not. If checked, the subscription renewal is invalid (i.e. canceled).
Reason of cancellation | If the subscription is canceled, this field may contain the short descriptive text of the reason.
Module* | The module to whose content the paid access is to be renewed.
Product* | The ID of the product for which the subscription is to be renewed.
Product name | The full name of the product.
Product URL | Link to a page containing the product description.
Last renewal date | The date and time when the subscription was last renewed.
Next renewal date* | The date and time of the forthcoming subscription renewal.
Last renewal attempt succeeded | Indicates that the last subscription renewal was successful.
Renewal attempts remain | If the subscription is to be renewed automatically, this field may contain the number of renewal attempts to be performed. If set to 0, no attempts will be undertaken.
Base order ID* | The ID of the order to be renewed.
Description | Arbitrary description of the subscription renewal.

    * - Required fields.

    Controls

    Button | Description
Add | Saves the new subscription and switches to the list of subscription renewals. Displayed when creating a new subscription.
Save | Applies changes performed on this page and switches to the list of subscriptions. Displayed when editing an existing subscription.
Apply | Applies changes performed on this page without switching to the list of subscriptions.
Reset | Cancels current changes and restores parameters to their original values.


Credit cards

In this topic

  • Filter
  • Context bar
  • List of credit cards

    • The Credit cards form (e-Store -> Credit cards) displays a list of all registered credit cards that your clients use to pay orders.

    Important!
    To provide secure credit card handling, you have to specify password to be used for encrypting credit card numbers, on the e-Store module settings page. If you fail to assign the password, the warning message will be displayed.

    Filter

    The filter is used to define one or more parameters to select cards to be displayed in the list.

    Field | Description
    User | Searches for cards by the first and last names, e-mail address of the card holder. You can use wildcards here.
    User ID | The ID of the registered user who can pay using this credit card.
    User login | Searches for cards by the login of the card holder.
    Active Searches for cards by their active state:
    • yes - display only active cards (those which can be used for payments);
    • no - display only inactive cards;
    • all - display all cards.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add a new credit card | Opens a form in which you can create a new credit card record.
Excel | Exports data from the table to the MS Excel format.

    List of credit cards

    Field | Description
    Checkbox column | Used to select credit cards to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
             Clicking the action button of any credit card opens a menu allowing to:
    • Edit - switches to the credit card parameters editing form;
    • Delete - deletes the record containing information about the credit card.
    ID | The ID of a credit card in the system.
    User | The ID, name, login and e-mail address of a user - credit card holder who can pay using this card.
    Active Indicated the credit card is active.
    Inactive cards cannot be used for payments.
    Sorting | Sort weight of the card. The more this value is, the higher the card is positioned in lists.
    Currency | Currency in which payments with this credit cards are performed.
    Type | Type of the credit card
    Selected | Number of records (c/cards) selected from the database.
    Checked | Number of marked records.


Creating and editing a credit card

In this topic

  • Context bar
    "Credit card" tab
    Controls

    • This form is used to provide parameters of a new or existing credit card.

    Important!
    To provide secure credit card handling, you have to specify the password that is to be used for encrypting credit card numbers, on the e-Store module settings page. If you fail to assign the password, the warning message will be displayed.

    Context bar

    Link | Description
Credit cards | Switches to the form displaying the list of credit cards.

    "Credit card" tab

    Field | Description
ID | The credit card system identifier. Displayed when editing an existing credit card.
Date of the last modification | The date and time when the record was last modified. Displayed when editing an existing credit card.
User | The ID of the registered user who can pay using this credit card. You can select the user ID from the list by clicking [...].
Active | Indicated the credit card is active. Inactive cards cannot be used for payments.
Sort index | Sort weight of the card. The more this value is, the higher the card is positioned in lists.
Payment system* | Select here the payment system for which this credit card can be used.
Currency in which payments are allowed | Currency in which payments with this credit cards can be performed.
Credit card type | Select here the credit card type.
Credit Card Number* | Credit card number. Displayed in encoded form; only the last 4 digits of the number can be viewed.
Expiration Date | Date after which this credit card becomes invalid for payments.
CVC2 | The CVC2 code of the credit card (the last 3 digits on the back of a card).
Minimum allowed amount | Minimum amount that can be withdrawn from this card within a single transaction.
Maximum allowed amount | Maximum amount that can be withdrawn from this card within a single transaction.
Currency of amounts | Currency in which the values of the minimum and maximum amounts are specified.
Description | Arbitrary description.
Last activation | The date and time when this credit card was last used.

    * These fields are required.

    Controls

    Button | Description
Add | Saves the new credit card and switches to the list of credit cards. Displayed when creating a new credit card.
Save | Applies changes performed on this page and switches to the list of credit cards. Displayed when editing an existing credit card.
Apply | Applies changes performed on this page without switching to the list of internal user accounts.
Reset | Cancels current changes and restores parameters to their original values.


Discounts - Bitrix Site Manager - Content Management & Portal Solutions

Discounts

In this topic

  • Filter
  • Context bar
  • List of discounts
    •

    The Discount form serves to establish discounts and make them dependent on the order value. The discount is calculated on the total order amount, without delivery costs.

    Filter

    A filter is used to set the parameters for selecting the discounts to be displayed in the list.

    Field | Description
Site | The site whose discounts are to be displayed.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add a new discount | Opens a form in which you can create a new discount.
Excel | Exports data from the table to the MS Excel format.

    List of discounts

    Field | Description
    Checkbox column | Used to select discounts to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
             Clicking the action button of any discount opens a menu allowing to:
    • Modify discount parameters - switches to the discount editing form;
    • Delete - deletes the discount.
    ID | The ID of the discount.
    Site | The site on which this discount is valid. Different sites use different discounts.
    Act. | Indicates whether the discount is currently active or not. Inactive discounts are not offered to customers.
    Total order value | The range of the order amounts (without delivery costs) for which the discount is offered.
    Discount | Discount value. Discounts can be specified as relative values (percentage), or as fixed values.
    Sort | Sort order; defines how the discounts are positioned in lists.
    Selected | Number of records selected from the database.
    Checked | Number of marked records.


Creating and editing a discount

In this topic

  • Context bar
  • Form fields
  • Controls
    •

    Context bar

    Button | Description
Discounts | Opens a list of discounts.
Add a new discount | Creates a new discount in this form.
Delete | Deletes the current discount.

    Form fields

    Field | Description
ID | The discount ID.
*Site | The site on which the discount is active. Different sites use different discounts.
Applicable to orders | The range of the order amounts (without delivery costs) for which the discount is offered. You can define only one bound (for example, if the From field is set to 100, and the To field is empty or contains zero, the discount is offered to orders whose amount is more than or equal to 100).
*Discount value | The discount value. Discounts can be specified as relative values (percentage), or as fixed amounts which depends on the selection in the drop-down list beside the discount value field. If "%" is selected, the value is the percentage off the order price. Otherwise, the discount is an absolute value specified in the currency selected for the range.
Active | Indicates whether the discount is currently active or not. Inactive discounts are not offered to customers.
Sort index | Sort order; defines how the discounts are positioned in lists.

    * - Required fields.

    Controls

    Button | Description
Save | Saves changes and opens the list of discounts.
Apply | Applies changes and stays in this form.
Cancel | Cancels recent changes, reverts parameters to their original values and opens the list of discounts.


Commercial Catalog - Bitrix Site Manager - Content Management & Portal Solutions

Commercial Catalog

The Commercial Catalog is the module aimed to:

  • manage product prices;
  • export information in predefined formats like Froogle and CSV; the latter can be customized at export time;
  • import information in the CSV format;
  • export information in any format according to the user-defined profile.

Product catalog relies upon the Information Blocks module functions. Using the Commercial Catalog module features requires that the Information Blocks module is also installed.

You can customize your product catalog using the Commercial Catalog menu and the module settings page (Settings -> System settings -> Commercial Catalog). Prices in the product catalog are controlled through forms of the Information Blocks module.

To make an information block behave as the product catalog, you have to mark these information blocks as catalogs on the commercial catalog settings page (Settings -> System settings -> Commercial Catalog).

Main commercial catalog features:

Price types
A single product may have different types of price assigned to it. Different user groups can be configured to view and use different price type. Thus, you can introduce retail prices available to all site visitors, and wholesale prices which can be viewed by all visitors but available only for dealing to members of the "Bulk buyers" group.
Extra charges or discounts
One of the catalog price types is declared a base price. All other prices can be calculated based on this price, or they can be fixed manually. Prices can be recalculated automatically given the base price and the extra rate.
Export and import in the CSV format
The module can export and import the whole catalog and prices to/from the CSV file (see the corresponding topics for detailed information on export and import).
Shopping cart interoperability
A product is always put in the shopping cart at the price most favorable for the user.

See Also

Import
Export
Manual export to CSV

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Discount coupons

In this section

Filter
Context bar
List of coupons and discounts

The Discount coupons form (e-Store -> Commercial catalog -> Discount coupons) displays a list of all discount coupons and simple discounts which can be used by users to purchase products at a reduced price. You can use this page to add more discounts and coupons, and edit parameters of the existing ones.

Filter

To view discounts and coupons satisfying the search criteria, set the appropriate filters for the list of orders.

Field | Description
Site | Specifies to display discounts and coupons of the site to whose products the sought entity is applicable.
Active | Finds active, inactive or all discounts or coupons.
Active period | The period during which the sought entity is presumed to be active. You can specify either starting and ending dates of the active period, or just select (in the list) how many days elapsed since the entity was made active.
Name | The name of the sought entity.
Coupon | When searching for a coupon, you can type its code here.
Renew Specifies the role of the sought entity:
  • yes - specifies to display only coupons and discounts which can be used with subscription renewals;
  • no - finds only coupons and discounts which cannot be used with subscription renewals;
  • all - finds all entities.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
New discount | Opens a form in which you can add a new coupon or simple discount.
Excel | Exports data from the table to the MS Excel format.

List of coupons and discount

Field | Description
Checkbox column | Used to select entities to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
 Clicking the action button of any entity opens a menu allowing to:
  • Edit - switches to a discount and coupon editing form;
  • Delete - deletes the respective entity.
ID | The discount or coupon ID.
Site | The sites to whose products the respective entity is applicable.
Active from | The date from which the entity (discount or coupon) is active.
till | The date when the entity expires.
Active | Indicates the discount or coupon is active. Inactive discounts and coupons cannot be used with purchases.
Name | The name of the entity.
Sort | The sort weight of the discount or coupon. The more this value is, the higher the entity is positioned in lists.
Amount | The discount amount.
Renew | Indicates the discount or coupon can be used when buying a subscription renewal.


Creating and editing discount coupons

In this section

  • Context bar
  • Editing form
  • Discount
  • Restrictions
  • Controls
    •

    This form is used for creating or editing a discount or a discount coupon.

    Note
    A coupon is a kind of discount. A distinctive feature of a coupon is the unique code assigned to it, unlike a discount which do not have any specific code. To use a coupon, a customer has to enter the coupon code.

    Context bar

    Button | Description
Discounts | Opens a list of discounts and coupons.
Add new discount | Creates a new discount in this form.
Delete discount | Deletes the currently edited discount.

    Editing form

    "Discount" tab
    Field | Description
    ID | The unique discount ID.
    Modified | The date and time the discount was last modified.
    Site | The site to whose products the discount can be applied.
    Active | If checked, the discount is active and can be applied.
    Active period | Specify here the period during which the discount or coupon is to be active.
    Name | Enter here an arbitrary name of the discount or coupon.
    Sort index | The sort weight of the discount or coupon. The more this value is, the higher the entity is positioned in lists.
    Discount type Select here how you want to specify the discount value:
    • Percent - the discount is a percentage off the product price;
    • Fixed amount - the discount is entered as am amount to subtract from the product price.
    Discount amount | The discount value. Depending on the chosen type, you have to enter either a percent value, or an amount.
    Discount currency | Select here the currency in which the fixed amount discount is specified.
    Maximum discount amount | Maximum possible discount value. Generally used with percent discounts. The maximum amount should be specified in the currency selected in the previous field.
    Applicable to subscription renewal | If checked, the discount (coupon) can be used when purchasing the subscription renewal.
    Short description | Arbitrary comment.
    "Restrictions" tab
    Field | Description
    Coupon | If you want to make a coupon discount, type here the desired coupon code, or click Generate to have the code generated automatically.
    User groups allowed to use the discount | Choose user groups whose members can use the discount. If none is selected, the discount is available to all user groups.
    Price types to which this discount is applicable | Select here the types of prices to which the discount can be applied. If none is selected, the discount can be applied to prices of all types.
    Sections to which this discount is applicable Fields of this group can be used to denote the site sections to whose products the discount can be applied.
    • Click the Add button to add a section selected in the list above the button.
    • Click Delete to remove the respective section from the list.
    If no section is selected, the discount is applicable to products in all sections.
    Products with discount In this field you can select products which can be purchased at the currently edited discount. Click Add to add a product to the list.

    If no product is selected, the discount can be applied to all products in section selected in the previous field.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of discounts.
Apply | Applies changes performed on this page without switching to the list of discounts.
Cancel | Cancels current changes and restores parameters to their original values.


Markups and discounts

In this section

Context bar
List of markups and discount

The Markups and discounts form (e-Store -> Commercial catalog -> Markups and discounts) is used to manage markups and discounts in the system.

For short, markups and discounts are both hereinafter referred to as "discount" .

A discount is the percentage reduction from the product price. Each customer or a user group can be assigned individual discounts.

A discount type is the named discount value (e.g. Quantity discount). Named discounts are introduced for easier discount handling.

If you regularly offer the same discounts for your products, you may want to create a discount type based on the discount amount. In this case, the system will automatically calculate selling prices by adding the discount amount to the base product price. When the discount changes, the system automatically recalculates selling prices.

Context bar

Button | Description
New discount | Opens a form in which you can create a new discount or markup.
Excel | Exports data from the table to the MS Excel format.

List of markups and discounts

Field | Description
Checkbox column | Used to select discounts to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
 Clicking the action button of any discount opens a menu allowing to:
  • Edit - switches to a discount editing form;
  • Delete - deletes the respective discount.
ID | The discount ID in the database.
Name | Arbitrary name of the discount. For easier control, it is recommended to give meaningful and comprehensive names to discounts.
Amount | The percentage of price change. For markups, use positive values. For discounts, use negative values.
Recalculate prices | If checked, all the prices which use this discount (markup) will be recalculated upon clicking Save or Apply.


Markup (discount) parameters

In this section

  • Context bar
  • Editing form
  • Controls
    •

    Context bar

    Button | Description
List of discounts | Opens a list of discounts and markups.
New discount | Creates a new discount or markup in this form.
Delete | Deletes the currently edited discount or markup.

    Editing form

    Field | Description
ID | The discount or markup ID.
Name | An arbitrary name of a discount or markup. It is recommended to give names which clearly describe the discount or markup meaning.
Amount | The amount of discount or markup, in percent. Discounts have negative values, while markups have positive values.
Recalculate prices | If checked, changing the discount or markup amount causes all prices created using it to be recalculated.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of discounts and markups.
Apply | Applies changes performed on this page without switching to the list of discounts and markups.
Cancel | Cancels current changes and restores parameters to their original values.


Price types - Bitrix Site Manager - Content Management & Portal Solutions

Price types

In this section

  • Context bar
  • List of price types
    •

    The Price types form is used to manage types of prices which you can use to set different prices to different customer groups.

    Price types were introduced to facilitate assigning different prices to a product. For example, you can enter and show different prices for retail and wholesale customers, and dealers.

    Context bar

    Button | Description
New price type | Opens a form in which you can create a new price type.
Excel | Exports data from the table to the MS Excel format.

    List of price types

    Field | Description
    Checkbox column | Used to select price types to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
             Clicking the action button of any price type opens a menu allowing to:
    • Edit - switches to a price type editing form;
    • Delete - deletes the price type.
    ID | The price type identifier.
    Code | The symbolic code of the price type used in the administrative section to identify the type.
    Name | The price type name as it is displayed on different sites.
    Sort | The sort order of the price type in lists.
    Base | If Yes, this price type is the base price. Other price types are calculated from this price type.


Creating and editing a price type - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a price type

In this topic

  • Context bar
  • Form fields
  • Controls
    •

    This form is used to create and edit price types. Some form fields may be shown or hidden depending on the action: adding or editing a price type.

    Context bar

    Button | Description
Price types | Opens a list of price types.
Add price type | Creates a new price type in this form.
Delete price type | Deletes the currently edited price type.

    Form fields

    Field | Description
ID | The price type ID in the database. This field is only displayed when editing an existing price type.
Base | If this field is set to Yes, this price type is the base price. Other price types are calculated from this price type.
Code | The symbolic code of the price type used in the administrative section to identify the price type.
Sorting | The price type sort order. Affects the position of the type in lists.
Name | The name of the type for different sites.
User groups allowed to view prices of this type | Select here user groups whose members can view prices of this type (in price lists etc.).
User groups allowed to buy at prices of this type | Select here user groups whose members can buy products and services at prices of this type.

    Controls

    Button | Description
Save | Saves the price type and opens the Price types form.
Apply | Click this button to save the price type and stay in this form.
Reset | Resets the form fields to their initial values.


Entering prices - Bitrix Site Manager - Content Management & Portal Solutions

Entering prices

Nominating prices to products of the commercial catalog (or to elements in terms of information blocks) is performed as editing the information blocks elements. If the information block is marked as a product catalog in the Commercial Catalog module settings, you can assign prices to the element (product in terms of a product catalog).

The Base price field requires that you enter here the price value being the base for calculating other prices (for example, purchasing price).

Select the base price currency in the Base price currency field.

The In stock field is optional; here you can provide number of product units currently available.

Check the option Reduce quantity upon order if you want the value of the In stock field to automatically decrement when an order occurs. If this option is checked and the value of In stock becomes null, no further orders of this product are possible. If this option is unchecked, the In stock field is generally senseless.

Set the values of different price types for the product, or choose the desired discount (or markup) type. In this case, the real value is calculated automatically on the basis of the base price and the discount rate:

[Price] = [Base price] +
          [Base price] * [Discount/markup rate percentage] / 100

Currency of the resulting price always conforms to that of the base price. As soon as the base price or rate change, the dependant price is recalculated.

You can set the discount (markup) type to not set and specify the value and currency manually. In this case, the selling price is fixed and will not change when the base price or discounts change.


Settings - Bitrix Site Manager - Content Management & Portal Solutions

Settings

In this topic

  • Export and import
  • Catalogs
  • Selling access
  • Access
  • Controls
    •

    The Settings form is used to customize the module global settings.

    Export and import

    The Settings form of the commercial catalog is used to customize the module global settings.

    Parameter | Description
Type of information block to import from the CommerceML format | Defines the type of catalog to receive the information imported from 1C.
Automatically deactivate product if the price was not found (CommerceML) | If checked, deactivates a product without any price assigned.
Period of export to Yandex.Products | Defines how often data items selected in the List of information blocks are exported to Yandex.Products. See Automated export to Yandex.Products for more information.
Products not in CommerceML file | Default action for products that are not found in the CommerceML file. This parameter is used when importing data from such files.
Export to / Import from CSV
Available product fields | If products in your database has numerous fields, you could find it tiresome to select the required ones every time you perform export or import. This field allows to restrict displayed fields to the ones selected here.
Available price fields | Select here the price fields which will be available for the CSV export or import.
Number of catalog levels | Defines how many catalog levels will be available in the export or import files.
Available group fields | Here you can select the group fields available for selection when exporting data.
Available currencies | Currencies available for export or import.

    Catalog

    The system architecture assumes that an information block can be conferred a commercial catalog status, which imparts the utmost flexibility to the system. This group of settings allows to turn any existing information block into a commercial catalog and make the block a subject of export to Yandex.Products.

    Field | Description
Information block | The name of an information block.
Commercial catalog | Enabling this option of a required information block empowers it with the commercial catalog features.
Content selling | If checked, this catalog can be used to sell information content.
Export to Yandex.Products | Check this box if the information block data is to be exported to Yandex.Products.

    Selling access

    On this tab you can select user groups whose membership can be sold in order to grant access to paid resources. For example, you can sell permissions to access a certain site section, file downloads, advertising or any other site resources. You can define a time period during which users can use the paid resources.

    Generally, selling access involves the following actions to be performed:

    • create a user group with the appropriate permissions (Settings -> Manage users -> User groups);
    • enable selling access features for this user group here in this form;
    • add a user who paid for the access to this user group and define a period of membership (Settings -> Manage users -> Users).
    Field | Description
User group | The name of a user group.
membership can be sold checkboxes | Checking this box allows the membership of the respective user group to be sold.

    Access

    This form is used to customize access permissions for all user types in the system. What is more, by setting the default permission to the desired value, you can easily set permissions for users who have the <default> access rights.

    Field | Description
    Default | Changes the default permission. This affects all user groups that have the default access permission.
    [User group] Changes the permission of a specific user group. The following access permissions apply to the Commercial Catalog module:
    • deny - any access is denied;
    • read-only - users can only view the module files and settings;
    • write - full access.

    Controls

    Button | Description
Save | Saves the performed changes.
Reset | Cancels current changes and restores parameters to their original values.
Restore defaults | Resets module settings to their default values.


Export explained - Bitrix Site Manager - Content Management & Portal Solutions

Export explained

Exporting data from a catalog allows to set up the information interchange between your site and other sites or applications (for example, Microsoft Excel). The Export setup form helps you export the catalog information using both predefined and custom export templates. What is more, this form allows you to create export templates, place links to frequently used export templates and profiles to the menu, arrange for automated export execution through the use of agents or cron.

Developers will find the examples of templates in the Templates chapter.

There are two Export templates types: equipped with extra export settings (including step-by-step wizards), and without settings.

Parameterized templates

At startup time, the template first calls the appropriate export set-up script (export wizard) in which a user has to provide parameters required by the export template.

You can create a set of parameters and save it as an export template by using the command Add profile. When executing an export profile other than the default one, the export wizard is not launched; the export is performed on the basis of parameters previously saved in the profile.

You can have any export template set for the automated execution through the use of agents or cron (UNIX only), except the default template. This is because the default template assumes processing user input which cannot be accomplished in the automatic mode; all the required parameters must be stored in the profile beforehand.

Non-parameterized templates

Such templates are executed (that is, perform data export) right upon execution. No export profiles are created. A non-parameterized template does not assume extra parameters to be passed in and can be set up for automated execution via agents or cron.

The command Add to menu adds an appropriate item to the left menu of the administration section. The new menu item functions in the same way as the corresponding command Export of the form Export setup.

Agents

Agents are PHP functions which are run periodically at a given interval. Every time a page is requested, the system automatically checks for agents wanting execution and runs them if needed. It is not recommended to assign lengthy or large export jobs to agents. You should use the cron daemon for this purpose.

When you are setting an agent-aided export job, the system asks to provide the interval of execution. This is the period of time, in hours, at which the agent will run repeatedly starting from the current moment.

The cron daemon

The cron daemon works in the background and runs the assigned tasks at the specified time. Visitor traffic does not affect the task execution. The cron daemon allows running tasks both periodically and at the required time. The cron daemon is only available on UNIX-based servers.

When binding export jobs to cron, the system displays a request for both the period and time of execution, and the path to the PHP interpreter. If you provide the period of execution (in hours) , the export will execute automatically starting from the current moment. If you specify the exact time, the export will be performed every day at the time specified.

You can consult your hosting service provider for the path to the PHP interpreter.

The Bind to cron command adds a record to the configuration file (/bitrix/crontab/crontab.cfg) containing a list of current cron tasks. After you have changed the cron task list, you have to install the configuration file again. If the option Install automatically is enabled, the system will attempt to install it without your assistance. If you do not have enough permissions, such attempt may possibly fail. In this case, you have to connect to your site via the SSH or SSH2 or any other similar protocol supported by your provider for the shell remote operations and install the configuration file manually by typing the command:

crontab <full_path_to_crontab.cfg>

To view the list of currently installed tasks, run the command

crontab -l

List of currently installed tasks is also displayed at the bottom of the Export setup form (if you have enough permissions for the task list retrieval).

To remove all tasks assigned to cron, run the command

crontab -r

This will also remove any tasks which are not in the configuration file.

The cron job environment is the file: /bitrix/php_interface/include/catalog_export/cron_frame.php. Please ensure this file contains correct paths to PHP and site root.


Manual export to CSV (default profile) - Bitrix Site Manager - Content Management & Portal Solutions

Manual export to CSV (default profile)

Exporting data to the CSV format allows to set up the information interchange between your site and other sites or applications (for example, Microsoft Excel).

Perform the following operations to export a catalog to a CSV file.

  1. Select the Export action of the required profile. The export wizard will start.
  2. Select the information block for export and click Next.
  3. Set the file format properties: the field separator to be used for the file generation.
  4. Assign database fields to file fields. To do so, assign the required number of the CSV file field to the database field. If you do not want the field to export to a file, uncheck the corresponding Export option.
  5. Enter the CSV file name (with the full path relative to the site root). If the file does not exist, it will be created. If the file exists, it will be overwritten.
  6. Click Start export.


Manual export to Froogle (default profile) - Bitrix Site Manager - Content Management & Portal Solutions

Manual export to Froogle (default profile)

In this section

Export setup

Now there is several catalogs in the Internet accumulating information about the web shop stocks. Your promotion efforts will succeed if you post up-to-date and actual information about your stock to these catalogs.

A common requirement of such catalogs is that the stock information should be delivered in a special format. Bitrix Site Manager is capable of automising this task without developer's assistance. Currently the system implements the following export format:

  • CSV - common standard format;
  • Froogle - Google family catalog format;
  • Yandex - Yandex catalog format;
  • Yandex Simple - simplified Yandex format.

For easier exporting the frequently used catalog sections to a required format, each format allows to create user profiles containing information about the product groups to be exported.

If your site runs on a UNIX-based system, you can schedule the catalog export operation to be performed regularly. This can be achieved by binding the required export profile to the cron daemon.

Another way to automate export is to use agent functions. An agent is the PHP function which is run on a scheduled basis. When a page request occurs, the system checks for pending agents and runs them if required.

You can bind export profiles to cron or create the agent function on this page (e-Store -> Commercial catalog -> Data export).

Export setup

Field | Description
Action menu
 Clicking the action button of any export profile opens a menu allowing to:
  • Export - runs the export profile;
  • Add to menu - adds the profile to the left menu;
  • Add agent - creates an agent function for automated export using this profile;
  • Bind to cron - binds the profile to cron;
  • Delete - deletes the profile.
Name | The export format name.
File | The filename of the export format script.
Profile The profile used by the export format template.

The default profile always asks for the information block whose catalog is to be exported. With custom profiles, the export is performed automatically using the information block specified when creating the profile.
In menu | Specifies that the profile is added to the left menu for faster access.
In agents | Specifies that an agent exist which is used to export the catalog on a scheduled basis.
On cron | Specifies that the export profile is bound to cron.
Last run | The date and time when the last export operation occurred.

See also

Export explained

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Creating export profiles - Bitrix Site Manager - Content Management & Portal Solutions

Creating export profiles

To facilitate exporting the frequently used product groups to a certain format, export profiles can be created for each formats. An export profile contains information about the product groups to be exported and the selected information blocks.

To create an export profile, select the appropriate Add profile link of the required format here: e-Store -> Commercial catalog -> Data export.

Creating export profiles comes to setting the export parameters and thus is quite the same as the catalog export using default templates. The only thing that you need to provide is the name of the profile which will be shown in the list of profiles.

See Also

Manual export to CSV (default profile)
Manual export to Froogle (default profile)


Automated export to Yandex.Products - Bitrix Site Manager - Content Management & Portal Solutions

Automated export to Yandex.Products

The Commercial Catalog module features exporting product catalogs to an XML file appropriate for uploading to the Yandex.Products system.

To make a catalog the subject of export, you should enable export to an XML file in the module settings. An XML file will be generated at an interval specified in the field Interval of export to Yandex.Products. The generated file will be available at http://your_site/upload/yandex.php. The default folder folder upload can be changed in the field Default upload folder of the main module settings form.

The file http://your_site/upload/yandex.php can accept auxiliary parameters referer1 and referer2 which are used for links to products regarding the advertising campaigns. For example, the following URL

http://your_site/upload/yandex.php?referer1=wizard&referer2=soft

will generate an XML file with links to product description pages in the following format:

http://your_site/catalog/detail.php?ID=8192&r1=wizard&r2=soft

If the parameter referer1 is omitted, it is set to yandext. For example:

http://your_site/catalog/detail.php?ID=8192&r1=yandext&r2=


Export templates (for developers) - Bitrix Site Manager - Content Management & Portal Solutions

Export templates (for developers)

The information in this topic is supplementary to the description of export highlighted in Export explained and is intended for use by developers.

Export templates

Templates must be located in /bitrix/php_interface/include/catalog_export/. The preset templates call the existing scripts only. Custom templates must contain all the code required for the export. The system considers all files in this folder ending with _run.php as templates. If the folder contains a file with the same name but ending with _setup.php the system considers this file as the export wizard for the corresponding export template.

If the export template contains the tag <title> (even if in PHP comments), the inner text of this tag is treated as the export template name. Otherwise, the name of the template is taken after the file name.

You can add any number of templates to the folder /bitrix/php_interface/include/catalog_export/.

Export template

An export template is a common PHP scripts without any data input. This script can use all standard variables and those specified in the export wizard.

The export template can assign a text value to the variable $strExportErrorMessage containing the description of errors occurred during export. In this case, the system will consider export unsuccessful and display the contents of $strExportErrorMessage.

If the system detects the variable $SETUP_FILE_NAME accessible, the system will treat this name as the path to file containing the exported data. This path may be either relative or absolute. The system will display the full path name of this file.

Example of the simplest export template

<?
// <title>Simplest</title>
// Print the name of the selected information blocks
$strName = "";

// The variable $IBLOCK_ID must be set by either export wizard
// or taken from profile
// The variable $SETUP_FILE_NAME must be set by either export wizard
// or taken from profile

$IBLOCK_ID = IntVal($IBLOCK_ID);
// Catalog and iblock modules had been connected
$db_res = CIBlock::GetList(Array(), Array("ID"=>IntVal($IBLOCK_ID)));
if ($ar_res = $db_res->Fetch())
{
    $strName = $ar_res["NAME"];
}

if (strlen($strName)>0)
{
    if ($fp = @fopen($_SERVER["DOCUMENT_ROOT"].$SETUP_FILE_NAME, 'wb'))
    {
        @fwrite($fp, $strName);
        @fclose($fp);
    }
    else
    {
        $strExportErrorMessage = "Error opening data file for writing";
    }
}
else
{
    $strExportErrorMessage = "IBlock not found";
}
?>

Export wizard

Export wizard aims to provide additional export parameters (choosing catalogs and groups for export, specifying the path to a data file etc.). If an export template does not require extra parameters, export wizard is optional.

An export wizard may have multiple steps. In this case, you should use the variable $STEP which contains the current wizard step. When passing to the next step, you have to increment its value by 1.

The last step must set the variable $FINITE to True. The system treats this flag as the indicator to finish the export wizard and passes control over to an export template or saves a profile.

When the export wizard terminates, it must set the variable $SETUP_FIELDS_LIST. This variable contains a list of names of variables that the wizard has set. Names must be separated with commas.

If the final action of the wizard is the export profile creation (i.e. $ACTION contains a value of EXPORT_SETUP), the variable $SETUP_PROFILE_NAME must be set to the name of the profile to be created.

You should also set the variable $SETUP_FILE_NAME to the name of a data file. In this case, the system will automatically prompt a user with the data file name.

Export wizard example

<?
$strMyError = "";

if ($STEP>1)
{
    $IBLOCK_ID = IntVal($IBLOCK_ID);
    if ($IBLOCK_ID<=0)
    {
        $strMyError .= "Information block not selected.<br>";
    }

    if (strlen($SETUP_FILE_NAME)<=0)
        $strMyError .= "Data file not specified.<br>";

    if ($ACTION=="EXPORT_SETUP" && strlen($SETUP_PROFILE_NAME)<=0)
        $strMyError .= "Profile name not specified<br>";

    if (strlen($strMyError)>0)
    {
        $STEP = 1;
    }
}

echo ShowError($strMyError);

if ($STEP==1)
{
    ?>
    <form method="post" action="<?echo $APPLICATION->GetCurPage() ?>">
    Please select the information block:
    <select name="IBLOCK_ID">
    <?
        $db_res = CIBlock::GetList(Array("iblock_type"=>"asc",
                                         "name"=>"asc"));
        while ($res = $db_res->Fetch())
        {
    ?>
        <option value="<?echo $res["ID"] ?>"
         <?if (IntVal($res["ID"])==$IBLOCK_ID) echo " selected";?>>
        <?echo $res["NAME"];?>
        </option>
    <?
        }
    ?>
    </select><br>

    Please enter the data file name:
    <input
     type="text"
     name="SETUP_FILE_NAME"
     value="<?echo (strlen($SETUP_FILE_NAME)>0) ?
                    htmlspecialchars($SETUP_FILE_NAME) :
                    "/upload/file.csv" ?>"
     size="50">
    <br>

    <?if ($ACTION=="EXPORT_SETUP"):?>
        Profile name:
        <input type="text"
         name="SETUP_PROFILE_NAME"
         value="<?echo htmlspecialchars($SETUP_PROFILE_NAME)?>"
         size="30">
        <br>
    <?endif;?>

    <?//The following variables MUST be set?>
    <input type="hidden" name="lang" value="<?echo $lang ?>">
    <input type="hidden" name="ACT_FILE"
     value="<?echo htmlspecialchars($_REQUEST["ACT_FILE"]) ?>">
    <input type="hidden" name="ACTION" value="<?echo $ACTION ?>">
    <input type="hidden" name="STEP" value="<?echo $STEP + 1 ?>">
    <input type="hidden" name="SETUP_FIELDS_LIST"
     value="IBLOCK_ID,SETUP_FILE_NAME">

    <input type="submit"
     value="<?echo ($ACTION=="EXPORT")?"Export":"Save";?>">
    </form>
    <?
    }
    elseif ($STEP==2)
{
  //We want only one step; pass the control
  $FINITE = True;
}
?>


Import setup

In this section

  • Context bar
  • List of import profiles
    •

    The Import setup form is used to manage import profiles which you can use to quickly import data in your catalog.

    Context bar

    Button | Description
Add profile | Opens a form in which you can create a new profile.

    List of import profiles

    Field | Description
    Action menu
             Clicking the action button of any profile opens a menu allowing to:
    • Import - runs the profile;
    • Add to menu - adds the profile to the left menu;
    • Add agent - creates an agent function for automated import using this profile;
    • Bind to cron - binds the profile to cron;
    • Delete - deletes the profile.
    Name | The export format name.
    Profile The profile used by the import template.

    The default profile always asks for the import settings. With custom profiles, the import is performed automatically using the information block specified when creating the profile.
    In menu | Specifies that the profile is added to the left menu for faster access.
    In agents | Specifies that an agent exist which is used to import the catalog on a scheduled basis.
    On cron | Specifies that the import profile is bound to cron.
    Last run | The date and time when the last import operation occurred.


Importing CSV files - Bitrix Site Manager - Content Management & Portal Solutions

Importing CSV files

In this section

  • Import preconditions
  • Importing a catalog
  • Example of import file
    •

    Import preconditions

    The system provides for populating and modifying the catalog through the use of external CSV files (comma-separated values). Values in CSV files can have any separators in it. This form is user to upload CSV files to the site and fill the catalog with the product information.

    Since CSV files does not maintain information on the catalog structure and product properties, it is essential that you create the catalog structure before you start uploading your CSV file.

    Perform the following operations to create the catalog structure.

    1. Create and customize an appropriate information block (if you have not created it yet).
    2. Create all the required properties in the information block.
    3. Convert the information block to a catalog (see Commercial Catalog).
    4. Upload product pictures to the site (if you intend to use images).

    Importing a catalog

    The following steps disclose the import wizard operations.

    Step 1
    1. Open this form (e-Store -> Commercial catalog -> Data import -> Import CSV (new)).
    2. Click Browse... to locate a CSV file and set the field Data file from local computer if a file is stored on your local disk.
      If the data file is stored on your site, find it in the folder tree.
      If your local data file has large size, it is recommended to upload it via the FTP protocol before you proceed.
    3. Select the information block in which you will load the information.
    4. If you have created an import scheme once, you can select one. In this case, all the subsequent steps are omitted and the import starts immediately.

      Important!
      The scheme must be fully compliant with the imported file. Otherwise, the import result is unpredictable.

    5. Click Next to go to the second step.
      If you have selected the import scheme, the import procedure will start immediately.
    Step 2
    1. Select the appropriate CSV file format: with separators - fields are separated with a special symbol (e.g. a comma or a space) or fixed field width. Depending on your choice, you will have to customize the corresponding settings:
      • if you have chosen with separators, set the Field separator to the one used in your file;
      • if you have chosen fixed field width, specify ordinal numbers of the separating columns in the field Separator marks.
    2. If the first row in a file contains names of fields, check the box First row contains field names. If you check this option but the file's first row contains data instead of names, the first row will be processed incorrectly.
    3. Click Next to go to the next step.
    Step 3
    1. Assign file fields to database records. Order of fields in a file may differ from that in the catalog database. This is why it is essential to assign fields to records correctly.

      If a field is the grouping node, assign it a value of Group of level X.

      The values Unique identifier (B_IBLOCK_ELEMENT.XML_ID) and Name (B_IBLOCK_ELEMENT.NAME) are mandatory, you must assign any one of them. These fields are used to match products in a file and products in the database.

      Important!
      Please ensure that fields are matched correctly. Otherwise, the import result is unpredictable.

    2. If you are loading products with pictures, please upload pictures to the site via the FTP beforehand. Specify the path to images in the corresponding field.
    3. Instruct the system what to do with products currently in the database but absent from the imported CSV file:
      • choose remove to totally replace products in the catalog with those in a file;
      • choose deactivate to just hide products from visitors;
      • choose leave to add data from file to the database.
    4. If you plan to import similar CSV files on the regular basis, you can save the import scheme and use it with subsequent import operations.

      Important!
      The stored scheme can only be applied to files with the same structure. Otherwise, the import result is unpredictable.

    5. Click Load data to start importing.

    Example of a correct CSV file

    ID;Name;Qty;Battery_Prop;Group;Sale from;to;Base price;Curr;Retail;Curr
295;Siemens S55;10;90;Li-Ion;Siemens;1;10;160.00;USD;251.20;USD;N
295;Siemens S55;10;90;Li-Ion; Siemens;11;20;150.00;USD;235.50;USD;N
295;Siemens S55;10;90;Li-Ion;Siemens;21;;140.00;USD;219.80;USD;N
297;Siemens S46;2;680;Li-Ion;Siemens;1;10;85.00;USD;100.73;USD;N
297;Siemens S46;2;680;Li-Ion;Siemens;11;20;80.00;USD;94.80;USD;N
297;Siemens S46; 2;680;Li-Ion;Siemens;21;;75.00;RUR;88.88;RUR;N
325;Siemens U15;5;720;Li-Pol; Siemens;1;10;310.00;USD;367.35;USD;N
325;Siemens U15;5;720;Li-Pol;Siemens;11;20;290.00;USD;343.65;USD;N
325;Siemens U15;5;720;Li-Pol;Siemens;21;;270.00; USD;310; USD;N


How to import a CSV file

The catalogs can be created and filled with information by importing data from external CSV files. You can import CSV files in the Import CSV (new) form.

Since CSV files do not bear information regarding the catalog structure and peculiarities of its elements, you will need to perform the following actions prior to loading the data.

  1. Create and set up an information block, if required.
  2. Create all the required properties in the information block.
  3. Convert the information block to a catalog (see Commercial catalog settings).
  4. If needed, upload images used by the catalog to the site.

Do the following to create a catalog from a CSV file.

  1. Open the Import CSV (new) form: e-Store -> Commercial catalog -> Data import -> Import CSV (new) (or open Data import and click Add profile).
  2. If you import a CSV file from your computer, click Browse and select the file.

    If the data file size is large, a better solution is to upload it to your site via the FTP. Then, select the file by clicking Choose beside the data file from the site field.

  3. Select an information block in which the information is to be imported.
  4. Click Next.

  5. Choose the appropriate CSV format (delimited with a special symbol or fixed width field).
  6. For the delimited format, specify the correct separator in the Field separator field. For the fixed width field format, specify the numbers of columns which are the field separators.
  7. If your CSV file's first row contains field names, check the First row contains field names option.
  8. Click Next.
  9. Assign file fields to database fields. You must select at least one of the values: B_IBLOCK_ELEMENT.XML_ID or B_IBLOCK_ELEMENT.NAME. These fields are used to match file fields to database fields.

    Important!
    Ensure that the field correspondence is set up correctly. Otherwise, importing may lead to unpredictable results.

  10. To import elements containing images, upload images to any site folder via FTP prior to importing the CSV file. Then, specify the path to the folder in the Path to images field.
  11. Define how to treat elements which are currently in the database but not in the file (delete, deactivate or leave).
  12. Click Load data.


Statistics - Bitrix Site Manager - Content Management & Portal Solutions

Statistics

The module of the statistics accumulation and display provides for:
  • collecting and analyzing all the main performance indices of the site,
  • gaining the impartial numeric statistics for further analysis,
  • tracking the effectiveness of the site traffic.

The Statistics module helps to:

  • track hits, sessions and visitors;
  • track visitors who adds the site to their Favorites list;
  • register all the referring sites;
  • record the search keywords of both external and built-in search engines;
  • analyze the popularity of the site sections and pages;
  • keep the daily visitor statistics while emphasizing the resident audience;
  • perform the on-line monitoring of the site visitors;
  • block or redirect a visitor and add it to the stop-list;
  • track sessions of any user within the visits;
  • view the visitor paths;
  • register events, both internal and external;
  • control the advertising campaign progress and generate detailed reports;
  • track pages that are indexed by the external search engines;
  • perform the automatic clean-up of the statistics database as prescribed in the module settings.


List of Terms - Bitrix Site Manager - Content Management & Portal Solutions

List of Terms

List of Terms
  • Hit
  • Session
  • Host
  • Visitor
  • Event
  • Referring page
  • Search phrase
  • Search engine
    •
  • Search engine hit
  • UserAgent
  • Stop list record
  • Advertising campaign
  • Entry point
  • Exit point
  • Site path
  • Site path section
    •
    Hit
    A hit is one download of a page. The following actions also result in generating a hit:
    • clicking a link and the consequent page loading;
    • page reload done with F5 or Ctrl+F5;
    • navigating to a erratic page (producing error 404).
    Session
    A session in the Bitrix Site Manager is interpreted as the PHP session. A session is opened at the time of the visit start and is terminated after the browser window is closed. Also, a new session is opened upon the user authorization (logging in) and is closed with the user session termination (logging out). Terms session and visit are identical. In other words, a session is a visit to the site.
    Host
    A host means the IP address of the site visitor. The Bitrix Site Manager implies various levels of uniqueness for hosts in different reports.

    The Statistics section displays the number of unique hosts (IP addresses) per day and the number of unique hosts for all the time of gathering the statistics (that is, since the module has been installed).

    Advertising campaigns considers the IP address uniqueness within one advertising campaign only. All visitors under the advertising campaign and their IP addresses are stored in a special table. A visitor or the corresponding IP address is unique within this table only. Most of the existing statistical systems imply that the maximum deviation between the number of hosts and visitors of 10%. The Bitrix Site Manager Statistics module offers the unexampled deviation level of 3%.
    Visitor
    A visitor is the unique ID attached to any browser and saved in a cookie (a file that may be stored locally on a client side containing information pertinent to a particular site).

    If a browser (or other web content retrieving software) does not accept or support inter-session or session cookies, a special method of the visitor identification is used instead. The specific visitor is recognized by applying a hash function (md5 ) to a range of environment variables peculiar to this very user: IP address, browser settings, provider settings and other parameters peculiar to this very user at the time of visit.
    To put this another way, a visitor is a browser or other software connected to a site.

    The Statistics module implies various levels of the visitor uniqueness.

    The Statistics summary subsection displays the number of unique visitors per day as well as the number of unique visitors for all the time of gathering the statistics (that is, since the module has been installed).

    Advertising campaigns uses the same uniqueness rules for visitors as applied to hosts, that is within one advertising campaign.
    In both cases,new visitors are visitors that hit the site for the first time.
    Event
    An event can be described as any action that occurs either inside or outside the site. The Statistics module gathers information on those events only that had been presumed and programmed by the web programmer originally (see the Events topic in the SDK help section). The following are the examples of events: file download, transfer to an external pay system, order payment, order cancellation, banner click, leaving the site using a link to some other resource on your site, jumping to some page of your site.
    Referring page
    A referring page or referring site is any web resource having pages with links to your site. If a visitor hits your site using the link on a page like that, the site and page address are stored in the Statistics module and from now on considered referring.
    Search phrase
    If a visitor enters the search phrase on some search engine, found your site in the search results and clicked on it, the visitor will navigate to your site. This is the case that the visitor hits your site using the search phrase . All visits with search phrases are tracked in the Statistics module and displayed in the Search keywords subsection. In addition to the search phrase, the system stores the referring site and page, which is in fact the address of the search engine page containing search results.
    Search engine
    A search engine is any search engine in the Internet. For example: Google, Altavista, Yahoo, etc. Any search engine has the following characteristics:
    • own UserAgent string identifying the search engine robot;
    • group of domains (addresses of sites available for search requests);
    • variable containing a search phrase.
    Search engine hit
    A search engine hit is the case of indexing a page. All search engines have a set of tools for indexing the Internet resources. The process of indexation is accomplished by so-called search robots. Each robot is uniquely identified by its UserAgent. When the robot tries to index a page on your site, it sends a request to a web server and then loads the HTML code of the page and analyzes its contents. The Statistics module records such page downloads as the search engine hit . The search robots are distinguished by their UserAgent's.
    UserAgent
    A UserAgent is in fact the contents of the HTTP field UserAgent . The field is provided by the software communicating with a web server. Examples of such software are web browsers, download managers, offline browsers, search robots, etc. The software uses this field to identify itself during the communication. Please note that the contents of this field can be easily changed in many cases, many applications provide interface for doing it (for example, download manager FlashGet).
    Sample UserAgent strings

    NetCaptor web browser:

    Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; NetCaptor 7.0.2 Final; .NET CLR 1.0.3705)

    ReGet download manager:

    ReGet SE version 1.3.1*
    Stop list record
    Stop list is a set of parameters used to filter out visitors and apply the prescribed action: redirect, show a message, fail to provide the site content, etc.
    Advertising campaign
    The Statistics module provides the mechanism to register certain threads of the site visitors. Such threads can be identified by a range of characteristic:
    • One or two parameters in the link to your site:referer1 and referer2. The following is an example of such a link: http://www.bitrixsoft.com/?referer1=bsm&referer2=doc.
    • Search engines that forward the visitors to the site.
    • Wildcards of any referring page(s).
    • Wildcards of any pages on your site that the visitors open.
    The system records the following parameters for each of the visitor threads:
    • Sessions
    • Hits
    • Visitors
    • New visitors
    • Visitors who added the site to Favorites
    • All events initiated by the advertising campaign visitors.
    The advertising campaign reports show two indices for these parameters:
    • Direct hit under an advertising campaign
    • On-return hit under an advertising campaign.
    A direct hit under an advertising campaign is the session opened when a visitor is identified as the advertising campaign visitor. That is, if you click on the linkhttp://www.bitrix.ru/?referer1=bsm&referer2=doc, a session will open upon your visit and you will be identified as the visitor under advertising campaignr1:bsm; r2:doc. You are treated as the direct-hit visitor under the advertising campaign as long as the session is open.

    A return under an advertising campaign is the consecutive session opened for a visitor after they have previously maid a direct-hit visit under this advertising campaign. That is, if you have done a direct hit under an advertising campaign and no attempts has been made later to enter the site under other advertising campaigns, all consecutive visits will be treated as returns under the advertising campaign of the direct visit.
    Entry point
    If you have just opened the browser window and typed any address within your site, this address will be considered the entry point to the site. In other words, an entry point is a first hit in a session.
    Exit point
    Generally, when you enter the site you view one or more pages. The last page that you viewed is the exit point. In other words, an exit point is the last page in a session.
    Site path
    A site path is a set of one or more pages that the visitor was consequently opening using the links on these pages. A path may branch thus making up several paths if a visitor opens more than one page from the source page. The Microsoft ®Internet Explorer allows doing so by selecting the command Open in a New Window in the context menu or by holding the Shift key down while clicking on links.
    Site path section
    The Statistics module considers a site path section is a set of pages which consists of the first page and an arbitrary number of the consequent pages of the path.
    Example

    You enter the site to a page a, click on the link to a page b to open it, and then click on the link to a page c. So, you made a single site path consisting of the three sections:
    page a;
    page a -> page b ;
    page a -> page b -> page c .
    But if you, holding the Shift key, open pages d and e from the page c, both in new windows, you will make two paths. Both paths will consist of the four sections, and the first three sections in these paths will be identical.


Statistics summary - Bitrix Site Manager - Content Management & Portal Solutions

Statistics summary

In this topic

  • Traffic
  • Advertising campaigns
  • Event types
  • Referring sites
  • Search keywords
  • Site indexing

    • This page displays the summary of the site statistics.

    The filter allows to set the period of time to display the statistics for. After the filter is activated, all tables except that of advertising campaigns will show the additional column containing information for the specified period only. All values in the advertising campaign table always reflect the specified period.

    Filter

    The filter can help you quickly obtain information for the required period of time. After the filter is activated, all tables except Advertising campaigns will contain extra column showing data for the specified period. The Advertising campaigns report will show values for the specified period.

    Parameter | Description
Period | This parameter is used to define the range of dates for which the information is to be displayed.
Site | The site whose statistics is required.

    Context bar

    Button | Description
Site traffic graphs | Opens a form displaying the traffic graphs.

    Traffic

    Overall traffic | Today | Yesterday | 2 days before | Total
Hits | [1] | [2] | [3] | [4]
Hosts | [5] | [6] | [7] | [8]
Sessions | [9] | [10] | [11] | [12]
Events | [13] | [14] | [15] | [16]
Visitors
Total | [17] | [18] | [19] | [20]
New | [21] | [22] | [23] |
Added to favorites | [24] | [25] | [26] | [27]
Online | [28] |  |  |
    Legend
    1. Number of today's hits.
    2. Number of yesterday's hits.
    3. Number of hits for day before yesterday.
    4. Total number of registered hits.
    5. Number of today's unique IP addresses.
    6. Number of the yesterday's unique IP addresses.
    7. Number of unique IP addresses for the day before yesterday.
    8. Total number of unique IP addresses.
    9. Number of today's sessions.
    10. Number of the yesterday's sessions.
    11. Number of sessions for the day before yesterday.
    12. Total number of sessions.
    13. Number of today's events.
    14. Number of the yesterday's events.
    15. Number of events for the day before yesterday.
    16. Total number of events.
    17. Number of today's visitors.
    18. Number of the yesterday's visitors.
    19. Number of visitors for the day before yesterday.
    20. Total number of visitors.
    21. Number of the today's first-time visitors.
    22. Number of the yesterday's first-time visitors.
    23. Number of the first-time visitors for the day before yesterday.
    24. Number of today's visitors who added the site to their Favorites list.
    25. Number of yesterday's visitors who added the site to their Favorites list.
    26. Number of visitors who added the site to their Favorites list, for the day before yesterday.
    27. Total number of visitors who added the site to their Favorites list.
    28. Visitors currently on the site.

    Advertising campaigns (Top 10)

    Advertising campaign | Today | Yesterday | 2 days before | Total
[1] | [2] | [3] | [4] | [5]
Total | [6] | [7] | [8] | [9]
    1. Name of the advertising campaign.
    2. Number of the today's direct-hit sessions.
    3. Number of the yesterday's direct-hit sessions.
    4. Number of direct-hit sessions for the day before yesterday.
    5. Total number of direct-hit sessions made during the advertising campaign.
    6. Total number of today's sessions of all advertising campaigns.
    7. Total number of the yesterday's sessions of all advertising campaigns.
    8. Total number of sessions of all advertising campaigns, for the day before yesterday.
    9. Total number of all sessions of all advertising campaigns.

    Event types (Top 10)

    This report displays events occurred today, yesterday or 2 days before. An event is a click on a link containing parameters event1 and event2. The first column contains names of events in the form event1 / event2.

    Name | Today | Yesterday | 2 days before | Total
[1] | [2] | [3] | [4] | [5]
Total | [6] | [7] | [8] | [9]
    1. Name of the event type.
    2. Number of today's events of this type.
    3. Number of the yesterday's events of the this type.
    4. Number of events of this type occurred 2 days before.
    5. Total number of events of this type.
    6. Total number of today's events for the present day.
    7. Total number of the yesterday's events.
    8. Total number of events occurred 2 days before.
    9. Total number of all events.

    Referring sites (Top 10)

    Site | Today | Yesterday | 2 days before | Total
[1] | [2] | [3] | [4] | [5]
Total | [6] | [7] | [8] | [9]
    1. A referring site.
    2. Number of today's visits from this site.
    3. Number of the yesterday's visits from this site.
    4. Number of visits from this site occurred 2 days before.
    5. Total number of visits from this referring site. The period for which the referring sites are kept can be configured in the module settings, parameter Days to keep referring domains.
    6. Number of all today's referrers.
    7. Number of all the yesterday's referrers.
    8. Number of all referred transfers occurred 2 days before.
    9. Total number of all referrers from this referring site.

    Search keywords (Top 10)

    Keyword | Today | Yesterday | 2 days before | Total
[1] | [2] | [3] | [4] | [5]
Total | [6] | [7] | [8] | [9]
    1. A search phrase.
    2. Number of today's visits with this search phrase.
    3. Number of the yesterday's visits with this search phrase.
    4. Number of visits with this search phrase occurred 2 days before.
    5. Total number of visits with this search phrase. The period for which the search phrases are kept can be configured in the module settings, parameter Days to keep the referring domains.
    6. Number of all today's visits with this search phrase.
    7. Number of all the yesterday's visits with this search phrase.
    8. Number of all visits with this search phrase occurred 2 days before.
    9. Total number of all visits with all search phrases.

    Site indexing (Top 10)

    SE | Today | Yesterday | 2 days before | Total
[1] | [2] | [3] | [4] | [5]
Total | [6] | [7] | [8] | [9]
    1. The name of the search engine (or agent that is treated as a search engine).
    2. Number of today's indexing hits.
    3. Number of the yesterday's indexing hits.
    4. Number of indexing hits occurred 2 days before.
    5. Total number of index hits.
    6. Total number of today's index hits from all search engines.
    7. Total number of yesterday's index hits from all search engines.
    8. Total number of index hits from all search engines occurred 2 days before.
    9. Total number of all index hits from all search engines.


Site traffic - Bitrix Site Manager - Content Management & Portal Solutions

Site traffic

This form displays the site traffic statistics including hits, hosts, sessions and events. Table report is empowered with the visual representation of the site traffic statistics.

Filter

The filter is used to select the type of information and the period to build the graph. After you click Report, the system draws the graph and mirrors the report in the table.

Parameter | Description
Period | This parameter is used to define the range of dates for which the information is to be displayed.
Site | The site whose statistics is required.
Graph will display | Groups of options that you can choose to be displayed on the graph.

Context bar

Button | Description
Grouped by... | Click this button to add a new mail processing rule. In the menu, select the type of rule to add.
Excel | Exports data from the table to the MS Excel format.

Site traffic graph

The graph displays data selected from the database according to the filter criteria.

Example of graph

Click on image to enlarge

Click on image to expand

Table

ID | Date | Day of week | Hits | Hosts | Sessions | Events | Total | New | Fav.
[1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | [10]
Selected: [11]
  1. The ID of the record in the statistics database.
  2. The date for which the information is displayed in the row.
  3. Day of week (Su - Mo).
  4. Number of hits for this day.
  5. Number of unique hosts hits for this day.
  6. Number of sessions for this day.
  7. Number of events for this day.
  8. Total number of visitors for this day.
  9. Number of new visitors for this day.
  10. Number of visitors who added the site to their Favorites list.
  11. Number of records selected from the database.


Sections and pages. Entrance and exit points - Bitrix Site Manager - Content Management & Portal Solutions

Sections and pages. Entrance and exit points

In this section

  • Filter
  • Context bar
  • Diagram
  • Report table
  • Example of the page (section) traffic graph
    •

    • Depending on the selection in the tree menu of the function access area, this form can display:

    • diagrams and reports on the traffic of sections and pages;
    • diagrams and reports on the entrance and exit points.

    Filter

    Parameter | Description
    Period | Period to display on the diagram.
    Page / Section* The expression to filter the displayed sections and files. Additionally, you can specify:
    • the site whose sections or pages are to be included in the diagram and report;
    • method to display false requests (error 404): with other pages, only false requests or all pages except false requests.
    View | Select the data to include in the diagram: site sections; site pages; sections and pages.
    Advertising campaign | Filter to include one or more advertising campaigns in the report.
    Data type for advertising campaigns If you select one or more advertising campaigns to filter the report, you can additionally specify the data type. You can build the graph for:
    • direct hits under advertising campaigns;
    • returns under advertising campaigns;
    • both direct hits and returns.

    * - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" beside the field. For strict searches using this field, mark the corresponding checkbox.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Excel | Exports data from the table to the MS Excel format.

    Diagram

    The following is the example of diagram with the legend:

    Click on image to enlarge

    Click on image to expand

    For each segment, the legend shows:

    • for traffic reports: percentage of a page or a section among other viewed pages and sections. For entrance/exit points reports: how often a page or a section was the entry or the exit point;
    • link (») to the corresponding page or section;
    • link (in the form of the page/section path) which opens a page/section traffic diagram, or a diagram of entrance/exit points;
    • number of hits according to the filter conditions.

    The following figure illustrates the diagram segment legend.

    Report table

    For the Pages and sections report, the table shows the number of hits. For the Entrance points (Exit points) report, the table shows the number of sessions.

    Action menu | Number | Section/page | Hits /sessions/ | Percent
[1] | [2] | [3] | [4] | [5]
Selected: [6]
    1. Clicking the action button opens a menu allowing to:
      • Traffic graph for this page - opens a page with the appropriate graph in a new window.
      • Links statistics of this page - displays a path report for this page.
    2. The record ordinal.
    3. The section (page) link and path.
    4. Number of unique hits (the Pages and sections report) or sessions (the Entrance points (Exit points) report) for the specified period.
    5. Percent of hits of this page (section), or percent of jumps from this page (section).
    Example of the page (section) traffic graph

    A window with this graph is opened when the Traffic graph for this page command is selected in the action menu of a section or page.

    Click on image to enlarge

    Click on image to expand
    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Site Paths - Bitrix Site Manager - Content Management & Portal Solutions

Site Paths

Depending on the selection in the tree menu of the function access area, this form can display full paths or path branches. You can also build a diagram of pages to which visitors went from any path branch.

Filter

Parameter | Description
Period | The period of time for which the data is to be rendered on the diagram.
Number of pages in the path | The diagram will only include paths with the number of pages within the specified range.
First page of the path* | Wildcard for the first page to include in the report. This field gives the most comprehensive results if applied to the full path diagram.
Any page of the path* | Wildcard for pages to include in the report. The wildcard will match any appropriate page name in each of the paths included in the report. This field gives the most comprehensive results if applied to the full path diagram.
Last page of the path* | Wildcard for the last page of each path to include in the report. The wildcard will match any appropriate last page name in each of the paths included in the report. This field gives the most comprehensive results if applied to the path section diagram.
Advertising campaigns | One or more advertising campaigns to be used as filtering criteria while generating the report.
Data type for advertising campaigns In case you have specified one or more advertising campaigns as a filter, you can select the following types of hit to additionally filter the report:
  • direct hit under an advertising campaign;
  • on-return hit under an advertising campaign;
  • both direct and on-return hits under an advertising campaign.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Start of the paths | If clicked, opens a report containing all pages and sections from which visitors started navigating through the site. Available after a path branch has been selected in the list of full paths.
Path steps / Full paths | Allows to choose the type of path to display.
Excel | Exports data from the table to the MS Excel format.

Path Diagram

 | Path branch / Page | Jumps | Percent
ordinal | [1] | [2] | [3]
Selected: [4] | Total: [5] |  |
  1. Link (») to the corresponding page; path pages or path branches. The link on a page opens a diagram with the path branch ending with this page.
  2. Number of jumps.
  3. Percentage of jumps.
  4. Number of paths selected to display.
  5. Total number of paths.


Visitor Attentiveness - Bitrix Site Manager - Content Management & Portal Solutions

Visitor attentiveness

Depending on the selection in the tree menu of the function access area, this form can display:

  • diagrams and graphs on the visitor session duration;
  • diagrams and graphs on the number of hits in visitor sessions.

The form displays the graph and the diagram for the specified period of time for the selected site.

Filter

Parameter | Description
Period | Period to display on the diagram.
Site | The site whose graph and diagram is to be displayed.

Click Set filter to activate the filter and build graphs. To display all information, click Cancel.

Example of the average session duration graph

Click on image to enlarge

Click on image to expand

Example of the session duration diagram

Click on image to enlarge

Click on image to expand
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Countries - Bitrix Site Manager - Content Management & Portal Solutions

Countries

Depending on the selection in the tree menu of the function access area, this form can display diagrams and graphs of:

  • country based sessions on a daily basis;
  • new visitors;
  • hits;
  • events.

The form displays the graph and the diagram of the chosen entities for the specified period, and the diagram for the entire period of statistics gathering.

Filter

Parameter | Description
Period | Select a period of time that a graph or a pie chart are to display.
Country | Select countries to include in the report. The first 20 countries are selected by default, being sorted by number of the new visitors in decreasing order.

Click Set filter to activate the filter and build graphs. To display all information, click Cancel.

Context bar

Button | Description
Data type | Opens a popup menu in which you can select the type of the data which will be displayed on a graph or a diagram: new visitors, sessions, hits, events.

Example of the graph

Click on image to enlarge

Click on image to expand

Example of the pie chart for the selected period

Click on image to enlarge

Click on image to expand

Example of the pie chart for the entire period of statistics gathering

Click on image to enlarge

Click on image to expand
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Advertising campaigns - Bitrix Site Manager - Content Management & Portal Solutions

Advertising campaigns

In this section

  • Filter
  • Context bar
  • Table
  • Details: about information campaigns
    •  This page outlines the information on the advertising campaigns.

    Filter

    Parameter | Description
Find | Allows to find advertising campaigns by their main parameters: ID, referer1 or referer2.
ID | Searches for an advertising campaign by its ID.
Referer1 / referer2* | Finds advertising campaigns by the identifiers: referer1 and referer2.
Duration (days) | Finds advertising campaigns whose duration lies within the specified period. Advertising campaign duration is the amount of time elapsed from the first hit till the last hit.
Sessions (total) | Finds advertising campaigns whose number of sessions lies within the specified range.
Visitors (total) | Finds advertising campaigns whose number of visitors lies within the specified range.
Period | If enabled, includes an additional column in the report containing information for the specified period.
Audience
Attentiveness | Specifies to find campaigns whose Attentiveness parameter lies within the specified range. The Attentiveness is the average of hits per session.
Visitors per day | Finds campaigns whose Visitors per day parameter lies within the specified range. Range of the Visitors per day values for matching. The Visitors per day is the average of visitors per day.
Financial
Costs | Range of the Costs values for matching. The Costs field allows storing the value spent for the advertising campaign.
Proceeds | Range of the Proceeds values for matching. The Proceeds field accumulates all the monies for each event within the advertising campaign. The field allows manual modification.
Profit | Range of the Profit values for matching. The value of the Profit field is calculated as Proceeds less Costs for each advertising campaign.
Efficiency (ROI) | Range of the Efficiency values. Efficiency, or ROI is calculated in the following way: (Profit / Costs) * 100%
Currency | The list allows to select the currency that the values will be displayed in.

    * - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add | Adds a new advertising campaign.
Grouping | Allows to group the information in the table by one of the advertising campaign identifiers: either referer1 or referer2.
Excel | Exports data from the table to the MS Excel format.

    Table

    Field | Description
    Checkbox column | Used to select advertising campaigns to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
            Clicking the action button of any advertising campaign opens a menu allowing to:
    • Advertising campaign analysis - opens a form containing the detailed information about the campaign dynamics: summary, graphs, profits, events etc.;
    • Modify - opens a form in which you can edit the required advertising campaign;
    • Reset - zeros the campaign counters: visitors, attentiveness, financial indices;
    • Delete - deletes the advertising campaign;
    The following items are only available if at least one event has occurred on the advertising campaign:
    • Sections - opens a form containing the report on sections and pages viewed by visitors who entered the site under this advertising campaign;
    • Paths - shows the report on paths traveled by visitors;
    • Dynamics - displays the advertising campaign daily dynamics (sessions, visitors etc.);
    • Graphs - opens the advertising campaign graphs form (displaying hits and events).
    ID | The advertising campaign ID.
    referer1 | The advertising campaign identifier - referer1.
    referer2 | The advertising campaign identifier - referer2.
    Start | The date the first hit was made under this adv. campaign.
    End | The date the last hit (direct or on-return) was made under this adv. campaign.
    Priority | The adv. campaign priority. This parameter is provided when creating the adv. campaign.
    Today's sessions | Number of direct-hit and on-return* sessions for today.
    Total sessions | Total number of direct-hit and on-return sessions.
    Total today's events | Number of direct-hit and on-return sessions for today.
    Total events | Number of events occurred during the period specified in the filter.
    Selected | Number of records (adv. campaigns) selected from the database.
    Checked | Number of marked records.

    * - A return under the advertising campaign implies situation when a visitor has made a direct hit under the advertising campaign and returned to the site some time later, provided that they did not make any direct hits under other advertising campaign.

    Details: about information campaigns

    An advertising campaign is a set of conditions allowing to sort out a portion of the site visitor thread. All conditions are equal in their strength. The following conditions are allowed.

    • The parameters referer1 and referer2 in the link to your site. An example of such a link is http://www.bitrixsoft.com/?referer1=bbc&referer2=news.
    • Search engines that provide visitors with links to browse your site.
    • Wildcards of referring pages
    • Wildcards of visitor-hit pages of your site

    The following algorithm is used to select the advertising campaign.

    1. Advertising campaigns are sorted out to match the visitor parameters.
    2. The advertising campaign with the highest priority is selected to apply. If the priorities of the selected campaigns are equal, the campaign with the highest ID is selected.

    In case a visitor with the parameters referer1 and referer2 is recognized and no advertising campaign matches these criteria, a new advertising campaign is created with the supplied referer1 and referer2 as the identifiers.


Advertising campaign analysis

  • Filter
  • Report tables
  • "Statistics" tab
  • "Graphics" tab
  • "Finance (ROI)" tab
  • "Events" tab
  • "Entrance points" tab
  • "Exit points" tab
  • "Popular" tab
  • "Path steps" tab
  • "Site paths" tab
    •

    • This form shows all information gathered by the system about the selected or all advertising campaigns (AC). The analysis form can be opened by clicking on the action menu button of the required AC and selecting the Advertising campaign analysis menu item (in the Advertising campaigns form).

    Filter

    Parameter | Description
Find | Allows to find advertising campaigns by their main parameters: ID, referer1 or referer2.
Period | Period of time for which the information is required. If any period is defined, the Statistics report contains the Period column.

    Important!
    Clicking Search displays information about AC chosen by providing the search criteria in the Find field (i.e. by the ID or referer1 / referer2). Clicking Cancel invalidates the filter, e.g. displays information about all AC's.

    Report tables

    Since the system selects and displays a huge amount of statistical information, the latter is grouped in logical categories and presented in the tabbed property sheet. The property pages (tabs) contain the information appropriate to their titles.

    "Statistics" tab

    This tab comprises two tables: one with quantitative figures, while the other shows relative figures.

    The table with quantitative figures has the following format.

     | Today | Yesterday | 2 days before | Period | Total
Sessions |  |  |  |  |
Visitors |  |  |  |  |
New visitors |  |  |  |  |
Added to favorites |  |  |  |  |
Hosts (unique IP addresses) |  |  |  |  |
Hits |  |  |  |  |

    The table rows contain values of the parameters indicated in the left column, each for the date denoted in the table head. A Period column is only present if the filter field Period is set. The last column indicates the total number of events for each parameter.

    Each cell of the columns (Today, Yesterday, 2 days before, Period, Total) is split in two. The first cell (in green) shows the direct-hit value of the parameter, while the other cell (in blue) contain the on-return value.

    A return under an advertising campaign is a session opened for a visitor after they have previously maid a direct hit visit under this advertising campaign provided that no attempts have been made to enter the site under other AC's.

    The table of relative figures:

    Analytical parameters
Visitors per day | Average visitors per day for the entire gathering of statistics.
Attentiveness | Average hits per session, direct and on return.
Intensity | Average number of events occurred on direct hit (or on return) to the total number of visitors under the AC.
New visitors | Ratio of new visitors to all visitors under the AC.
Returned | Percent of visitors returned to the site after the first visit under the AC.
    "Graphs" tab

    This tab shows two graphs for the selected AC: the traffic graph and the event graph, each on daily basis. Below each graph is a legend containing links which can be clicked to view the event types.

    Example of the traffic graph

    Click on image to enlarge

    Click on image to expand
    Example of the event graph

    Click on image to enlarge

    Click on image to expand
    "Finance (ROI)" tab

    This tab contains a table showing indications on the AC costs, profits and payback.

    Parameter | Description
Expenses | Amount of money spent for the AC.
Revenue | Total amount of all financial events occurred within this AC. This value can be entered manually in the AC settings.
Profit | Revenue less expenses.
ROI | Return on investment index (calculated as (profit / expenses) * 100%).
Cost per click | Ratio of expenses to the total of direct-hit sessions.
Cost per visitor | Ratio of expenses to the total of direct-hit visitors.
    "Events" tab
    "Entrance points" tab

    This tab displays the diagram and the report on entrance and exit points under the selected AC.

    Example of the diagram of entrance points

    Click on image to enlarge

    Click on image to expand

    For each segment, the legend shows:

    • how often a page or a section was the entry or the exit point;
    • link (») to the corresponding page or section;
    • link (in the form of the page/section path) which opens a diagram of entrance/exit points;
    • number of hits linked to the report of visitor hits..
    List of entrance points

    The table shows the count of sessions for each entrance point.

    Action menu | Ordinal | Section/Page | Sessions | Percent
[1] | [2] | [3] | [4] | [5]
Selected: [6]
    1. If clicked, opens a popup menu containing the following commands:
      • Traffic graph - opens (in a new window) a page with the corresponding graph.
      • Click statistics - views a report of clicks only from this page.
    2. The record ordinal.
    3. The link and path to the section (page).
    4. Number of unique sessions for the period specified for the selected AC.
    5. Percent of visits/clicks to/from this page or section.
    6. Number of records selected from the database.
    "Exit points" tab

    The report on this tab is similar to the report of entrance points, but shows information about pages and sections which were viewed by visitors who came under the selected AC before they left the site.

    "Popular" tab

    This tab is also similar to the report of entrance points, but contains information about pages and sections which were the most popular among visitors who came under the selected AC. However, since the report is designed to analyse pageviews (i.e. hits), its values are the number of hits rather than sessions.

    "Path branches" tab

    This tab contains a report of the path branches.

     | Path branch / Page | Clicks | Percent
path ordinal | [1] | [2] | [3]
Selected: [4] | Total: [5] |
    1. The link (») to the page; a set of consecutive pages or branches of the path. The link on the page name opens the diagram of the path branch ending with this page.
    2. Absolute value of clicks.
    3. Relative value of clicks.
    4. Number of paths selected from the database.
    5. Total number of paths.
    "Site paths" tab

    This tab is similar to the report of entrance points, but displays information about each step in each path traveled by the site visitors. Click on a page name to view the subsequent step in the path.


Advertising campaign graphs - Bitrix Site Manager - Content Management & Portal Solutions

Advertising campaign graphs

This form displays graphs based on the data collected within the advertising campaign. You can open this form by selecting the Graphs item of the action menu in the list of advertising campaigns:

or by clicking on the Advertising campaign graphs link (Graphs tab of the Advertising campaign analysis form).

Filter

Parameter | Description
Period | Period of time to display the graph.
Show | Events to be displayed on the graph. The Add button opens a window in which you can select more events to be displayed in the list. The Delete button removes the selected events from the list.

Click Set filter to activate the filter and build graphs. To display all information, click Cancel.

Context bar

Button | Description
List of advertising campaigns | Clicking this button opens the advertising campaign report.
Dynamics of advertising campaign | Opens the advertising campaign dynamics report (number of hits, sessions etc.)
Excel | Exports data from the table to the MS Excel format.

Example of the advertising campaign popularity graph

Click on image to enlarge

Click on image to expand

Example of the advertising campaign event graph

Click on image to enlarge

Click on image to expand
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Advertising campaign dynamics - Bitrix Site Manager - Content Management & Portal Solutions

Advertising campaign dynamics

This page displays figures of the daily dynamics of the advertising campaign.

  • number of sessions;
  • number of visitors;
  • number of visitors who added the site to their Favorites list;
  • number of hosts (unique IP addresses);
  • number of hits (page loads);
  • events (user messages, purchases etc.)

Filter

Parameter | Description
Period | Period of time for which the events are required.

Click Set filter to activate the filter and view the report. To display all information, click Cancel.

Context bar

Button | Description
List of advertising campaigns | Clicking this button opens the advertising campaign report.
Advertising campaign graphs | Displays the advertising campaign graphs.
Excel | Exports data from the table to the MS Excel format.

Report table

 |  | Sessions |  | Visitors |  |  | Fav. |  | Hosts |  | Hits |  | Events
Action menu | Date | DIR | RET | DIR | RET | NEW | DIR | RET | DIR | RET | DIR | RET
 | Total |  |  |  |  |  |  |  |  |  |  |  |

Each table row contains the dynamics figures for a certain date. The table columns are organized in the following way.

  • First column (Action menu) contains buttons [image] which can be clicked to open the popup menu with the following commands:
    • Event list - opens a window enumerating events occurred on that date.
  • Second column (Date) indicates the date for which the information is given.
  • The following four columns (Sessions, Visitors, Favorites, Hosts, Hits) contain the dynamics values for the given date:
    • Sessions - number of sessions opened by visitors who came to the site under the advertising campaign (a session opens when a visitor enter the site, and closes when a browser window is closed. Also, a new session opens at the moment of successful authorisation, and closes when logging off).
    • Visitors - number of unique visitors.
    • Favorites - number of visitors who added the site to their Favorites lists.
    • Hosts - number of unique IP addresses.
    • Hits - number of page loads.
    Each of these figures has two values: number of direct-hit events (DIR, cells in green) and on return (RET, cells in blue). A direct hit under an advertising campaign is the session opened when a visitor is identified as the advertising campaign visitor. A return under an advertising campaign is the consecutive session opened for a visitor after the first direct-hit visit under the advertising campaign.

    Besides, the Visitors column shows the number of new visitors (NEW, cells in red). A new visitor is the one from whom the unique identifier issued to all visitors could not be acquired. Such visitors are admitted to enter the site for the first time.
  • The last column shows the number of the direct-hit events for the given date, and the on-return events (in brackets). Links on values open the list of events (the direct-hit or on-return events, respectively).


Advertising campaigns comparative analysis - Bitrix Site Manager - Content Management & Portal Solutions

Advertising campaigns comparative analysis

This form gives a pictorial display of several advertising campaign (AC) graphs in a single grid chart, which allows for easier comparison of their effectiveness.

Filter

Parameter | Description
Period | Period of time to display on the diagram.
Advertising campaign ID | Here you can select advertising campaigns for comparison. You can also set extra filters by the AC identifier and parameters referer1 / referer2.
referer1 | Specifies to find adv. campaigns by their referer1.
referer2 | The same, but by referer2.
Advertising campaigns | Select here AC's whose figures are to be mirrored on the graph. Press and hold Ctrl to select more than one AC's. The Add button opens a window in which you can select more AC's to be displayed in the list. The Delete button removes the selected AC's from the list.
Event ID | Filters AC's events by their identifiers.
event1 | Specifies to filter AC's events by their event1.
event2 | The same, but by event2.
Specify events of interest here | Select here additional events to be plotted on the graph. Press and hold Ctrl to select more than one event. The Add button opens a window in which you can select more event. The Delete button removes the selected event from the list.

Click Set filter to activate the filter and build graphs. To display all information, click Cancel.

Context bar

Button | Description
Compared parameter | Clicking this button opens a menu in which you can choose one of the many statistical parameters to show on the graph.
Excel | Exports data from the table to the MS Excel format.

The graph and the report

This area contains the graph and the table, both displaying the selected values for the specified period.


Creating and editing an advertising campaign - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing an advertising campaign

This form is used to create new and edit existing advertising campaigns (AC). You can get more information on advertising campaign here.

Context bar

Button | Description
List | Opens a list of AC's.
Add | Creates a new AC.
Reset | Zeros the current AC's counters: visitors, attentiveness, financial indices
Delete | Deletes the current AC.

"Properties" tab

Field | Description
Priority | The AC priority. The greater is the value, the higher is the priority.
Advertising campaign identifiers
referer1 | The AC identifier referer1. This value is passed in URL as &referer1=value.
referer2 | The same as above, but for referer2.
Additional conditions The AC functions (i.e. events are registered) if any of these conditions are true.
Navigated from | The referring page mask. If a visitor enters your site from any other site matching the mask, such entrance is registered as an event of this AC. The allows the following wildcards:“%” - 0 or more symbols; _ (underscore) – 1 any symbol.
Search engines | The search engines entrances from which are considered to be visits under this AC.
Navigated to | The target page mask. If a visitor enters your site by opening a page whose name matches the mask, such entrance is registered as an event of this AC. The allows the following wildcards:“%” - 0 or more symbols; _ (underscore) – 1 any symbol.

"More" tab

Field | Description
Finance
Cost | Amount of money spent for the AC. Values are stored and displayed in the base currency of the module. Values can be entered in any currency, but will be converted to the base currency when saving changes.
Revenue | Amount of money of all financial events occurred within the AC. The value is handled similarly to costs.
Additional settings
Mode of event display | Defines how the events of this AC are displayed in the list of AC's.
Description | The description of the AC.

Remember to click Save (saves changes and open the list of AC's) or Apply (applies changes and stays in the AC editing form) after you have made any changes.


Event types - Bitrix Site Manager - Content Management & Portal Solutions

Event types

This page displays a detailed view of the types of events.

An event type is the custom event defined by developer. Examples of event types are:

  • leaving the site for payment in the third-party pay system. This kind of event fires when a visitor clicks the Buy button that navigates to, for example, http://www.regnow.com;
  • file download. This kind of event fires when a visitor clicks the Download link or button;
  • the banner clicks on your site;
  • posting a comment;
  • walking through the sections of the site.

Virtually any action occurring on the site can be recorded as an event in the Statistics module. For more information, please refer to the Developer Guide, Events section.

In addition to recording local events within your site, you have an opportunity to record external events: for example, order payment or cancellation (see List of Events).

Filter

Parameter | Description
Find | Allows to find event types by their main parameters: ID, event1 or event2.
ID* | The ID of the event type in the database.
event1* | Event type identifier (event1).
event2* | Event type identifier (event2).
Name* | The name of the event type.
Description* | The description of the event type.
First | Period of time during which the first required event could have occurred.
Last | Period of time during which the last required event could have occurred.
Period | Specifies the period of time over which to display the events.
Total events | Instructs to display event types whose total count of events lies within the range specified in this field.
Amount | Shows event types whose total financial value lies within the range specified in this field.
Currency | Currency in which to display financial values.
Days to keep each event | Finds event types whose parameters Days to keep each event (if specified) matches the range specified in this field.
Days to keep the event type dynamics | Finds event types whose parameters Days to keep the event type dynamics (if specified) matches the range specified in this field.
Include in advertising report | Specifies to find event types whose flag Include in advertising report matches the value of this field.
Include in pie chart and graph by default | Same as the previous field, but used with the Include in pie chart by default flag.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Add | Creates a new event type.
Grouping | Defines how the information is to be grouped: by event1, event2 or without grouping. Grouping alters the table display: each row shows data for all event types with the equal event1 or event2.
Diagram | Opens a form containing the event type diagram.
Graphs | Shows event type graphs.
Excel | Exports data from the table to the MS Excel format.

Report table

Column | Description
Checkbox column | Used to select event types to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any event opens a menu allowing to:
  • Modify - opens a form in which you can edit the required event type;
  • Erase - zeros the event type counters;
  • Delete - deletes the event type;
  • Graphs - opens the event type graphs;
  • Dynamics - displays the event type dynamics;
  • Campaigns - opens the Advertising campaigns comparative analysis form with the filter set to this event type.
This column is only available in ungrouped tables.
ID The event type ID.

This column is only available in ungrouped tables.
Name The name of the event type.

This column is only available in ungrouped tables.
event1 The event type identifier event1.

This column is only available in ungrouped tables.
event2 The event type identifier event2.

This column is only available in ungrouped tables.
Today | Number of events of this type occurred today.
Yesterday | Number of events of this type occurred yesterday.
2 days before | Number of events of this type occurred 2 days before.
Total | Total number of events of this type.
First | The date when the first event of this type occurred.
Last | The date when the last event of this type occurred.


Creating and editing an event type - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing an event type

This form is used to create and edit event types. You can get more detailed information on event types here.

Context bar

Button | Description
List | Shows a list of all events.

"Event type" tab

Field | Description
event1 | The event type identifier - event1. The event type identifiers are two arbitrary string values allowing to identify the event type in the human readable form rather than a numerical ID, as well as to group different event types in reports.
event2 | The event type identifier - event2.
Include in advertising report | If unchecked, events of this type will not be displayed in the advertising campaign report.
Include in chart and graph | If unchecked, events of this type will not be shown in the default event type chart.
Days to keep each instance of this event type | Specifies how long events of this type will be kept. If the value is not set, the default module setting applies (parameter Days to keep each event).
Days to keep the event type dynamics | Specifies how long the dynamics for events of this type will be kept. If the value is not set, the default module setting applies (parameter Days to keep the event type dynamics).
Sorting | Sorting order for this event type.
Name | The short name of the event type.
Description | Input field allowing to provide a full text description of the event type.

Remember to click Save if you have made any changes; otherwise they will be lost.


Event type chart - Bitrix Site Manager - Content Management & Portal Solutions

Event type chart

This form shows a chart displaying the portion of a specific event type among all event types. The filter allows to set the period of time (range of dates) and events to display on the chart. You can get more detailed information on event types in this section.

Filter

Parameter | Description
Period | Period of time for which to display the diagram.
List of events | Events to be displayed on the diagram. The Add button opens a window in which you can select more event types to be displayed in the list. The Delete button removes the selected event types from the list.

Chart legend

Beside the diagram is the legend showing additional information.

  • Value in round brackets - count of events of the given type. Click this link to open a list of events whose filter is set to display the given event type and the period specified in the filter.
  • Value in square brackets - The event type ID. The link opens the list of event types whose filter is set to display the given event type.
  • Third value - The event type identifiers: event1 and event2. Clicking the link shows the form with the event type graph.

Example of the chart

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Event type graph - Bitrix Site Manager - Content Management & Portal Solutions

Event type graph

This form shows a graph displaying the number of events of different types on daily basis. You can get more detailed information on event types here.

Filter

Parameter | Description
Period | Period of time for which to display the diagram.
List of events | Events to be displayed on the graph. The Add button opens a window in which you can select more event types to be displayed in the list. The Delete button removes the selected event types from the list.

Context bar

Button Description
Type of graph Click to open a menu in which you can choose the desired type of graph:
  • Summary graph - one graph showing the sum of values of all event types.
  • Separate graphs - separate graphs for each event type.
Value to display Selects the desired parameter to plot:
  • Money - financial counters of events (if those exist);
  • Quantity - count of events .

Graph legend

Below the diagram is the legend showing additional information.

  • Value in square brackets - The event type ID. The link opens the list of event types whose filter is set to display the given event type.
  • Third value - The event type identifiers: event1 and event2. Clicking the link shows the event dynamics report for the given event type. The report filter is set to display the given event type and the period specified in the filter form with the event type graph.

Example of the graph

Click on image to enlarge

Click on image to expand
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Event type dynamics - Bitrix Site Manager - Content Management & Portal Solutions

Event type dynamics

This page displays the dynamics (quantity) of events of the given type. The filter allows to constrict the view range by setting the event type and the period.

Filter

Parameter | Description
Event type | The ID of the event type whose dynamics is to be displayed. The Choose button can be clicked to open a window in which you can select the desired event(s).
Period | Period of time for which to display the diagram.

Context bar

Button | Description
Graph | Shows the graph of events of the selected type.
Excel | Exports data from the table to the MS Excel format.

Table

Date | Count
The date for which the value is specified. | Number of events of the given type for the corresponding date.
Selected | Number of records selected from the database.
Total | Total number of events for the given period (or the total number of events).
Days | Number of days for which the report is rendered.


List of events - Bitrix Site Manager - Content Management & Portal Solutions

List of events

This page displays the detailed view on each event occurred within or outside the site.

Filter

Parameter | Description
Find | Allows to find events by their main parameters: advertising campaign ID, event1 or event2.
ID | The ID of the required event in the database.
Event type ID | The ID of the required event type in the database.
Event type name | The name of the required event type.
event1 / event2 | Finds events by their event type identifiers, event1 and event2, respectively
event3 | Finds events by their auxiliary parameter.
Date | Specifies the period of time over which to display the events.
Session ID | Specifies to find events occurred within a session with the specified ID.
Visitor ID | Specifies to find events by the ID of a visitor who initiated the event.
Country | Finds events made by visitors who came from the specified country.
Advertising campaign ID | The ID of an advertising campaign under which the required events occurred.
Show advertising campaign on-return events This field allows you to filter events which:
  • occurred at the time of a direct visit under an advertising campaign
  • ... on-return visit;
  • occurred without advertising campaign.
Hit ID | This field contains the ID of the hit which caused the required event to occur.
Referrer URL | Specifies the external page URL from which a visitor came to your site thereby initiating the required event.
Occurred at URL | Specifies the URL of a page of your site which a visitor entered thereby initiating the required event.
Redirected to URL | The page to which the visitor was redirected after the required event had occurred.
Amount | Range of values to filter the events according to their amount of money.
Currency | The currency in which the amount of money will be displayed.
Filter between-field logic | Defines how the filter works: whether all criteria must match, or at least one true condition is sufficient.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Add | Opens a form in which you can add a new event manually.
Excel | Exports data from the table to the MS Excel format.

Table

Column | Description
Checkbox column | Used to select events to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
ID | The event ID.
Type | The event type ID. The link opens a list of event types with the filter set to this event type.
event1 | The event type identifier - event1.
event2 | The event type identifier - event2.
Date | The date when the event occurred.
Session | The ID of a session during which the event occurred. The link opens a list of sessions with the filter set to this session.
Visitor | The ID of a visitor who initiated the event. The link opens a list of visitors with the filter set to this visitor.
Country | Country of the visitor who initiated the event.
Ad campaign | The ID of the advertising campaign (AC) under which the visitor initiated the event. If the ID contains asterisk (*), the event is the on-return event. Otherwise, this is the direct-hit event. The link opens a list of AC's with the filter set to this AC.
Hit | The ID of the hit on which the event occurred. The link opens a list of hits with the filter set to this hits.
Site | The site on which the event was fired.
Money | The financial value of the event. Printed in the base currency of the Statistics module, or in the currency specified in the filter.
Selected | Number of events selected form the database.
Checked | Number of marked events.
Amount of money | The sum of financial values of all events.
Total | Total number of registered events.


Adding events - Bitrix Site Manager - Content Management & Portal Solutions

Adding events

In this topic

  • Loading from file
  • Event table
  • Automated registration of events
    •

    This form allows you to add events occurred outside the scope of your site. Examples of such events are order payments, order cancellation, etc.

    Loading from file

    The page also offers facilities to upload a CSV file containing a list of events. The uploaded file should have the following format:

    "[1]","[2]","[3]","[4]","[5]","[6]","[7]", where:

    1. ID of the event type
    2. Auxiliary parameter "event3"
    3. Date. The date should be specified in the date format of the current language.
    4. Additional parameter in the following format:
      [site code].[session ID].[visitor ID].[country ID].[advertising
 campaign ID].[Y-return within advertising campaign; N-direct visit].
      The site code is defined in the settings of the Statistics module.
    5. Amount of money
    6. Three-character currency abbreviation (e.g. USD, RUR, EUR, etc.). The currency must have been defined in the Currency module. Otherwise, the value will not be converted to the base currency and the value will be assigned as is.
    7. Refund flag. If set to Y, then the value is kept back from the advertising campaign revenue. If set to N, then the value is added to the advertising campaign revenue.

    Please follow the below guidelines when creating a CSV file.

    • If any value is void, the separating comma is mandatory.
    • All of the values must be double quoted. If the value contains a double quote, it must be replaced with the two double quotes: " -> ""
    • Every new event must start from the new line.
    • Decimal point is used as the separator between the whole and fractional part of a money values.

    Standard CSV file example

    16,"file1.exe","10.12.2002 12:30","BITRIX_SM.10.5.RU.6.Y","250","USD"
16,"help_doc.chm","10.12.2002 12:30"
16,"www","BITRIX_SM.11.4.US.8.N","233.45"
16,"Bitrix: ""Site Manager""","BITRIX_SM.11.4.US.8.N","233.45","RUR","Y"

    Click the Load button to load the file in the form. The form is described below.

    Manual entry

    Another way to add events is to enter them manually.

    # | Event type ID | Event3 | Date | Additional parameter (site_code. session.visitor.country. advertising_campaign. return_flag) | Amount | Currency | Chargeback |
[1] | [2] [3] | [4] | [5] [6] | [7] | [8] | [9] | [10] | [11]
    1. Event number.
    2. Event type ID.
    3. Click this icon to select the type of event in a separate window.
    4. Auxiliary parameter event3 (for example, it may contain the order amount).
    5. Date of the event.
    6. Click this icon to display a calendar.
    7. Additional parameter.
    8. Sum of money under the event.
    9. Currency (this column is only displayed if the base currency had been specified in the module settings. The base currency can be set if only the Currency module is installed.)
    10. If checked, the Amount is subtracted from the advertising campaign profit. Otherwise, the advertising campaign profit becomes increased by the value of Amount.
    11. Click this icon to duplicate the current line.

    Automated registration of events

    When a visitor leaves the site, for example, for making an order, the link to the external pay system should contain a special template – #EVENT_GID#. Later, the script file redirect.php automatically substitutes this template with the compound identifier:

    [site code].[session ID].[visitor ID].[country ID].[advertising
 campaign ID].[Y-return within advertising campaign; N-direct visit].

    The below is an example of such a link:

    <a href="http://www.ritlabs.ru/redirect.php?event1=softkey_out&
 event2=thebat&event3=buy&
 goto=http://www.softkey.ru/catalog/basket.php?
 prodid=902&quantity=1&referer1=ritlabs_site&referer2=#EVENT_GID#">
Êóïèòü
</a>

    The above link is provided in the readable form for simplicity. The original link in the canonic format looks as follows:

    <a href="http://www.ritlabs.ru/redirect.php?event1=softkey_out&
 event2=thebat&event3=buy&
 goto=http%3A//www.softkey.ru/catalog/basket.php%3Fprodid%3D902%26quantity%3D1%26referer1%3Dritlabs_site%26referer2%3D%23EVENT_GID%23">
Buy
</a>

    The system HTML editor offers special features to insert such links.

    Most pay systems allow special parameters and return them in the order notification mail message. For example, the pay system www.softkey.ru accepts both referrer1 and referer2 parameters. As soon as you receive a message notifying you of the order, you should enroll this event in the statistics of your site.

    If you want the events to be enrolled automatically, you can do so by loading a PHP page. The full address of the page is constructed using the following formula.

    http://[your_site]/bitrix/admin/event_edit.php?

    USER_LOGIN=[login]&USER_PASSWORD=[password]&lang=[language]&
    Login=Y&TYPE=AUTH&AUTH_FORM=Y&

    ARR[]=[N]&LOAD_[N]=Y&EVENT_ID_[N]=[type_ID]&EVENT3_[N]=[EVENT3]&
    DATE_ENTER_[N]=[Date]&PARAM_[N]=[ÏÀÐÀÌÅÒÐ]]&MONEY_[N]=[amount]&
    CHARGEBACK_[N]=[refund_flag]&

    ARR[]=[N+1]]&LOAD_[N+1]=Y&EVENT_ID_[N+1]=[type_ID]&EVENT3_[N+1]=[EVENT3]&
    DATE_ENTER_[N+1]=[Date]&PARAM_[N+1]=[parameter]&MONEY_[N+1]=[amount]&
    CHARGEBACK_[N]=[refund_flag]&

...

    ARR[]=[M]&]&LOAD_[M]=Y&EVENT_ID_[M]=[type_ID]&EVENT3_[M]=[EVENT3]&
    DATE_ENTER_[M]=[Date]&PARAM_[M]=[parameter]&MONEY_[M]=[amount]&
    CHARGEBACK_[N]=[refund_flag]

&check_unique=Y&save=Y
    Legend
    [your_site]
    Address of your site.
    [login]
    Login of a user with write access to the Statistics module.
    [password]
    Password of the above described user.
    [language]
    Abbreviation of the language used to format the event date (for example, en).
    [N], [N+1]
    Ordinal number of the event to add.
    [M]
    Number of events to add.
    [type_ID]
    Type ID of the event to add.
    [EVENT3]
    Auxiliary event parameter.
    [Date]
    Date of the event in the of the specified language ([language] field).
    [parameter]

    Parameter in the following format:
    [site_code].[session].[visitor].[country].[advertising_campaign].[on-return_flag].

    [amount]
    Amount of money under this event
    [refund_flag]
    Refund flag. If set to "Y", then the value is kept back from the advertising campaign revenue. If set to "N", then the value is added to the advertising campaign revenue. The default value is "N".
    check_unique
    Set this flag to Y to check the uniqueness of the added events. Otherwise, the uniqueness check is not performed.

    Sample address

    http://www.bitrix.ru/bitrix/admin/event_edit.php?
       USER_LOGIN=admin&USER_PASSWORD=123456&lang=ru&Login=Y&
       TYPE=AUTH&AUTH_FORM=Y&ARR[]=1&LOAD_1=Y&EVENT_ID_1=35&
       EVENT3_1=250&DATE_ENTER_1=10.01.2003&PARAM_1=BITRIX_SM.10345.676.US.3.Y&
       ARR[]=2&LOAD_2=Y&EVENT_ID_2=35&EVENT3_2=340&DATE_ENTER_2=11.01.2003&
       PARAM_2= BITRIX_SM.10400.700.RU.5.N&MONEY_2=970.35&check_unique=Y&save=Y

    Warning!
    The example above is given in human-readable form. For the page lo load correctly, you need to encode the URL (for example, using the PHP function urlencode()).


Search keywords - Bitrix Site Manager - Content Management & Portal Solutions

Search keywords

This page displays information on search keywords and phrases used by visitors to find your site from external search engines (SE), and to find pages on your site using the internal search.

Filter

Parameter | Description
Search keyword | Specifies the mask of the search phrase to be found.
ID* | The ID of the required database record containing information on the search phrase.
Search engine* | Finds the required SE by its name or ID. Alternatively, you can select SE from the drop-down list of the registered search engines.
Date | The date the search phrase was enrolled in the database.
To* Specifies the mask of the page which a visitor entered as the result of the search query and the subsequent click. If applied to the internal search engine, this is the last page viewed according to the search results. Additionally, you can specify:
  • the site to which a visitor came;
  • method to display false requests (error 404): with other pages, only false requests or all pages except false requests.
Referrer ID* | Search by the ID of the referring sites.
Session ID* | Search by the ID of the session during which the phrase was enrolled in the database.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter and build graphs. To display all information, click Cancel.

Context bar

Button | Description
Excel | Exports data from the table to the MS Excel format.

Table (ungrouped or grouped by search phrase)

ID | Search keywords | Search engine | Date | To | Referrer | Session
[1] | [2] | [3] | [4] | [5] | [6] | [7]
Total: [8]
  1. The search keyword jump ID.
  2. The search phrase.
  3. The ID and name of the search engine. For the internal site search - <internal>. Link on the ID opens a list of search engines with the filter set to this search engine. Link on the name of the SE groups the current form by search phrases of this SE.
  4. The date the search phrase was added to the database.
  5. The site alias and the target page URL. Link on the site alias opens the site settings form. Link on the page URL opens this page for view.
  6. The ID in the table of the referring sites. Link on the ID opens a list of referring sites with the filter set to this sites.
  7. The ID of the session during which the search phrase was added to the database.
  8. Number of phrases selected from the database.

Table (grouped by search phrase)

 | Search keywords | Quantity |
[1] | [2] | [3] | [4]
 | Selected:[5]
  1. The search keyword ordinal.
  2. The search phrase. You can click it to add it to the filter.
  3. Count of the search phrase uses.
  4. Graph bar.
  5. Number of phrases selected from the database.
Example of the table

Table (grouped by search engine)

 | Search keywords | Quantity | Average hits |
[1] | [2] | [3] | [4] | [5]
 | Selected:[6]
  1. The record ordinal.
  2. The ID and name of the search engine. Link on the ID opens a list of search engines with the filter set to this search engine. Link on the name of the SE groups the current form by search phrases of this SE.
  3. Number and percent of visits from this SE.
  4. Average number of hits from this SE.
  5. Graph bar.
  6. Number of search engines selected from the database.
Example of the table
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Search engines - Bitrix Site Manager - Content Management & Portal Solutions

Search engines

This page contains information on how search engines crawl your site.

Filter

Parameter | Description
Name | The name of the required search engine.
ID | The ID of the required search engine in the database.
Active | Specifies to find only active, inactive or all search engines.
Save hits | Specifies to find only those search engines that have this flag enabled. The flag Save hits determines whether hits of this search engine are registered or not.
Include in the indexing pie chart by default | Tells to match only those search engines that have this flag turned on. This flag determines if the search engine is included in the chart or not.
Total hits | Finds search engines whose number of indexed pages lies within this range.
Last hit date | The date the required SE last indexed the site.
Period | Defines the time interval for which to display information.
UserAgent | The UserAgent of the sought search engine.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Add | Clicking this button opens a form in which you can add a new SE.
Diagram | Shows the site indexation chart.
Graphs | Shows the site indexation graph.
Excel | Exports data from the table to the MS Excel format.

Table

Column | Description
Checkbox column | Used to select SE's to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any SE opens a menu:
  • Graph - opens a form with the graph of site indexing by this SE;
  • Dynamics - shows the dynamics of site indexing by this SE (hits per each day);
  • Modify - edits the SE;
  • Delete - deletes the SE.
ID | The search engine ID.
Name | The name of the search engine. Link on the name opens a form with the graph of site indexing by this SE.
UserAgent | The UserAgent string of this SE.
Today | Number of today's indexations. | Link on the value displays the site indexing report for the corresponding date(s).
Yesterday | Number of yesterday's indexations.
2 days before | Number of indexations for the day before yesterday.
Period | Number of indexations for the period provided in the filter.
Total | Total number of indexations made by this SE.
Last hit | The date the site was indexed last time.
Selected | Number of SE's selected from the database.
Checked | Number of marked SE's.


Search engine diagram - Bitrix Site Manager - Content Management & Portal Solutions

Search engine diagram

This page displays a pie chart illustrating the part of each search engine (SE) in the overall SE traffic.

Filter

Parameter | Description
Period | Period of time to be rendered on the diagram.
Search engines | Specifies the SE's to be included in the diagram.

Click Set filter to activate the filter and build the diagram. To display all information, click Cancel.

Context bar

Button | Description
List | Clicking this button opens a list of search engines.
Graphs | Opens a form with the search engine graph.

Legend

Beside the diagram is the legend showing additional information.

  • Value in round brackets - count of hits of this SE. Click this link to open a list of hits whose filter is set to display the given SE and the period specified in the filter.
  • Value in square brackets - The ID of the SE. The link opens the list of SE's whose filter is set to display the given SE.
  • Third value - the name of the SE. The link opens the form with the graph of this SE.

Example of the diagram

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Search engine graph - Bitrix Site Manager - Content Management & Portal Solutions

Search engine graph

This page displays a graph showing how the search engines (SE) index your site, in terms of hits per day.

Filter

Parameter | Description
Period | Period of time to be rendered on the graph.
Search engines | Specifies the SE's whose data is to be plotted. In the drop-down list, you can choose the way the graph are created: draw the summary of al SE's, or draw each SE individually.

Click Set filter to activate the filter and build the graph.

Context bar

Button | Description
List | Clicking this button opens a list of search engines.
Graphs | Opens a form with the search engine chart.

Legend

Beside the diagram is the legend similar to that of the search engine chart.

Example of the chart

Click on image to enlarge

Click on image to expand
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Search engine hits - Bitrix Site Manager - Content Management & Portal Solutions

Search engine hits

This form displays pages indexed by external search engines (SE).

Filter

Parameter | Description
Search engine Specifies to find a search engine given its ID or name.
Alternatively, you can select one from the list.
ID | The ID of the database record containing the address of the indexed page.
Date | Range of dates for which the information is required.
Page The address of the indexed page.
Additionally, you can specify how to display false requests (error 404): with other requests, only false requests or all pages except false requests.
UserAgent | Finds the specific UserAgent. Corresponds to the HTTP header field UserAgent, which identifies a search engine.
IP address | Wildcard for the IP address field. It contains IP addresses of search engines at the time of indexing a page.
Filter between-field logic Defines how the search is performed:
  • "and" - display records satisfying all criteria;
  • "or" - display records satisfying at least one criteria.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Excel | Exports data from the table to the MS Excel format.

Table

ID | Date | Search engine | UserAgent | IP address | Page
[1] | [2] | [3] | [4] | [5] | [6]
Selected: [7]
  1. The ID of the indexed page.
  2. The date and time the page was indexed.
  3. The search engine.
  4. The UserAgent of the search engine.
  5. The SE IP address of at the moment of entering the site.
  6. The address of the indexed page.
  7. Number of pages selected from the database.


Search engine hits dynamics - Bitrix Site Manager - Content Management & Portal Solutions

Search engine dynamics

This page displays the search engine daily dynamics.

Filter

Parameter | Description
Search engine | Specifies the SE's whose data is required.
Period | Period of time to be rendered on the graph.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
List | Opens a list of search engines.
Graphs | Displays the search engine graph.
Excel | Exports data from the table to the MS Excel format.

Table

Date |  | Hits
[1] |  | [2]
Selected:[3] | Total days: [4] |
  1. The date the search engine hit occurred.
  2. Number of indexed pages (hits) for the specified date.
  3. Number of records (hits) selected from the database.
  4. Total number of pages indexed.


Creating and editing a search engine - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a search engine

This form is used to create new and edit existing search engines (SE). You can access this form by clicking Add in the list of search engines, or by clicking the Action menu button and selecting the Modify item:

Context bar

Button | Description
List | Opens a list of search engines.
Add | Creates a new search engine in this form.
Delete | Deletes the currently open SE.

"Properties" tab (SE parameters)

Field | Description
Active | This flag indicates that the search engine is active.
Check traffic limit | If the option is checked and traffic control is activated in the module settings, any traffic restrictions are removed from this search engine.
Save hits | This flag prescribes to store addresses of the indexed pages in the database.
Include in chart and graph | If checked, the search engine will be included in the SE diagram and graph by default.
Days to keep hits | Number of days to keep addresses of the indexed pages. If this value is not specified, the value from the Statistics module settings is used instead (parameter Days to keep search engine hits).
Days to keep dynamics | Number of days to keep the dynamics of site indexing for this search engine. If this value is not specified, the value from the Statistics module settings is used instead (parameter Days to keep search engine dynamics).
Name | The name of the search engine (e.g. Google)
UserAgent | The search engine UserAgent (e.g.: Googlebot/)
Domains
Domain | Search engine domain name without the www part (e.g. google.com, google.co.il, google.co.uk, search.yahoo.com, etc.)
Variable | Name of the variable that is used to pass the search phrase.

Domain variables

With the domain variables, the following rules apply.

For example, if we search for bitrix in Google, the URL containing the search engine parameters is the following:

http://www.google.com/search?hl=en&ie=UTF-8&q=bitrix

In this case, the parameter that holds the sought string is q, so we should set the variable name to q for google.com. In future, this variable will be used to parse the search phrases.

Possible case with the option Search in results is handled in the similar way. For example, we want to narrow the search criteria of the previous search with download. The URL in this case is

http://www.google.com/search?hl=en&lr=&ie=UTF-8&q=bitrix&
       as_q=download&btnG=Search%C2%A0within%C2%A0results.

In this case, the additional variable is as_q. So, we set the variables to q,as_q – note that they are separated them with comma. Further on, the search phrases will be displayed as bitrix / download, separated with slash while preserving their order.


Autodetect - Bitrix Site Manager - Content Management & Portal Solutions

Autodetect

This page helps to search for new UserAgent’s in the system statistics and classify them as a browser or a search engine.

Classifying a UserAgent as a browser means that from now on this UserAgent will be excluded from the search results on this page. All the site visitors entering the site with this UserAgent string will be treated as common visitors: they will have their own profiles, sessions, hits, advertising campaign clicks and events recorded.

Classifying a UserAgent as a search engine results in registering all hits with this UserAgent as the search crawler visit with the sole purpose to only index the site contents. Such hits will be treated as the search engine hits; the only records that will be created are the addresses of the indexed pages.

General recommendations

  • If the UserAgent is unfamiliar to you, first try to search for this UserAgent in the Internet before classifying it.
  • Pay special attention to the length and uniqueness of the search engine wildcard you are about to add. Otherwise, the wildcard may match browser and all visitors with this UserAgent will be recorded as search engines.
  • If the UserAgent contains occurrences of bot, robot or crawler, it is much likely a search engine robot (for example: Googlebot).
  • If the UserAgent is a downloader software, it should be treated as a browser, otherwise the file download events will not be recorded.
  • If the UserAgent is an offline browsing software, it should be treated as a browser.
  • If the UserAgent is a web content retrieving software, it should be treated as a browser.
  • If the UserAgent is undefined, the best choice is to not classify it.

Filter

Parameter | Description
UserAgent* | UserAgent of the site visitor
Only for today | Specifies whether to display UserAgent's detected today, or all.
Sessions | Filters records by the number of sessions (number of visits with the specific UserAgent).

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Table

Checkbox column | UserAgent | Sessions | Mask | Search engine | Browser
[1] | [2] | [3] | [4] | [5] | [6]
Selected:[7] | Checked: [8] |
  1. Select here UserAgent's to which an action is to be applied.
  2. The unknown UserAgent.
  3. Number of sessions with this UserAgent.
  4. Mask for the search engine or the browser to be added. The mask allows the following wildcards: % - 0 or more characters; _ (underscore) – any one character.
  5. Select to classify the UserAgent as a search engine.
  6. Select to classify the UserAgent as a browser.
  7. Number of found unknown UserAgent’s.
  8. Number of UserAgent's marked in [1] to be added.


Referring sites - Bitrix Site Manager - Content Management & Portal Solutions

Referring sites

This page displays the report containing the referring pages linked to your site and the target pages on your site that the visitors hit.

Filter

Parameter | Description
ID | The ID of the required record.
Session ID | The ID of the required session which was opened when a visitor came to the site.
Referrer URL | The page containing links to your site.
Protocol | Filters results by the protocol type (e.g. http).
Domain | Filters results by entry of the specified text in the domain name.
Page | Address of the referred page.
Destination The expression to filter the result. Additionally, you can specify:
  • the site whose sections or pages are to be included in the diagram and report;
  • method to display false requests (error 404): with other pages, only false requests or all pages except false requests.
Failed page request | This flag allows to filter out the referred pages that could not be found on the server (error 404).
Period | Range of dates to filter out the visitors when matching against the information in the database.
Filter field logic | Defines how the filter works: whether all criteria must match, or at least one true condition is sufficient.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter and build graphs. To display all information, click Cancel.

Context bar

Button | Description
Group by | Opens a menu in which you can choose how the results are grouped: by domain, by links (pages) or without grouping.
Excel | Exports data from the table to the MS Excel format.

Table (ungrouped)

ID | From | To | Date | Session
[1] | [2] | [3] | [4] | [5]
Total: [6]
  1. The ID of the record in the database.
  2. The referring page.
  3. The page to which the referring page has links.
  4. The date of the visit from the referring page.
  5. The ID of the session opened at the moment of the visit.

Table (grouped by the referring site or page)

 | From | Value | Average hits |
[1] | [2] | [3] | [4] | [5]
 | Selected: [6]
  1. The record ordinal.
  2. The site domain name or the page.
  3. The absolute and relative number of visits from the referring site.
  4. Average number of hits from the referring site.
  5. Visual representation of the value.
  6. Number of records selected from the database.
Example of the report grouped by referring domain

Example of the report grouped by referring page


Visitors - Bitrix Site Manager - Content Management & Portal Solutions

Visitors

In this section

  • Filter
  • Context bar
  • Table
  • Visitor details
    •

    This page displays site visitors.

    Filter

    Parameter | Description
    ID, login, name, last name* | The login, name or last name or ID of the required registered user.
    Visitor ID* | The ID of the required site visitor.
    Registered | Specifies to display registered or unregistered or all users.
    UserAgent* | This field allows to filter out visitors according to browsers they used to view the site.
    IP address* | Finds visitors by the IP address of their last session.
    Languages* | Finds visitors by languages installed in their browsers.
    Country* | Specifies to select visitors from specific countries (resolved as per IP address).
    First visit date | Finds visitors by the date of the first visit.
    Visit date | Specifies to find visitors by the range of dates of visits. Please note that the session tables are used for this kind of search, so the required data may have been cleared.
    Last visit date | Finds visitors by the date of the last visit.
    Page* Specifies to find visitors by:
    • the site;
    • first pages of the first entry;
    • last pages of the last entry.
    Additionally, you can specify how to display false requests (error 404): with other requests, only false requests or all pages except false requests.
    Advertising campaign visitors | This flag allows to filter out visitors who entered the site under the advertising campaign on their first or last visit.
    Advertising campaign ID* | Filters visitors by the ID of the advertising campaign of the first or last visit.
    referer1 / referer2* | Identifiers of the advertising campaign of the first or last visit, respectively.
    referer3* | Auxiliary parameter of the advertising campaign.
    Events | Finds visitors by the range of number of events they initiated.
    Sessions | Same as above, but for sessions.
    Hits | Same as above, but for hits.
    Added to favorites | This flag allows to filter out visitors who did or did not add the site to favorites.
    Filter between-field logic Defines how the search is performed:
    • "and" - display records satisfying all criteria;
    • "or" - display records satisfying at least one criteria.

    * - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Excel | Exports data from the table to the MS Excel format.

    Table

    Column | Description
    Action menu
             Clicking the action button of any visitor opens a menu allowing to:
    • Details - opens a separate window displaying the detailed information about the visitor.
    ID | The visitor ID. If the ID is in red, this is your ID.
    Visitor | Information about the registered visitor: [ID] (login) Name LastName. Link on [ID] opens the user editor.
    Sessions | Number of visitor sessions (entries to the site). If 1, this is the first visit; otherwise, the visitor is considered to be returned. The link opens the list of sessions with the filter set to the ID of the visitor (not user).
    Events | Number of events initiated by this visitor. The link opens the list of events with the filter set to the ID of the visitor.
    Hits | Number of hits (pageloads) made by this visitor. The link opens the list of hits with the filter set to the ID of the visitor.
    First visit | The date and time of the first visit.
    Last visit | The date and time of the last visit.
    IP | The visitor IP address. The link starts the whois lookup service (http://www.whois.sc/IP).
    Country | The country of the visitor.
    Example

    Click on image to enlarge

    Click on image to enlarge

    Visitor details

    A new window with this report is opened if you select the Details command in the action menu of a visitor.

    Parameter | Description
ID | The ID of the visitor in the database.
Sessions | Number of sessions opened by the visitor.
Events | Number of events initiated by the visitor.
Hits | Number of pages that the visitor viewed.
First visit
Date | The date and time the first session took place.
Session ID | The ID of the first session.
Hits | Number of pages viewed by the visitor during the first session.
Time | Duration of the first session.
From | The referring page of the first session.
To | The page on this site first entered by the visitor at the time the first session started.
Advertising campaign | If the first session was initiated by an advertising campaign click, this field displays details on this advertising campaign: [ID] referer1 / referer2 / referer3
Last visit
Date | The date and time of the last session of the visitor.
Session ID | The ID of the last session.
Hits | Number of pages that the visitor had viewed during the last session.
Time | Duration of the last session.
User | Registration information of the visitor at the time of the last session.
Last | The last viewed page.
IP (host) | The IP address of the visitor and the resolved host name.
Country | Country of the visitor (determined by the IP address of the visitor)
UserAgent | The UserAgent of the visitor browser.
Advertising campaign | The advertising campaign at the time the last direct visit.
Languages | Languages installed in the browser of the visitor.
Cookie | Contents of the cookie file of the visitor at the time of the last hit.

    Example

    Click on image to enlarge

    Click on image to enlarge
    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Visitor sessions - Bitrix Site Manager - Content Management & Portal Solutions

Visitor sessions

This page displays sessions of the site visitors.

The Bitrix Site Manager considers the following events and actions as the session start:

  • Opening the site in a browser.
  • Visitor authorisation.
  • Termination of the visitor authorised session. In this case, the current session is closed and the new one is opened immediately.

The following events and actions are considered as the session end:

  • Closing the browser window.
  • Termination of the visitor authorization. The current session is closed.

Formally, a session is one "visit" to the site.

Filter

Parameter | Description
ID, login, name, last name* | Specifies to find sessions by the visitor (user) registration information.
Session ID* | The ID of the required session.
Start date | Specifies the range of dates within which the required sessions started.
End date | Specifies the range of dates within which the required sessions finished.
Visitor ID* | The ID of the required visitor. Compare to the ID of a registered user.
Registered | Find sessions of registered or unregistered visitors or both.
First time/returned | Finds sessions of either first-time or returned visitors.
Added to Favorites | Filter out sessions of visitors who added the site to their Favorites list during the session.
IP address* | Allows to find visitors by the IP address.
UserAgent* | The UserAgent of the required visitors.
Country* | Specifies the country of the required visitors. Country is determined as per IP address.
Now in stop list | Finds visitors who was added to the stop-list.
Stop list record ID | Allows to select visitors who was added to the stop-list by the stop-list record ID.
Hits | Range of number of hits (loaded pages) initiated during the required session. The report will include only sessions with number of hits within this range.
Events | Range of number of events initiated during the required session. The report will include only sessions with number of events within this range.
Visits on advertising campaign | Filters out sessions of visitors who came under an advertising campaign, common visitors or both.
Advertising campaign ID* | The ID of an advertising campaign to filter out sessions in the report. Used in conjunction with the previous field.
Returns under advertising campaign | This flag allows to find direct- hit or on-return sessions under an advertising campaign. Used in conjunction with the Visits on advertising campaign field.
referer1 / referer2* | Advertising campaign identifiers - referer1and referer2. Used in conjunction with the Visits on advertising campaign field.
referer3* | Auxiliary parameter to match against visits under an advertising campaign - referer3. Used in conjunction with the Visits on advertising campaign field.
Return on advertising campaign | Allows to find only sessions on return under advertising campaign. Used in conjunction with the Visits on advertising campaign field.
First page | Finds sessions by the first viewed page and site. Additionally, you can specify how to display false requests (error 404): with other requests, only false requests or all pages except false requests.
Last page | Same but filters by the last pages in sessions.
Filter between-field logic Defines how the search is performed:
  • "and" - display records satisfying all criteria;
  • "or" - display records satisfying at least one criteria.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Excel | Exports data from the table to the MS Excel format.

Table

Column | Description
Action menu
Clicking the action button of any session opens a menu allowing to:
  • Details - opens a separate window displaying the detailed information about the session.
ID | The ID of the session in the database. Your session is in red.
Visitor For a registered visitor:
  • [user ID] - the link opens the user editing form;
  • (login) Name SurName;
  • [visitor ID] - the link opens the list of visitors filtered by this visitor.
Start | The date and time the session started.
Duration | Duration of the session.
IP address | The visitor IP address. The link starts the whois lookup service (http://www.whois.sc/IP).
Hits | Number of hits (pageloads) made during this session. The link opens the list of hits with the filter set to the ID of the session.
Events | Number of events initiated during this session. The link opens the list of events with the filter set to the ID of the session.
Advertising campaign | If a visitor made a direct hit or return under an advertising campaign (AC), this column shows: the AC ID, referer1/referer2/referer3. The link on the AC ID opens the list of advertising campaigns with the filter set to this AC.
Selected | Number of records selected from the database.
Example of the report

Click on image to enlarge

Click on image to enlarge

Detailed session view

Field | Description
ID | The ID of the session in the database.
Hits | Number of viewed pages.
Start | The date and time the session started.
End | The date and time the session finished (time of the last hit).
Duration | Duration of the session.
Visitor | Information on the registered user or visitor.
First IP address | The IP address of the visitor at the time the session started.
Last IP address | The IP address of the visitor at the time the session closed.
Country | Country of the visitor.
Referrer | The page from which the visitor entered your site.
Target page | The page that the visitor entered when the session started.
Last page | The last page on your site opened by the visitor.
Advertising campaign | If a visitor made a direct hit or return under an advertising campaign (AC), this column shows: the AC ID, referer1/referer2/referer3. The link on the AC ID opens the list of advertising campaigns with the filter set to this AC.
UserAgent | The UserAgent of the visitor.
Example of the report

Click on image to enlarge

Click on image to enlarge
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Visitior's hits - Bitrix Site Manager - Content Management & Portal Solutions

Visitor hits

This page displays hits of the site visitors. A hit in the Bitrix Site Manager is one page load. The following actions also generate a hit: clicking a link and the consequent page load; page reload by pressing F5 or Ctrl+F5; opening a non-existing page (producing error 404).

Filter

Parameter | Description
ID, login, name, last name | Specifies to find hits by the visitor (user) registration information.
Hit ID | The ID of the required hit in the database
Session ID | Finds hits by the ID of the session during which the required hits were generated.
Date | The date and time the hit occurred.
Visitor ID | Finds hits by the ID of the visitor who generated the required hits.
Registered | This flag allows to filter out hits of either registered or unregistered visitors.
First time/returned | Allows to select visitors who entered the site for the first time, or returned to the site.
IP address | The IP address of the visitor who generated the required hits.
Country | Country of the visitor who generated the required hits.
UserAgent* | The UserAgent of the visitor browser.
Cookie | Finds hits of visitors by their cookie.
Now in stop list | Finds visitors who was added to the stop-list.
Stop list record ID | Allows to select visitors who was added to the stop-list by the stop-list record ID.
Page | The page requested by the visitor at the moment of the hit.
Filter between-field logic Defines how the search is performed:
  • "and" - display records satisfying all criteria;
  • "or" - display records satisfying at least one criteria.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact matching searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Excel | Exports data from the table to the MS Excel format.

Table

Column | Description
Action menu
 Clicking the action button of any visitor opens a menu allowing to:
  • Details - opens a separate window displaying the detailed information about the visitor.
ID | The hit ID. If the ID is in red, this is your ID.
Date | The date and time the hit was generated.
Visitor | Information about the registered visitor: [ID] (login) Name LastName. Link on [ID] opens the user editor.
IP address | The visitor IP address. The link starts the whois lookup service (http://www.whois.sc/IP).
Country | The country of the visitor.
Page | The page on which the hit occurred.
Selected | Number of hits selected from the database.
Example of the report

Click on image to enlarge

Click on image to enlarge

Detailed hit information

Field | Description
ID | The ID of the hit in the database.
Session | The ID of the session in the database.
Date | The date and time the hit occurred.
From | The referring page (the page from which a visitor entered the site).
Page | The address of the page.
Visitor | The visitor registration information and the ID.
IP address | The IP address of the visitor at the time when the hit occurred.
Country | Country of the visitor.
UserAgent | The UserAgent of the visitor browser.
Query method | The method of an HTTP query: GET or POST. You can find more details on methods here: Method Definitions.
Cookies | Contents of the cookie file of the visitor at the time of the hit.
Example

Click on image to enlarge

Click on image to enlarge
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Stop list - Bitrix Site Manager - Content Management & Portal Solutions

Stop list

A stop list is the table containing certain parameters used to limit the visitor access to the site contents and redirect to other resources.

Filter

Parameter | Description
ID | The ID of the required stop list record in the database.
Site | Restricts search to the stop-list records of the specific site.
Start date | The date the stop list record became active.
End date | The date the stop list record became inactive.
Active | Finds either active or inactive records, or both.
Add to statistics | Allows to find records that are to be recorded in the statistics database.
IP address | Fins the stop-list records by the IP address of the visitor.
UserAgent | Same as IP address, but used with the UserAgent.
From | The referring page (finds records by the referring pages of visitors who were added to the stop-list).
To | Finds records by the destination pages of visitors who were added to the stop-list.
Redirect | Finds records by the mask of pages to which the visitors in the stop-list are redirected.
Message | Selects records by the message that a visitor sees after one is added to the stop list.
Comment | Arbitrary comment provided by the administrator.
Filter between-field logic Defines how the search is performed:
  • "and" - display records satisfying all criteria;
  • "or" - display records satisfying at least one criteria.

* - These fields allow using Boolean expressions. You can get information on the syntax by clicking on the symbol "?" next to the field. For exact searches using this field, mark the corresponding checkbox.

Click Set filter to activate the filter. To display all information, click Cancel.

Context bar

Button | Description
Add | Clicking this button opens a form in which you can create a new stop-list record.
Excel | Exports data from the table to the MS Excel format.

Table

Column | Description
Checkbox column | Used to select stop-list records to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any stop-list records opens a menu:
  • Modify - edits the stop-list record parameters;
  • Delete - deletes the stop-list records.
ID | The ID of the stop list record.
Activity status The indicator denotes the record state:
  • - the record is currently active;
  • - the record is currently inactive.
    •  The following fields affect the record activity:
    • the record commencement time;
    • the record expiration time;
    • the record active state.
    Start | The date and time the stop list record became active.
    Active | The flag indicating the record is active.
    Site | The site within which the record is active.
    IP address | The visitor IP address.
    Net mask | The visitor network mask.
    Stat | If yes, the statistics module registers an event of putting the visitor to the stop-list.
    Selected | Number of stop-list records selected from the database.
    Checked | Number of stop-list records marked in the checkbox column.


Creating and editing a stop list record - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a stop list record

In this section

  • Context bar
  • "Parameters" tab
  • "Actions" tab
  • "Comment" tab
  • Notes on network masks
    •

    This form is used to create and edit the stop list record.

    Context bar

    Button | Description
Stop list | Opens the stop list.
Create | Creates a new stop-list record.
Delete | Deletes the current stop-list record.

    "Parameters" tab

    Field | Description
Modified | The date and time the record was last modified.
Record activity
Active | Makes the record active or inactive.
Start date | The date the record is to become active.
End date | The date the record is to become inactive.
Criteria to filter out visitors
Site | The site on which the record works. | A visitor matches the stop-list record only if all criteria match.
IP address | The IP address of the affected visitor.
Net mask | The visitor IP address mask.
UserAgent | The visitor UserAgent.
From | The referring page (from which the affected visitors enter the site).
To | The page to which affected visitors come.

    "Actions" tab

    Field | Description
Redirect to URL | Address of the page to which the visitors is to be redirected (if the visitor matches the record criteria).
Show message | The message to be displayed to the visitor.
Encoding | Language of the message; affects the message display.
Save statistics | Set this flag to record the stop-list visitor hits.

    "Comment" tab

    An arbitrary comment explaining the reasons why the record was created.

    Remember to click Save after you have made any changes.

    Subnet mask (in stop lists)

    In the TCP/IP terms, a subnet mask (or net mask) is a bit mask (set of flags) that specifies which bits of the IP address specify a particular IP network or a host within a subnetwork. For example, an IP address of 12.34.56.78 with a subnet mask of 255.255.0.0 specifies net 12.34.0.0.

    To extract the network ID (network address) from an arbitrary IP address using an arbitrary subnet mask, IP uses a mathematical operation called a logical AND comparison:

    IP address:   00001100 00100010 00111000 1001110 (012.034.056.078)
Subnet mask:  11111111 11111111 11100000 0000000 (255.255.224.000)
------------------------------------------------------------------
Network ID:   00001100 00100010 00100000 0000000 (012.034.032.000)

    A stop list record contains two records: network IP and subnet mask. A visitor is considered to match a stop list record if, having the subnet mask (of a stop list record) applied to their IP address, we get the network IP (of a stop list record).

    Example 1. Deny access to all visitors from IP of 206.191.49.66.

    1. Specify the following:
      • network IP = 206.191.49.66
      • subnet mask = 255.255.255.255
    2. When a visitor with IP of 206.191.49.66 enters the site, the following operation occurs:
      Visitor IP address: 11010001 10111111 11000001 1000010 (206.191.049.066)
Subnet mask:        11111111 11111111 11111111 1111111 (255.255.225.255)
------------------------------------------------------------------------
Result:             11010001 10111111 11000001 1000010 (206.191.049.066)
      If the result matches the network IP (of a stop list record), the visitor is found in the stop list. Thus, all visitors from 206.191.49.66 will match the stop list record.

    Example 2. Deny access to all visitors from subnet of 206.191.49.xxx (IP in the range from 206.191.49.1 to 206.191.49.255)

    1. specify:
      • network IP = 206.191.49.0
      • subnet mask = 255.255.255.0
    2. When a visitor with IP of 206.191.49.76 enters the site, the following operation occurs:
      Visitor IP address: 11010001 10111111 11000001 1001100 (206.191.049.076)
Subnet mask:        11111111 11111111 11111111 0000000 (255.255.225.000)
------------------------------------------------------------------------
Result:             11010001 10111111 11000001 0000000 (206.191.049.000)
      The result matches the network IP (of a stop list record), and consequently, the visitor is found in the stop list. Thus, all visitors with IP's from 206.191.49.1 to 206.191.49.255 will not be allowed to access the server.


Online visitors - Bitrix Site Manager - Content Management & Portal Solutions

Online visitors

This form displays sessions and visitors who are currently active on the site. The table refreshes automatically after a period of time which can be set here by clicking one of the links: 20, 30, 60, 120 or 300, which specify the refresh period, in seconds. To update the list immediately, click Refresh. The timer in round brackets indicates the period of time left till the next refresh.

Context bar

Button | Description
Excel | Exports data from the table to the MS Excel format.

Report table

Column | Description
Action menu
Clicking the action button of any visitor records opens a menu:
  • Details - opens the visitor details report;
  • Stop-list - adds the visitor IP address to the stop-list.
Advertising campaign | If the session was initiated by an advertising campaign click, this field displays details on this advertising campaign: [ID] referer1 / referer2 / referer3. The link on the ID opens the list of advertising campaigns with the filter set to this campaign.
Hits | Number of hits (pageloads) made during this session. The link opens the list of hits with the filter set to the ID of the session.
Session time | Duration of the session.
User For a registered visitor:
  • [user ID] - the link opens the user editing form;
  • (login) Name SurName;
  • [visitor ID] - the link opens the list of visitors filtered by this visitor.
IP address | The visitor IP address. The link starts the whois lookup service (http://www.whois.sc/IP).
Country | The visitor country (defined by the IP address).
Last page | The last page viewed by the visitor.
Referrer | The page from which the visitor entered the site.
Selected | Total number of online simultaneous visitors.

Example of the report

Click on image to enlarge

Click on image to enlarge
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Settings - Bitrix Site Manager - Content Management & Portal Solutions

Settings

This form (Settings -> Statistics) is used to customize the system-wide settings of the Statistics module.

General settings

"Settings" tab

Field | Description
Time to send the next statistical report by e-mail | This field contains the time that the statistical report will be sent. Henceforward, the report will be sent on a daily basis at the specified time. If you leave the field blank, no report will be sent. If the site runs on a Windows-based server, the filed is blank by default. This is due to the Windows operating system peculiarity that protracts sending e-mail messages.
On-line visitor interval | This field specifies the value that is used in the Online visitors subsection. This subsection displays sessions of visitors appeared active for the last N seconds. This field contains the value N.
Maximum number of records in tables | The Statistics module subsections display various tables containing the information retrieved from the database. Any retrieval is characterized by a number of the selected records. The more this number is, the more system resources and time is required by a server to accomplish the request and format the output. This parameter allows limiting the number of records and accelerating the process of building the statistical reports by specifying a reasonable value of records. If wish to avoid limitation, you can set any large value, for example, 100 000 000. As a rule, such values are rare to achieve, even if the site traffic puts a heavy load on the server.
Graphs weight | Width of graphs displayed in the statistical reports, in pixels.
Graphs height | Height of graphs, in pixels.
Pie charts diameter | Diameter of pie charts, in pixels.
Size of the TOP list in statistics summary | Number of elements (adv. campaigns, events etc.) displayed in reports on the Statistics summary form.
Size of the TOP list in the ad campaign detail view | Number of elements displayed in reports on the Advertising campaigns form.
Extra processing for visitors not accepting cookies | The Statistics module is capable of interacting with browsers or other software that do not accept inter-session or session cookies. This is achieved by storing the session data in a special table. The specific user (visitor) is recognized by applying a hash function (md5) to a range of environment variables peculiar to this very user. This flag allows enabling or disabling this feature.
Optimize tables when cleaning | The system automatically optimizes MySQL tables after it has deleted the outdated statistical information (fields Days to keep...).
Base currency (all the financial data will be stored in this currency) | If the Currencies module is installed, you can select a base currency for the Statistics module to store the financial showing. If the option Convert all financial showing is checked, all the values will be converted into a new base currency using the rate of exchange for the present day.
Traffic limits You can protect your site from mass downloads by using this form. If you do not want your site to be available offline or just to limit the number of concurrent connections from a single IP address, specify appropriate values in this form. You can customize the PHP and HTML code of the page that is sent to a user in case the traffic limit is exceeded.
Disable | If checked, the excessively active clients are blocked.
for | Period of time during which a client receives the HTTP error 503 (or other error specified in the template) in response to all requests.
if during the period of | A client must not make more hits than specified in the next field within this period; otherwise the client will be refused.
generated more than | Maximum allowed number of hits within the specified period of time.

"Stored data" tab

Field | Description
Page traffic
Save the section and page traffic statistics | This flag enables or disables tracking the traffic statistics of the site sections and pages. This information is available in the Site traffic subsection.
Collect data for the "Site Paths" report | If enabled, the statistics module registers events and other information required to display the site path report.
Max path length to keep for this site | Maximum number of clicks to be kept within one path.
Important page parameters | Page parameters (those passed in URL as ?param=value&param=value...) to be stored.
Ad campaigns
Use advertising campaign with referer1=NA, referer2=NA by default | Set this flag to apply a default advertising campaign to ordinary users that visit the site under no advertising campaign. The default advertising campaign has the following identifiers: referer1=NA, referer2=NA.
Automatically create ad. campaigns for URL'a with referer1 and referer2 | If this option is enabled, and if referer1, referer2 are present in URL but no adv. campaign matches these parameters, the system creates a new campaign with these parameters.
Synonyms for referer1 | This field contains aliases for the advertising campaign identifierreferer1. By default, the synonym for referer1 is r1 and referrer1.
Synonyms for referer2 | This field contains aliases for the advertising campaign identifierreferer2. By default, the synonym for referer2 is r2 and referrer2.
Synonyms for referer3 | This field contains aliases for the advertising campaign identifierreferer3. By default, the synonym for referer3 is r3 and referrer3.
Default event display mode in the advertising campaign report | The rightmost column in the advertising campaign report shows information on visitor events who hit upon the site under the advertising campaign. This parameter sets the default display mode if this column.
Search engines
Wildcard for the browser UserAgent (used to automatically detect search engines as exceptions) | This field allows you to specify the UserAgent wildcards. All software reporting this UserAgent will be excluded from the Autodetect (see the Autodetect subsection). The wildcard allows the following operators:% - 0 or more characters; _(underscore) - any one character. If you specify the inexact UserAgent string, you should enclose it with the operator %.
Events
Encode the event additional parameter | This flag enables or disables the base64-encoding of the events auxiliary parameter.
Short site identifier (used in the auxiliary parameter when loading events manually; without dots and spaces) | A short site identifier is used in the auxiliary parameter when loading the external events manually. This parameter had been introduced to allow distinguishing the auxiliary parameters of different sites, having these sites built with the Bitrix Site Manager CMS only.
Path to additional handlers for manual event loading | Path to the folder with scripts (relative to the site root) which can be used when loading events for CSV file preprocessing. Files from this folder are displayed in the Loading events form as a CSV file processors list from which a desired processor can be selected.
Referring sites and search phrases
Save the statistics of the referring sites and search keywords | This flag enables or disables tracking the statistics of external referrer hits, including search engines. This information is available in the Site traffic and Search keywords subsections.
Do not erase top domains from the referring | This field specifies the first N most active domains that will not be erased when cleaning the referring domains table. If set to 0, a common rule applies: the table is cleaned after the number of days specified in the field Days to keep the referring domains after the last visit from any domain occurred.
Hits
Save hits | Enables or disables storing addresses of the loaded pages. This information is available in the Visitor hits subsection.

"Retention period" tab

These parameters allow to specify the maximum period of time during which each event is stored. Each parameter field is equipped with the clear checkbox which, if marked, clears the corresponding piece of information upon clicking Save.

Field | Description
Page traffic
Days to keep history of the section and page visits | Information on the section and page traffic (in fact, number of hits per section or page) is stored in a special table. This field specifies number of days that the table is cleaned after the last hit occurred.
Days to keep the site path dynamics | For each path, the system keeps path clicks for every day. These data are stored in a special table which is cleared after number of days specified in this field passed after the last click.
Referring sites and search phrases
Days to keep search keyword hits | Any visit under a search phrase is recorded in a special table. This field specifies number of days that the table is cleaned after the last visit of such kind occurred.
Days to keep referring page hits | This field specifies number of days that the referrer hit table is cleaned after the last hit of such kind occurred.
Events
Days to keep each event | The Statistics module makes provision for the event types. The system stores all events, both internal and external, in a special table. This field specifies number of days that the table is cleaned after the event occurred.
Days to keep the event type dynamics | The system keeps the history for each event to store the number of events on a daily basis. This field specifies number of days that the table is cleaned after the event occurred.
Ad campaigns
Days to keep history of the advertising campaign visitors | The system stores the hit history of all visits under advertising campaigns. The history is stored in a special table. This field specifies number of days that the table is cleaned after the last visit.
Days to keep advertising campaign dynamics | The system keeps the unique history table for each advertising campaign to store the information on a daily basis. This field specifies number of days that the table is cleaned after the last event of any type occurred under this advertising campaign.
Days to keep search engine dynamics | The system keeps the history for each search engine to store the number of indexed pages on a daily basis. This field specifies number of days that the table is cleaned after the last indexing operation occurred.
Search engines
Days to keep search engine hits | A hit of a search engine is the address of the indexed page. The system keeps the unique history table for each hit. This field specifies number of days that the table is cleaned after the last indexing operation occurred.
Countries
Days to keep the country-based dynamics | For each country, the system keeps visits and other information. These data are stored in a special table which is cleared after number of days specified in this field passed after the last visit from a specific country.
Visitors
Days to keep visitors | Each visitor that hits the site is assigned own profile. All profiles are stored in a special table. This field specifies number of days that the table is cleaned after the last visit occurred.
Sessions
Days to keep sessions | Information on the visitor sessions is stored in a special table. A session has a number of parameters; one of them is the date of the last hit within a session. This field specifies number of days that the table is cleaned after the last hit occurred.
Hits
Days to keep hits | The system keeps the unique history table for each hit, that is, stores addresses of all pages transferred to a visitor. This field specifies number of days that the table is cleaned after the last hit occurred.

"Suppression" tab

This tab allows to set parameters describing rules used to exclude certain visitors from statistics.

Field | Description
Use the following rule Defines the method by which visitors are excluded:
  • gather all statistics; no suppression - the system gathers all statistics for all visitors;
  • suppress users of selected groups - users who are members of the selected groups are not included in statistics;
  • suppress users with certain IP addresses - visitors whose IP addressed match the specified IP address ranges are not included in statistics;
  • suppress users of selected groups with certain IP addresses - combines the previous two conditions.
User groups to be excluded from statistics | Information (hits, sessions etc.) on users who are members of the selected groups will not be recorded.
IP address range(s) to be suppressed Information on visitors whose IP addressed match the specified IP address ranges will not be recorded.

Sample ranges:
  • 192.168.10.110-192.168.10.120;
  • 11.0.0.5-11.0.0.5 (note: to set a single IP address, enter a range composed of this address).

"Access" tab

This form allows to assign access permissions to all available site users except administrator who always has full access. By altering the default access level, you can easily change the access permissions for all users at once who have the Default level.

The form allows to assign the following permissions to site visitors.

  • Deny - all access is forbidden.
  • View statistics without financial parameters - view traffic indices without any commercial information.
  • View all statistics - view all statistics.
  • Full access - view statistics, edit settings and permissions.
Field | Description
Default | Changes the default access level thus affecting all user groups that have the default access level.
[User groups] | Changes the access level.

Service tools area

Creating the IP-to-country lookup index

The form allows to recreate both the index and file with the IP address database used to lookup the country name by the visitor IP address. You can set the time slice in seconds (Step field), if the operation fails to complete within the assigned time on your server.

Statistics clean-up

The form can be used to clean all the statistics tables, except for the search engine tables (counters only will be reset) and IP-to-country tables.

Table optimization

The form is used to optimize the MySQL tables of the Statistics module.


Creating an event-driven link - Bitrix Site Manager - Content Management & Portal Solutions

Creating an event-driven link

You can create a link with parameters event1, event2 and event3 manually or by using the HTML editor.

Example of a download link for file.exe

/download/TWBSetup.exe?event1=download&event2=hffr&event3=file.exe

Example of an external link (URL-encoded)

/redirect.php?event1=hffr_click&event2=hffr&event3=buy&
 goto=http%3A//www.silveragesoftware.com/order/
 %3Freferer1%3Dsite%26referer2%3D%23EVENT_GID%23

Creating a link in HTML editor

  1. Open a page in which you want to insert a link.
  2. Switch to visual editing mode in HTML editor.
  3. Select the portion of text that you want to covert to a link and click [image].
  4. In the new window, select Link to Web location.

  5. Type in the values of event1 and event2 that you had previously used for creating the event type. The field event3 may contain arbitrary value (e.g. name of the current page). This value will help you analyze the jump results more precisely.

  6. Type a link to an external site in the field External link. You can use additional parameters here. For example, referer1=your_site_name and referer2=#EVENT_GID#.
    The parameter referer1=your_site_name will help the statistical system of an external site register your visitors if the extarnal system uses parameter referer1.
    The parameter referer2=#EVENT_GID# allows to register session ID, advertising campaign ID (if any), possible visitor's return.
  7. Click OK.

The resulting link might look as follows:

/redirect.php?event1=hffr_click&event2=hffr&event3=buy&
 goto=http%3A//www.silveragesoftware.com/order/
 %3Freferer1%3Dsite%26referer2%3D%23EVENT_GID%23


Users - Bitrix Site Manager - Content Management & Portal Solutions

Users

The Bitrix Site Manager allows to create any number of user groups with different access permissions to the site resources. With the access permission settings you can:

  • permit users to view information only in public sections of the site;
  • grant access to the private site sections. For example, a private forum, a partner section or any other section requiring the limited access permission;
  • allow users to edit certain files and sections, while denying the access to other files of the site.

The Bitrix Site Manager possesses a vast range of features allowing to manage site content thus considerably reducing the time required to maintain it. For example, the system allows to have several users (site administrators) simultaneously maintaining the site. The site administrators, in their turn, can distribute various management functions among other members of the company who have lower permissions to access the site resources.

Each registered site user has their personal credentials: the login and password, and belongs to a certain group. Each group is assigned its own access permissions. To access the site resources, a user has to log on to the site; that is, enter their login and password in the special authorisation form.


List of users - Bitrix Site Manager - Content Management & Portal Solutions

List of users

In this section

  • Filter
  • Context bar
  • List of users
    •

    The List of users page ( Settings -> Users -> List of users) displays site users and allows:

    • creating new site users;
    • editing users parameters and access permissions;
    • deleting site users.

    Filter

    A filter is used to set the parameters for selecting site users to be displayed in a list. The table that follows describes the filter fields.

    Parameter | Description
ID | The ID of the sought user. You can use advanced search here.
Modified | Specifies the range of dates within which the required records were modified in the database.
Last authorisation | Specifies the range of dates within which the required users were last authorised.
Active | Defines whether active, inactive or all users are to be displayed.
Login | Allows selecting users by their logins. You can use advanced search here.
E-Mail | Instructs to select users by their e-mail addresses. You can use advanced search here.
First and/or Last name | Instructs to select users by their names. You can use advanced search here.
Profile fields | Allows searching users by other profile fields, such as telephone number, ICQ number etc. You can use advanced search here.
Groups | List of groups to which the required users belong. To select several groups, press Ctrl and hold it while performing the selection.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add user | Opens a form in which you can create a new user.
Excel | Exports data from the table to the MS Excel format.

    List of users

    Column | Description
    Checkbox column | Selects users to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
             Clicking the action button of any rule opens a menu allowing to:
    • Edit - edits the user;
    • Add copy - duplicates the user;
    • Delete - deletes the user (not applicable to administrators).
    ID | The user ID.
    Modified | The date the user was last modified.
    Active | Indicates the user is active. The site administrator cannot be deactivated.
    Login | The user login.
    First name | The user name.
    Last name | The user last name.
    E-mail | The user e-mail address.
    Last authorised | The date the user was last authorised.


Creating and editing a user - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a user

In this section

  • Context bar
  • Editing form
  • User
  • Groups
  • Personal information
  • Work
  • Forum profile
  • Notes
    •
  • Control buttons
    •

    This form is intended for setting the parameters of the existing or the newly created users.

    Context bar

    Button | Description
List of users | Opens a page containing the list of users.
Create new user | Creates a new user in this form. The button is displayed when editing the existing user only.
Copy user | Duplicates the current user.
Delete user | Deletes the current user.

    Editing form

    All the user parameters are logically grouped and placed in corresponding tabs.

    "User" tab

    This tab is used to specify the user parameters.

    Field | Description
Last update | Contains the date and time when the user was last modified. The field is displayed when editing the existing user.
Last authorised | Date and time when the current user was last authorised (logged on to the system). The field is displayed when editing the user.
Active | Specifies whether the user is active or not. Inactive users cannot log on to the system using their account information.
Name | The user's first name.
Last name | The user's last name.
*E-Mail | The user's e-mail address to which all site notifications will be sent. This field is required.
*Login (min. 3 characters) | The user login required to log on to the system. This field is required.
New password (min. 6 characters) | This field can be used to change the current password of the user. Confirm the new password in the next field if you modify it.
Confirm new password | This field is used to confirm the new password. The contents of the field should be exactly the same as in the previous field.
Default site for notifications | The site whose text resources (templates) will be used to notify the user about changes.
Notify user | With this checkbox selected, click Save to notify the user about the new changes.

    *Required fields.

    "Groups" tab

    This tab specifies the list of groups whose member the current user is, and the duration of membership.

    Field | Description
    User group membership checkboxes | If a checkbox of a user group is marked, the user is a member of the corresponding user group.
    Groups This section is used to select groups to which the user is to be added. For each group, you can specify the period of time for which the user is added to the respective group.

    Specify only the from date if a user is to be added for an unlimited period.

    For example, if you want to grant an access to a private forum to a user for 1 month, you should do the following:
    • add a user to the respective group by checking the appropriate box (e.g. Private forum);
    • next, specify the active period after which the user is to be deleted from the group. The from field specifies the date from which the access is to be granted, and the till field - the access expiry date.

    "Personal information" tab

    This tab specifies the personal information of the user.

    Field | Description
Job title | These optional fields contain information about the user.
Web page
ICQ
Gender
Birthday
Photo
Phone numbers
Phone | Contacts.
Fax
Mobile
Pager
Postal address
Country | Optional postal address.
State
City
Zip
Address
Mailbox
Notes | Arbitrary comments.

    "Work" tab

    This tab specifies information about the user's work.

    Field | Description
Company name | These optional fields contain information about the user's work.
Web page
Department
Position
Profile
Company logo
Phone numbers
Phone | Contacts.
Fax
Pager
Postal address
Country | Optional postal address of the user's work.
State
City
Zip
Address
Mailbox
Notes | Arbitrary comments.

    "Forum profile" tab

    This tab specifies the user's profile parameters for use with the forum.

    Field | Description
Posting allowed | With this checkbox selected, the user can create messages (and reply) in the forum.
Show name | If this checkbox is selected, the forum displays the user's name.
Description | Short comment (couple of words) displayed in the forum.
Interests | The user's hobby and interests.
Signature | The user's signature to be added to all messages.
Avatar | The user picture displayed in the forum. Maximum allowed avatar size is specified in the Forum module settings.

    "Notes" tab

    Field | Description
Administrator notes | Arbitrary comments of the site administrator.

    Control buttons

    Button | Description
Save | Saves the user parameters. Opens the page with the list of users.
Apply | Saves the user parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


User groups - Bitrix Site Manager - Content Management & Portal Solutions

User groups

In this section

  • Filter
  • Context bar
  • List of user groups
    •

    The User groups page ( Settings -> Users -> User groups) is used to manage user groups. The User groups form is designed for:

    • viewing information on user groups;
    • selecting a user group to edit;
    • creating and deleting user groups.

    Filter

    Filter is used to select the user groups from the list matching the parameters specified. The below table describes the filter parameters.

    Parameter | Description
ID | The ID of the required user groups. Corresponds to the ID field of the list of groups. You can use advanced search here.
Modified | Specifies to select user groups whose parameters were changed during the period in this field.
Active | Defines whether active, inactive or all user groups are to be displayed.
Name | Names of the selected user groups. You can use advanced search here.
Description | Specifies to select user groups by their description. You can use advanced search here.
Users | Filters user groups by the number of users in each group. Specified as a numerical range.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add group | Opens a form in which you can create a new user.
Excel | Exports data from the table to the MS Excel format.

    List of user groups

    Column | Description
    Checkbox column | Selects user groups to which the desired actions are to be applied.
    Action menu
             Actions on a user group:
    • Edit - edits the user;
    • Add copy - duplicates the user;
    • Delete - deletes the user (not applicable to administrators).
    ID | The ID of the user group.
    Modified | The date the group was last modified.
    Active Indicates the group is active. If the group is inactive, all users of this group are disabled. There are two user groups that cannot be deactivated: Site administrators and Everyone.
    • The Site administrators group is always active and always contains at least one site administrator.
    • The Everyone group virtually contains all unauthorised site users.
    Sort. | The user group sort weight. Defines the group position in lists.
    Name | The appropriate name of the user group.
    Description | User group description. Invisible by default.
    Users | Number of users in the group.


Creating and editing a group - Bitrix Site Manager - Content Management & Portal Solutions

Creating and editing a group

In this section

  • Context bar
  • Editing form
  • Parameters
  • Security
  • Access
  • Control buttons
    •

    This form is intended for setting the parameters of an existing or a new user group. The table below describes the field values necessary for creating or editing a user group.

    Context bar

    Button | Description
Group list | Opens a page containing the list of groups.
Create new group | Creates a new user group in this form. The button is displayed when editing the existing group only.
Copy group | Duplicates the user group.
Delete group | Deletes the user group.

    Editing form

    The user group parameters form consists of three tabs. Each is used to define a certain set of parameters.

    "Parameters" tab

    This tab is used to specify the user group parameters.

    Field | Description
    Last update | Contains the date and time when the group was last modified. The field is displayed when editing an existing user group.
    Users | Number of users in the group. The field is displayed when editing an existing user group.
    Active | Specifies whether the group is active or not. If the group is inactive all users of this group are disabled.
    Sorting | The user group sort weight. Defines the group position in lists.
    *Name | Required parameter. Specify an arbitrary yet meaning-bearing group name, for example, Advertisers.
    Description | Arbitrary group description.
    Users in the group
    This form specifies the list of registered users who are the members of the current group, and the duration of membership.
    Field | Description
User | The ID, login and name of a user added to the group. The user ID is the link to the page containing the user editing form.
Active period | Specifies the period of time for which the user is added to the current group. On the expiry of the active period the user will be deleted from the group. If a user is to be added for an unlimited period, only the from date is to be provided.

    * - Required fields.

    "Security" tab

    This tab is used to specify the security policy for the current user group.

    Field | Description
    Predefined security settings An approach of security levels allows to prevent the site from XSS/CSS attacks. In this field you can choose one of the predefined levels of security. The required parameter values of security will be specified in the corresponding fields automatically. The following predefined security values are possible:
    • Do not override. When selecting this level, the predefined security parameters will be applied to all user groups:
      • high level will be applied to site administrators;
      • for the other groups, security level parameters must be configured by the site administrator.
      To modify individual parameter values, uncheck the Do not override box near the necessary fields.
    • Low;
    • Mean;
    • High.
    For users who are members of more than one group, the strictest rule (of those defined for these groups) will be applied to every setting of security policy.
    Session maximum lifetime | Maximum session duration (minutes). This parameters is used to avoid incorrect session lifetime settings in the php.ini file.
    SESSION_IP_MASK | With this protection on, theft of a cookie file containing the session information becomes useless. This type of protection is the most effective in struggle against XSS/CSS attacks.
    MAX_STORE_NUM | Number of computers on which authorised sessions of a single user can be stored. For site administrators, the value of 1 is recommended.
    STORE_IP_MASK | Prevents possibility to use a hash file, stolen from the user's computer with a view to attack the site. This parameter is recommended to use together with other rules concerning the authorisation duration and number of authorisations.
    STORE_TIMEOUT | Maximum length of the stored authorisation (minutes).
    CHECKWORD_TIMEOUT | Defines the maximum storage time of control word for the password recovery and allows to minimise the risks of site attacks via the recovery mechanism by intercepting e-mails.

    "Access" tab

    This tab specifies the user group access permissions for administrative sections of different modules.

    Field | Description
List of modules and access levels | Contains the list of the installed modules, for each of which you can set access rights for the user group. When you select the access level by default, the appropriate user group is assigned a standard access level defined in the main module settings. Changing the default access permission in the main module settings causes automatic changing of rights of this group to access the modules for which the default access level has been selected.

    Control buttons

    Button | Description
Save | Saves the user group parameters. Opens the page with the list of groups.
Apply | Saves the user group parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Search - Bitrix Site Manager - Content Management & Portal Solutions

Search

The Search module performs indexing and searching for information within the site. All text information that appears within the scope of the site in the form of static HTML pages or through modules (for example, information blocks, forum posts) becomes indexed automatically. You can search either the whole index, or a part of it.

Searches allow using special query language.

Query language

A common query in just one or more words, for example:

fresh fish salmon

This query will find pages containing all of the query words.

You can use logical operators to build more complicated queries, for example:

fresh fish or cleaner

This query will find pages containing both fresh and fish or cleaner.

fresh fish not mackerel

This query will find pages containing both fresh and fish but not mackerel.
You can use brackets for more complex queries.

Logical operators

Operator Synonym Description
and And
&
+ 		Logical operator and is implied and can be omitted. A query fresh & fish is equivalent to fresh fish.
or Or
| 		Logical operator or allow searching for records containing at least one of operands.
not Not
~ 		Logical operator not searches for records not containing an operand stated after the operator.
( ) Round brackets define the logical operators precedence. Please make sure that all brackets are paired.
" " Searches for exact phrase.


Search result sorting rules

In this section

  • About search result ranking rules
  • Ranking rules management
  • Filter
  • List of rules
  • Search index update
    •

    About search result ranking rules

    After a user enters the search query and clicks Search, the system searches the index and selects pages matching the query. Before results are displayed to a user, they are sorted by relevance (which is usually defined by density of keywords on a given page), or by the page timestamp. Users can choose the sorting mode on the search result page by clicking on one of the links: Sort by relevance or Sort by date.

    Sometimes you may need give preference to certain documents when displaying the search results. For example, you may want to put goods that are to be sold out as soon as possible, higher in the search results. To achieve this, a special facility has been developed allowing to assign a required weight (page rank) to required pages. Pages matching the specified ranking criteria will be put at the top of the search result list, according to page ranks indicated in the ranking rules.

    A fixed rank can be assigned to:

    • static files (requires full path to be supplied);
    • information blocks (you can specify an information block type, an information block and an element which should have the specified priority);
    • forums (the required forum, a forum thread and a message can be specified).

    The Search result sorting rules form displays existing page ranking rules. You can add more rules here and recreate the search index. You will have to recreate the index if you have created, deleted or modified a rule. Thus, adding or modifying a rule involves two steps:

    • ranking rules management: creating, modifying or deleting ranking rules;
    • search index update.

    Ranking rules management

    Filter

    To display only the required rules, set the filters according to the search criteria. The following table describes the filter fields.

    Parameter | Description
    ID | The ID of the required rule.
    Site | The site on which the required rule is effective.
    Module | The module (in fact, content disposition) to which the required rule is applicable.
    Parameter 1 The parameter 1 of the required rule. Depending on the selected content disposition, the parameter can be:
    • file name;
    • information block type;
    • forum name.

    Click Set filter to activate the filter. To display all information, click Cancel.

    Context bar

    Button | Description
Add | Opens a form in which you can create a new ranking rule.
Excel | Exports data from the table to the MS Excel format.

    List of rules

    Field | Description
    Checkbox column | Used to select rules to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
    Action menu
             Clicking the action button of any rule opens a menu allowing to Edit or Delete the rule.
    ID | The rule ID.
    Site | The site on which the rule is effective.
    Module | Content disposition. Indicates the type of content to which the rule is applicable.
    Parameter 1 First ranking parameter. Meaning depends on content disposition:
    • static files - not used;
    • information blocks - the information block type;
    • forums - the forum name.
    Parameter 2 Second ranking parameter:
    • static files - not used;
    • information blocks - the information block;
    • forums - the forum thread.
    Parameter 3 Third ranking parameter:
    • static files - file name;
    • information blocks - the information block element;
    • forums - the forum message text.
    Rank | The ranking rule weight. Defines the order in which documents matching the rule criteria are positioned in the search result list. The less is the weight, the higher is the position.

    Search index update

    This section contains button with which you can update the index. You will have to update the index for changes to take effect. Click Update to update the index.


Ranking rule parameters

In this section

Context bar
Rule properties: "Rule" tab
Control buttons

This form is used to create a new or edit an existing ranking rule.

Note
Applying a rule involves: examining the search request; finding documents satisfying the request; searching for ranking rules matching the found documents and in case matching rules are found, ranking the search results according to sorting weights specified in matching rules.

For example, a user searches for documents containing "nokia phones", and the following rule exists:

"Information blocks :: 'Catalog' block type :: 'Nokia Phones' information block :: sorting: 1"

When the search completes, the system will try to find a rule satisfying the search criteria. When searching for a rule, the system detects that some of the search results are the 'Nokia Phones' information block elements. Hence, the above described rule will be applied to the search results, which will apply the sorting value of 1 to results from the 'Nokia Phones' information block. In most cases, applying the sorting value of 1 automatically moves such search results to the top of list.

Context bar

Button | Description
List of rules | Opens the list of ranking rules.
Add a new rule | Creates a new ranking rule.
Delete this rule | Deletes the current rule.

Rule properties: "Rule" tab

Field | Description
Site | Choose the site on which the rule is to be effective. The rule will not be applied to search results on other sites.
Module The module (in fact, content disposition) to which the rule is applicable. The following content is supported:
  • static files. The rule scope is limited by the full path to a file specified in the parameter 3;
  • information blocks. The scope can be: information block type; information block; information block element. You can create a rule without setting a specific type, information block, or element. In this case, the rule will be applied to all types and elements of all information blocks.
  • forums. The scope can be: forum, forum thread, or a specific message. If none of these parameters are specified, the rule will be applied to all messages of all forums.
Parameter 1 First ranking parameter. Meaning depends on content disposition:
  • static files - not used;
  • information blocks - the information block type;
  • forums - the forum name.
Parameter 2 Second ranking parameter:
  • static files - not used;
  • information blocks - the information block;
  • forums - the forum thread.
Parameter 3 Third ranking parameter:
  • static files - file name;
  • information blocks - the information block element;
  • forums - the forum message text.
Custom rank | The ranking rule weight (sort index). Defines the order in which documents matching the rule criteria are positioned in the search result list. The less is the weight, the higher is the position.

Control buttons

Button | Description
Add | Confirms the creation of a new rule and opens the list of rules.
Save | Saves changes and opens the list of rules.
Apply | Applies the changes performed.
Cancel | Discards the changes performed and opens the list of rules.


Site reindexing

You may need to manually re-index if you use some non-standard facility to change files of the site. For example, you have to manually re-index site files after you have uploaded files via FTP. New pages will not be displayed in the search results until you recreate the search index.

In this form you can specify the processing parameters and recreate the search index.

"Reindexing" tab

Field | Description
Re-index modified content only | Check this box to re-index files only with timestamp other than that stored in the database.
Maximum size of the document to index | Limits the size of an indexed document. You can limit the file size if you have files of large size and the server has not enough processing power.
Stepwise indexing | This option enables the phased indexing. You can check this option if there are lime limit on script execution. If the indexing script cannot finish successfully during the allocated amount of time, the system will run it again and again until the site becomes fully indexed.
step | Amount of time, in seconds, to elapse between index steps.
Site | The site whose documents are to be indexed.
Module | This list allows to select the area to re-index. You can re-index all the site, only static files; only information blocks or forums.

Click Re-index site to start re-indexing.


Google Sitemap

The Google Sitemap is a new while very comprehensive tool used to dispatch information about site pages to the Google database. Google Sitemaps are particularly essential when used with dynamic sites whose pages are generated automatically since it ensures that the Google database will have the complete information about all site pages. In its core, the Google Sitemap is an XML file. Despite the fact that the file format is simple, creating a Google sitemap is a tedious task taking much time. This form will help you create your sitemap.

Sitemap properties: "Google Sitemap" tab

Field | Description
Site | The site for which the sitemap is required.
Stepwise operation | If your server experience excessive load, you may want to enable this option. In this case, your sitemap will be created in several steps.
Step duration | Duration of a each step, in seconds.

Click Create Sitemap to create the sitemap.

Warning!
During processing, all the files matching "sitemap_*.xml" in the root folder of the chosen site will be overwritten.

When the sitemap is ready, you will see brief instructions on how to dispatch your sitemap to Google, as well as the path to the sitemap.


Settings (Search) - Bitrix Site Manager - Content Management & Portal Solutions

Settings

The Search module functionality can be customized using the system settings form (Settings -> Search module). This form also offers interface for manual re-indexing of the site.

Context bar

Button | Description
Re-index site | Opens a form in which you can recreate the search index.
Google sitemap | Opens a form where you can create a site map for use with Google.

"Settings" tab

Include files
This field define wildcards that will be matched against file pathnames before they are indexed. If a file pathname matches at least one of the wildcards, it will be indexed. Otherwise, such a file will not be indexed.
Exclude files
Files with pathnames that match at least one of these wildcards will not be indexed.
Enable using of morphology
Activates the morphological search engine. If enabled, the index and search will consider all word forms. For example, the system will consider such form of go as goes, went, gone etc., and children for child.
Symbols that are not used as word delimiters...
The morphological search algorithm splits sentences into words using the common delimiters (space, full stop, comma etc.) At the same time, there are symbols which are not letters but may be parts of words: for example, dash (-). Specify here symbols which the morphological analyser must treat as constituents of words.


Currency module - Bitrix Site Manager - Content Management & Portal Solutions

Currency module

Undoubtedly, the on-line store on your site sells foreign goods. As a rule, the price for such items is calculated using the purchasing price. The latter is usually set in a foreign currency. However, the legislation requires that calculations of all trading operations be accomplished in the home state currency. The Currency module is used to simplify operations with such items and their prices.

The Currency module is designed to manage currencies and their exchange rates. This module is required for the proper functioning of the trade catalogues and on-line store modules.

The system allows you to flexibly manage currencies in the system. The list of currencies is defined by the site administrator. Face-values, exchange rates (they can be loaded from the Internet) and the display format for every site can be specified for each currency.


Currencies - Bitrix Site Manager - Content Management & Portal Solutions

Currencies

In this section

  • Context bar
  • List of currencies
    •

    The Currency form (Settings -> Currency -> Currencies) is designed to manage currencies in the system. Currencies are used in the system for the proper operation of the online store.

    Note!
    The store will not function until at least one currency is set in the system.

    Context bar

    Button | Description
Currency rates | Opens a form containing rates of each currency for each date.
Add new currency | Opens a form in which you can create a new currency.
Excel | Exports data from the table to the MS Excel format.

    List of currencies

    Column | Description
    Checkbox column | Selects currencies to which the desired actions or rules are to be applied.
    Action menu
             Actions on a currency:
    • Edit - edits the currency;
    • Delete - deletes the currency.
    Sort | The currency sort weight. Defines the currency position in lists.
    Currency | The 3-symbol currency abbreviation (for example: RUR, EUR, USD).
    Name | The full name of the currency.
    Face-value | Face-value, or quantity of currency units, for which the exchange rate is set. Usually it equals the face-value set by the Central Bank. For most currencies the face-value is 1 (for instance, 26.9 RUR for 1 USD). Some currencies, however, will have a different value (for instance, 23.20 RUR for 100 JPY).
    Default rate | A currency rate which will be used for conversion of currencies in case other rates are not defined in the Currency rates form.


Creating and editing currency properties

In this section

  • Context bar
  • Editing form
  • Control buttons
    •

    This form helps create a new currency or set the parameters of an existing one.

    Context bar

    Button | Description
List | Opens a form containing the list of currencies.
Create | Creates a new currency in this form. The button is displayed when editing the existing currency only.
Delete | Deletes the currency being edited.

    Editing form

    Field | Description
*Currency | Contains the 3-symbol currency abbreviation (for example: RUR, EUR, USD).
Face-value | Face-value, or quantity of currency units, for which the exchange rate is set. Usually it equals the face-value set by the Central Bank. For most currencies the face-value is 1 (for instance, 26.9 RUR for 1 USD). Some currencies, however, will have a different value (for instance, 23.20 RUR for 100 JPY).
*Default rate | A currency rate which will be used for conversion of the currency in case no other rate is specified in the Currency rates form for this currency. The rate of the base currency equals 1. For other currencies, the rate is specified relative to that of the base currency. That is, the Default rate field of a newly added currency must contain the amount which is fixed for it in the base currency. For example, if you set the rate of RUR to 1, then the USD rate can be set to 27.6, and the EUR rate to 34.2. See also: Currency rates.
Sorting index | The currency sort weight. Defines the currency position in lists.
Currency settings for the site
Name | The full name of the currency for this site.
Format template | Specifies the format for displaying sums in this currency. After selecting the template in the drop-down list, all the below fields will contain the default values. You can change the values of these fields if needed.
*Currency format string | Specifies the format for displaying sums in this currency. All symbols of the format string are displayed as they are, except for the "#" symbol. When displayed, this symbol is replaced with the real sum (for example, the format string "USD # for 1 item", will be displayed as "USD 210 for 1 item"). The display format depends on the values in the fields described below.
Decimal point in output | The symbol separating the integer and fractional parts of a number.
Thousand separator in output | The symbol separating the thousands of a number. Note for developers Hexadecimal values can be used to print separators, for example: \xA0.
Number of decimal digits | The number of digits in the fractional part of a number (e.g. cents for USD).

    * - Required fields.

    Control button

    Button | Description
Save | Saves the currency parameters. Opens the page with the list of currencies.
Apply | Saves the currency parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Currency exchange rates - Bitrix Site Manager - Content Management & Portal Solutions

Currency exchange rates

In this section

  • Filter
  • Context bar
  • List of currency rates
    •

    The Currency exchange rate (Settings -> Currency -> Currency rates) form is used for managing the currency exchange rates. This form helps you easily maintain the list of exchange rates for all the required dates; that is, you can keep a log file of the currency exchange rates. This information can help you later, for example, when reviewing orders for the specific period.

    When converting currencies for a current date, the system takes the newest exchange rate. If the rate is not found, the default rate will be used (from the Currency form).

    Filter

    The filter is used to set the parameters for selecting the exchange rates to be displayed in the list.

    Field | Description
Currency | Defines whether to display all currency exchange rates in the list or only rates for the selected currency.
Date | Range of dates for which the exchange rates are to be displayed. You can choose a number of days starting from the current one or set the range of dates by using calendars.

    To filter the exchange rates by the specified search criteria, click Set filter. To display all exchange rates, click Cancel.

    Context bar

    Button | Description
New currency rate | Opens a form in which you can create a new currency rate.
Excel | Exports data from the table to the MS Excel format.

    List of currency rates

    Column | Description
    Checkbox column | Selects currency rates to which the desired actions or rules are to be applied.
    Action menu
             Actions on a currency rate:
    • Edit - edits the currency rate;
    • Delete - deletes the currency rate.
    Currency | The currency for which the rate is fixed.
    Date | The date for which the rate is fixed.
    Face-value | Amount of the currency unit (see also Currencies).
    Rate | The exchange rate of this currency, relative to the base currency.


Creating and editing the exchange rate

In this section

  • Context bar
  • Editing form
  • Control buttons
    •

    Context bar

    Button | Description
List | Opens a form containing the list of currency rates.
Create | Creates a new currency rate in this form. The button is displayed when editing the existing rate only.
Delete | Deletes the rate being edited.

    Editing form

    Field | Description
ID | The ID of the currency rate.
*Date | The date for which the rate is fixed.
Currency | The currency for which the rate is fixed.
Face-value | Amount of the currency unit (see also Currencies).
*Rate | The exchange rate of this currency, relative to the base currency. The Query button retrieves the exchange rates for the specified date from the Internet.

    * - Required fields.

    Control buttons

    Button | Description
Save | Saves the currency parameters. Opens the page with the list of currency rates.
Apply | Saves the currency rate parameters. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Localisation - Bitrix Site Manager - Content Management & Portal Solutions

Localisation

All messages (table headers, hyperlinks, button text etc.) used in Bitrix Site Manager are stored in special files. For easier localisation of these files, the product includes the Localization module.

The distribution package contains the full set of files for the Russian and English languages.

A language file is a file located in the /lang/ directory. This directory can be located at any place of the site directory tree. The language ID is defined once on the page /bitrix/admin/lang_edit.php.

A language message is a group of phrases meaning the same in different languages. Each language message has its own ID.

Example of a message

Parameter | Value
The language message ID | MAIN_VERSION
Text in English | The Bitrix Site Manager Version
Text in German | Die Bitrix Site Manager Version


Translation of language files - Bitrix Site Manager - Content Management & Portal Solutions

Translation of language files

The Interface localization page (Settings -> Localization) displays the structure of directories containing language files in the order they are located on the disk. To navigate it, you can use links on the names of directories, and the navigation chain located under the page title.

For each folder or file, you can see the statistics of the translated and untranslated phrases. The number of untranslated phrases of corresponding language is displayed in red, for example:

Click the link on a language file to open a page where you can edit this language file.


Translating messages

In this section

Context bar
Form fields
Control buttons

This page displays language messages for English language as well as for languages whose encoding coincides with the current page encoding. The current page encoding depends on the current language which you can change by clicking the appropriate button in the administration toolbar.

An encoding can be assigned to a language on the Edit language page (Settings -> System settings -> Interface languages), which can be opened by selecting Modify in the Action menu of the required language.

You can edit language messages of the displayed languages, and delete messages of all languages by clicking Delete.

Context bar

Button | Description
List | Opens the list of language message files.
Show all messages / Show untranslated messages only | Click the button if you want either all messages to be displayed, or only untranslated ones. The default display mode is set in the module settings.

Form fields

Field | Description
File name | The name of the language message file.
Total messages | Number of language messages in the file.
Untranslated | Number of untranslated messages for each language.
Messages
ID | The message language ID.
Delete | Check Delete and click the Apply button to delete a language message.
language | The language message text for each language. In the source messages, you can find templates like "#ID#" and "#COUNT#". If the original text contains such templates, the translated text should contain them. When the system uses the message, templates are automatically replaced with specific values. The use of any PHP commands in language messages is prohibited. However, you can use all HTML-tags.

Control buttons

Button | Description
Save | Saves the language messages. Opens the page with the list of language messages.
Apply | Saves the language messages. Editing continues.
Cancel | Cancels current changes and restores parameters to their original values.


Settings - Bitrix Site Manager - Content Management & Portal Solutions

Settings

This form (System settings -> Settings -> Translation) serves to set the system parameters of the Localisation module.

"Settings" tab

Field | Description
Initial folders | Comma-separated directories to be scanned for the presence of language files.
By default, show only errors when editing | When editing a file, check this field if you want only untranslated phrases (errors) to be displayed. Uncheck this field if you want all phrases to be displayed. To change the display mode, click the appropriate button on the form of editing phrases.

"Access" tab

This form allows to customise access rights of all user groups, except administrators who always have the full access. Moreover, by editing the default access level you can easily change access policies for all users that have the default permission.

Field | Description
By default | Controls the access permission of user groups having the default permission.
[Group of users] Controls the specific access permission of user groups. The following access levels are possible:
  • denied - access denied;
  • read all module data - access to view files but not modify them;
  • write - access to view and edit files.


Sites - Bitrix Site Manager - Content Management & Portal Solutions

Sites

In this section

Context bar
List of sites

This form (Settings -> System settings -> Sites -> List of sites) is used to manage sites in the system. You can add or delete sites here, activate or deactivate them.

Each site can be located either in a separate folder or even on other hosting location. You can get more detailed information in Multiple Sites Support.

Context bar

Button | Description
Add site | Opens a form in which you can create a new site.
Excel | Exports data from the table to the MS Excel format.

List of sites

Field | Description
Checkbox column | Used to select sites to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any site opens a menu allowing to:
  • Edit - opens a form in which you can edit the site parameters;
  • Copy - duplicates the site;
  • Delete - deletes the site.
ID | The system ID of the site.
Active | Indicates the site is active. Inactive sites cannot be viewed (they become unavailable).
Sort | The site sort weight. Defined the site position in lists.
Name | An arbitrary site name.
Folder The path to the site folder. The system kernel allows the following URL types to identify sites:
  • relative (/fr/, /en/) - for different site mirrors of the same domain name controlled by a single system;
  • absolute root (www.site.com) - for different sites controlled by a single system;
  • absolute (www.site.com/en/) - for isolated mirrors and/or sites controlled by a single system.
Default | The site that is chosen as default. The system open the default site whenever a visitor tries to view the site by its domain name (www.site.com).


Creating and editing a site (site properties)

In this section

Context bar
Editing form
Controls

Context bar

Button | Description
List of sites | Opens a list of sites.
Create new site | Creates a new site in this form.
Copy site | Creates a new site by duplicating the currently edited site.
Delete site | Deletes the currently edited site.

Editing form

Fields | Description
ID | The site ID. A site identifier is a two-letter abbreviation, e.g. ru, en.
Active | Indicates whether the site is active or not. Inactive sites cannot be viewed (they become unavailable).
Name | The name of the site.
Parameters identifying a site in the public section
Default | If checked, the site is the default. The system open the default site whenever a visitor tries to view the site by its domain name (www.site.com).
Domain | One or more domain names of the site.
Site folder The path to the site folder. The system kernel allows the following URL types to identify sites:
  • relative (/fr/, /en/) - for different site mirrors of the same domain name controlled by a single system;
  • absolute root (www.site.com) - for different sites controlled by a single system;
  • absolute (www.site.com/en/) - for isolated mirrors and/or sites controlled by a single system.
Sorting index | The site sort weight. Defined the site position in lists.
Parameters
Language | The language used to display text context of the site.
Date format | The short date format used by this site, e.g. DD.MM.YYYY.
Date-time format | The long date format (including time) used by this site, e.g. DD.MM.YYYY HH:MI:SS.
Encoding | The page encoding used by this site. The value defines the encoding type with which the page text is to be rendered. The encoding depends on the language chosen.
Site name | The arbitrary site name.
Server URL | The URL of the server on which the site runs. Used in mail messages to identify sender (e.g. for automated messages).
Default e-mail address | The default sender address. Used in the From field.
Path to the web server root folder of this site The path to the web server root folder of this site. Clicking the link insert current inserts the current root folder path.

If all sites run on a single web server, leave this field blank.
Create e-mail templates With this field, you can create e-mail templates which will be used to generate e-mail messages:
  • don't create - no templates need to be created;
  • link to existing site templates - allows to use templates of one of currently existing sites;
  • copy from site templates - create new templates by copying templates of one of currently existing sites.
Templates
This section allows to define conditions which will stipulate the use of site design templates in different situations.
Field | Description
Template | Shows available site templates. Click the button [image] to preview the desired template.
Sort | The condition sort weight. Defined the position of the condition in this list, thus affecting the order in which conditions are applied.
Condition type The type of condition which, when true, will cause the corresponding template to be applied:
  • File or folder: a page or section for which the template will be used;
  • User group: one or more user groups for whom the site appearance will be directed by the respective template;
  • Time period: the date or a date range during which the site will be displayed using the respective template;
  • URL parameter: a parameter in URL which, if present, will cause the respective template to be applied;
  • PHP expression: arbitrary expression in the PHP language.
Condition The condition itself. Depends on the selection in the previous field.

Note
Leave this field blank to make the template applied by default.

Controls

Button | Description
Save | Applies changes performed on this page and switches to the list of sites. Displayed when editing an existing site.
Apply | Applies changes performed on this page without switching to the list of sites.
Reset | Cancels current changes and restores parameters to their original values.


Site templates - Bitrix Site Manager - Content Management & Portal Solutions

Site templates

In this section

Context bar
List of templates

This form (Settings -> System settings -> Sites -> Site Templates) is used to manage design templates which are the base to display the dynamic contents of the site. Using this form, you can create, edit and delete templates.

Context bar

Button | Description
Add template | Opens a form in which you can create a new site template.
Load template | Opens a form in which you can load (import) a template to the system.
Excel | Exports data from the table to the MS Excel format.

List of templates

Field | Description
Checkbox column | Used to select templates to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any template opens a menu allowing to:
  • Edit - opens a form in which you can edit the template;
  • Copy - duplicates the template;
  • Delete - deletes the template.
ID | The template system ID.
Name | Arbitrary template name.
Description | The template description.


Site template properties

In this section

  • Context bar
  • Template editing form
  • Template
  • CSS file
  • Additional files
    •
  • Controls
    •

    Context bar

    Button | Description
List of templates | Opens a list of site templates.
New template | Creates a new site template in this form.
Copy template | Creates a new site template by duplicating the currently edited one.
Delete template | Deletes the currently edited site template.

    Template editing form

    "Template" tab
    Field | Description
ID | The template identifier. Must not contain other letters than Roman. A string in brackets is the path to a folder containing the template. Note: a new template is created in the folder /bitrix/templates/template_ID.
Name | Arbitrary template name.
Description | The template description.
Site template design
This field is the text editor containing the template code. The macro #WORK_AREA# demarcates the top and bottom parts of the site design. This is where the page body resides.
    "CSS file" tab
    CSS file
    This field is the text editor containing styles used by the template. The file itself is stored in /bitrix/templates/template_ID/styles.css.
    "Additional files" tab
    Additional files
    This tab displays extra files used by the template (images, menu templates etc.).
    • Modify - edits the corresponding file;
    • Add include file - opens a form in which you can create a new file for use with the template.

    Controls

    Button | Description
Save | Applies changes performed on this page and switches to the list of site templates. Displayed when editing an existing site.
Apply | Applies changes performed on this page without switching to the list of site templates.
Reset | Cancels current changes and restores parameters to their original values.


Importing templates

In this section

Form fields
Controls

The Importing templates form is used to load the prepared site templates into the system.

Form fields

Field | Description
Template file | Click Browse to select a g-zipped template file to be imported.
Template ID | After the upload completes, the template archive will be decompressed and stored in a folder with the same name as the archived file. For example, if you upload a file template1.tar.gz, the template will be stored in /template1/, and will have the ID of template1. If you prefer to give the template and the storage folder another name, specify it in this field.
Make template default for the site | In this field you can select a site for which the new template will become the default.
Edit after import | If checked, the new template will be opened for editing right after the import operation completes.

Controls

Button | Description
Upload | Uploads and import the selected template.


Languages - Bitrix Site Manager - Content Management & Portal Solutions

Languages

In this section

Context bar
List of languages

One of the noticeable Bitrix Site Manager features is the support for unlimited number of user interface languages. You can:

  • enjoy the multi-language administration interface;
  • create as many sites as you need in different languages with a single installation of the system. A public section of each site has its own set of language preferences.

The system languages define how the system text messages can be rendered: table captions, error messages, control titles etc.

You can choose the desired administration interface language using the top toolbar buttons:

Developers will find the exhaustive information on system languages and interface here: Languages for developers.

Context bar

Button | Description
Add language | Opens a form in which you can create a new language set-up.
Excel | Exports data from the table to the MS Excel format.

List of languages

Field | Description
Checkbox column | Used to select languages to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any language opens a menu allowing to:
  • Modify - opens a form in which you can edit the language settings;
  • Copy - duplicates the language profile;
  • Delete - deletes the language profile.
ID | The system language ID.
Active | Indicates whether the language is active or not. The system messages and textual UI parts cannot be rendered in an inactive language.
Sort | The language sort weight. Defined the language position in lists.
Name | Arbitrary template name.
Default | Indicates the default language. When a visitor enters the site, all the text messages are rendered in the default language.


Editing language settings - Bitrix Site Manager - Content Management & Portal Solutions

Editing language settings

In this section

Context bar
Editing form
Controls

This form is used to set parameters of the language. After you have made any modifications, remember to save changes by clicking Save.

Context bar

Button | Description
Languages | Opens a list of site language profiles.
Add language | Creates a new language profile in this form.
Copy copy | Creates a new language profile by duplicating the currently edited one.
Delete language | Deletes the currently edited language profile.

Form fields

Field | Description
ID | The system language identifier.
Active | If checked, the language is active. The system messages and textual UI parts cannot be rendered in an inactive language.
Name | The name of the language.
Default | If checked, this language will be used to display text messages unless any other language is selected.
Sort index | The sort weight used to display the language in lists.
Date format | The short date format for this language.
Time format | The long date format for this language (includes time).
Encoding | The page encoding for use with this language.
Text orientation Specifies the language reading order:
  • Left to right - content flows from left to right;
  • Right to left - content flows from right to left.

Controls

Button | Description
Save | Applies changes performed on this page and switches to the list of site language profiles. Displayed when editing an existing language profile.
Apply | Applies changes performed on this page without switching to the list of site language profiles.
Reset | Cancels current changes and restores parameters to their original values.


e-Mail message templates - Bitrix Site Manager - Content Management & Portal Solutions

e-Mail message templates

In this section

Context bar
List of message templates

This form can be accessed by selecting Settings -> System settings -> e-Mail templates in the left menu of the administration section.

The e-Mail message templates form is used to manage mail message templates. Whenever a message is to be sent, the system searches for the appropriate template that can be used to create an e-mail message. If a template is found, a message is sent using this template.

The system distinguishes e-mail message templates by the message type and the site with which a template can be used.

Each message template may contain two types of information: constant data and variable information (parameters).

The constant data remain static in all messages and do not change. In other words, all recipients will receive this information exactly as you provide it in the message template. Example of constant data is signature, e.g. "Best regards" etc.

The parameters can vary from message to message depending on conditions. This means that a recipient will receive information that is intended for him or her, exactly. Example of a variable parameter is the recipient's e-mail address. The parameters which can be used in a message are listed in the template editing form in the Available Fields section.

Developers can find more detailed information on the mail message subsystem can be found in section Messaging subsystem.

Context bar

Button | Description
Add template | Opens a form in which you can create a new e-mail template.
Excel | Exports data from the table to the MS Excel format.

List of message template

Field | Description
Checkbox column | Used to select e-mail templates to which the desired actions are to be applied. Available rules and actions can be found in the action bar below the table.
Action menu
Clicking the action button of any e-mail template opens a menu allowing to:
  • Edit - opens a form in which you can edit the e-mail template;
  • Add copy - duplicates the selected e-mail template;
  • Delete - deletes the e-mail template.
ID | The system template ID.
Modified | The date and time the template was last modified.
Active | Indicates whether the template is active or not. Inactive templates are not used for generating a-mail messages.
Site | The site for whose messages the given template can be used.
Event type | The name of the event type which, when occurred, causes a message to be generated using the given e-mail template.
Subject | The e-mail message subject as will be seen in the Subject e-mail message field.

Developers will find more details about e-mail templates in the Mail subsystem section.


Creating and editing e-mail message templates

In this section

Context bar
 Form fields
Controls

This form is used to create and edit e-mail message templates.

Context bar

Button | Description
Templates | Opens a list of all existing e-mail message templates.
Add template | Creates a new e-mail message template in this form.
Copy copy | Creates a new template by duplicating the currently edited one.
Delete language | Deletes the currently edited template.

Form fields

Fields marked with ** can contain macros from the Available fields section.

Field | Description
Last update | The date the template was last modified.
Active | If checked, the template is active. Inactive templates are not used for generating a-mail messages.
Site | The site(s) for whose messages the given template can be used.
Event type | The code and name of the event type which, when occurred, causes a message to be generated using the given e-mail template.
From** | The message sender address.
To** | The message recipient address.
BCC** | The addresses of recipients who will receive the message as BCC.
Subject** | The e-mail message subject as will be seen in the Subject e-mail message field.
Message body type The message body format:
  • Text - plain text;
  • HTML - specifies the use of HTML to create and send messges.
Message body**
Create the message here.
Available fields
This section contains macros which can be used in fields marked with **.

For example, the From field may contain the #DEFAULT_EMAIL_FROM# macro. This will insert the default e-mail address specified in the site or maim module settings.

Controls

Button | Description
Save | Applies changes performed on this page and switches to the list of templates. Displayed when editing an existing template.
Apply | Applies changes performed on this page without switching to the list of templates.
Reset | Cancels current changes and restores parameters to their original values.


Modules - Bitrix Site Manager - Content Management & Portal Solutions

Modules

This form can be accessed by selecting Settings -> System settings -> Modules in the left menu of the administration section.

The Modules form is used to install and uninstall system modules. The system allows you to uninstall modules which you do not need or expect to be not in use. For example, if you do not need the Workflow module, you can uninstall it to free up resources and place in menu. You can always install it later.

Please note that some modules have an option to keep (not delete upon uninstall) their private data. If you plan to use the module later, you should check corresponding option when performing uninstall.


Settings - Bitrix Site Manager - Content Management & Portal Solutions

Settings

In this section

  • Module settings form
  • Settings
  • Authorisation
  • Update system
  • Access
  • Controls
    •  Service routines
  • Clear cache files
  • Public section
    •

    • The Settings form is used to customize global settings of the system as well as the individual module. It can be accessed by selecting Settings -> System settings -> Module settings -> Main module -> in the left menu of the administration section.

    Settings of other modules are module-dependent and described in the corresponding sections.

    Module settings form

    "Settings" tab

    This form (tab) provides interface for customizing the main parameters of the module.

    Field | Description
E-mail address(es) to receive copies of outgoing mail | All e-mail messages sent from the site will be also sent to this address.
Send e-mail event and template identifiers in messages | Each e-mail message will contain information that uniquely identifies it.
Duplicate e-mail address in header | Check this option if messages sent from the site do not contain field TO.
Site administrator e-mail | The address which will be used as the sender address when sending messages.
Convert newlines from UNIX to Windows format | If checked, all new lines will be converted from UNIX to Windows format (CR+LF).
Convert 8-bit characters in the message header | Enable this option if symbols with codes higher than 127 (i.e. 8-bit) are displayed incorrectly in the message header. This will cause such symbols to be encoded using base64.
Site name | The default site name. Can be overridden in the site settings.
Site URL | The site web address (without http://). Can be overridden in the site settings.
Cookie prefix | The string which will be placed at the beginning of the cookie name.
Default upload folder | The folder where all uploaded files (e.g. images) will be stored.
Send status 200 in header to error 404 | If checked, any error request will cause the OK status (202) instead of 404 (Not found).
Type of menu for zero level of site map | The name of the menu type whose items will be used to render the site map nodes.
Type of menu for other levels of site map | The name of the menu type whose items will be used to render the site map branches and leaves.
Error report mode | Defines which errors to display (useful for debugging purposes).
Spread cookies to all sites | Denotes that all domains will use common cookies. Used with the following modules: Statistics (Web Analytics), Advertising, Polls and Surveys, Forums. With this option, you can also enable the throughout authorisation on sites controlled by the same system.
Keep original names of uploaded files | If unchecked, files will lose their original names after they are uploaded to the site. Files will have names consisting of random alphanumeric symbols. If the option is enabled, folders with the random names will be created; uploaded files will be stored each in a separate folder. This allows to keep the original meaningful filenames, which can be useful for visitors when they want to download a file.
Replace invalid symbols in names of uploaded files | If the Keep original names of uploaded files box is checked, this option will replace all unsafe characters with random Roman letters. If this option is disabled, the system will not permit to save files having unsafe characters.
Default language of administrative section | Defines the default language which will be used to display the administrative section.

    "Authorisation" tab

    Field | Description
Allow visitors to self-register | If checked, site visitors are allowed to register.
Add to group upon registration | Group that a user will be automatically added upon registration.
Remember authorisation | If checked, a Remember me option will be showed in the authorization form.
Use secure cookie authorisation | Encrypts the identification information before it is stored in cookie.
Global authentication for all site domains | Enabling this option allows the throughout authorisation on all sites running on the same system. This means that, if a user authorises on one site, they will be automatically authorised on all other sites. This option requires enabling spread cookies to all sites.
Use CAPTCHA | Specifies that a special mangled text is to be entered at the registration time to prevent unauthorised registrations.

    "System update" tab

    Field | Description
License key | License key for this copy of the system.
Name of system update server | Name of the server used to download updates from (bitrixsoft.com).
Update proxy server | The address of the proxy used to access the update server.
Update proxy port | The proxy port.
Proxy user name | The user name for connection to the proxy server.
Proxy password | The proxy server password.
Check the integrity of update files | If enabled, a checksum will be calculated before the new downloaded files are copied to the destination folder from the intermediate folder (/updates/). If the sample and calculated checksums differ, an error message will display.
Download only stable updates | If checked, only the final releases of updates can be installed. Otherwise, allows to install beta updates.

    "Access" tab

    This tab configures the access permissions of user groups for the module.

    Field | Description
    Default | Specifies the default permission. This affects all user groups that have the default access permission.
    [User group] Changes the permission of a specific user group. The following access permissions apply to the e-Store module:
    • deny - any access is denied;
    • edit own profile - users can view and edit their profiles;
    • read-only - users can only view files and settings of the module;
    • read; edit own profile - users can only view the module files and edit their own profiles;
    • write - full access.

    Controls

    Button | Description
Save | Saves the performed changes.
Reset | Cancels current changes and restores parameters to their original values.
Restore defaults | Resets module settings to their default values.

    Service routines

    Clear cache files

    This form is used to delete cache files containing outdated or error information.

    Field | Description
Expired only | Specifies to delete only the expired information.
All | Erases all.

    Click Clear to perform clean-up.

    Public section

    With this form, you can lock your site (for example, during maintenance).

    Click the button to lock or unlock the site public section.


Site check - Bitrix Site Manager - Content Management & Portal Solutions

Site check

This form can be accessed by selecting System settings -> Site check in the left menu of the administrative section.

The Site check form provides means that a site administrator can use to thoroughly examine the parameters compliance of system used to run the Bitrix Site Manager. The form depicts information grouped by sections to facilitate perception. The following sections are available.

  • Required parameters - parameters critical for the system successful performance.
  • Disk access test - results of testing of physical disks for both reading and writing.
  • Recommended settings - these parameters are uncritical for the system successful performance but you have better set them to the recommended values.
  • Site modules - modules installed or available to be installed.

Send message to techsupport

Using this form, you can quickly contact the Bitrix technical support service. Please fill in the required fields and describe your problem thoroughly. Solution to most problems can be found much more promptly if you select to include in message information on the system kernel and PHP extensions. Such information is obtained by running the PHP function phpinfo(). It is strongly recommended to leave this option checked.


SQL query - Bitrix Site Manager - Content Management & Portal Solutions

SQL query

This form can be accessed by selecting System settings -> SQL query in the left menu of the administrative section.

The SQL query form can be used to execute an arbitrary SQL query to the database.

The syntax of an SQL query should conforms the SQL standard of the installed product edition. The MySQL edition presumes the use of the MySQL standard, whereas the Oracle edition expects queries in the Oracle standard.

IMPORTANT!
The system does not place any restrictions on your SQL queries. You must be extremely attentive when running statements like UPDATE, DELETE, DROP etc.


Update - Bitrix Site Manager - Content Management & Portal Solutions

Update

This form can be accessed by selecting System settings -> Update in the left menu of the administrative section.

Update system is used to update the system modules to the latest version as well as download new modules. Registered users only can download and install updates. Any updates affect the system kernel only (folder /bitrix/), public section remains untouched.

IMPORTANT!
If you have manually changed at least one of the kernel files (in folder /bitrix/ except files in folder /bitrix/php_interface/) or the database structure, automatic update can bring to unexpected results.

Module update involves 3 steps.

  1. The system displays a list of modules with the updates available. Select modules that you want to download updates for. If no updates are available, you have the latest versions of all modules.

    Selected modules will be downloaded to the temporary subfolder of the folder /bitrix/updates/.
  2. The system displays a list of downloaded module updates. Select modules that you want to update. If the Result column shows status other than Downloaded, try to download update(s) again.

    Selected modules will be updated. New modules will be copied to the system kernel.
  3. The system shows a list of updated modules. New modules display links to the module installation system.


Compression - Bitrix Site Manager - Content Management & Portal Solutions

Compression

At present, technology is developing progressively and offer yet more and more communication facilities. Low-speed devices used to work over the telephony cables (analogous modems) are now almost completely replaced with new science intensive solutions allowing to send immense information content at the speed of light: ADSL technology, fiber-optic and satellite networks. At the same time, many clients still use low-speed modems due to economy, simplicity of use or simply unavailability of modern solutions in their area. The Bitrix company always cares about your customers. This is why we have introduced page compression in our system, which allows to substantially retrench the amount of data transmitted from your site to a client. This technology is implemented in the Compression module.

The module compresses pages to speed up the data transfer from host to users. The module is able to decrease the amount of transferred HTML data by 4 to 20 times! This will appreciably increase the speed for both clients and site administrator.

The compression module has not customizable settings. You can estimate the efficiency by appending the parameter compress=Y to the URL in your browser. For example:

http://ourcompany.com/en/partners/catalog.php?BID=10&compress=Y

This will force the following table to display at the bottom of all pages:

Compression
Page size | 38695
After compression | 7375
Compress ratio | 5.25

Notes for developers
To estimate the page generation time, you can use the parameter show_page_exec_time=Y, which will cause the page generation time to display in the left bottom corner of a page (in contrast to transmission time).


LDAP

Introduction to AD/LDAP

Integrating a site in the corporate information system usually requires distributing team members’ permissions to access the site resources and management. A common solution to this problem is creating user groups with different access permissions applied to them and further adding users to these groups. In this case, an administrator may face a need to transfer the existing corporate user groups to the site management system (hereinafter referred to as CMS) to allow users to assess and manage the corporate site resources. This incurs doubling actions required to change access permissions or add a new user to both the corporate network and the CMS: the administrator has to create or edit a user profile in the corporate system as well as in the CMS.

This module enables to integrate the Bitrix Site Manager in the corporate networks built on Windows Server 2000 or 2003, Unix or Novell.

The AD/LDAP module is developed especially for use with the Bitrix Site Manager permits mapping corporate network user groups to those of the CMS. This allows to manage user groups of the corporate information system in the centralized fashion.

This manual describes the scope and implementation of the Bitrix Site Manager AD/LDAP module functions. An approach to set up the module and assign corporate user groups to those of the Bitrix Site Manager is also highlighted.


LDAP Functions

Functions

The AD/LDAP module has been developed with respect to LDAP (Lightweight Directory Access Protocol) and AD (Active Directory) standards.

The AD/LDAP module is built on the concept of storing data as records containing a set of attributes; these records are stored in a hierarchical database. The following figure illustrates how the user group information is stored on the LDAP/AD server:

Using this structure to store user data enables the AD/LDAP module to assign corporate user groups to the site user groups.

The assignment rules are specified in a special Assignment Table in the site administrative section. The assignment allows user groups of the site and the corporate network to have different names. For example, a corporate network user group Techsupport can be mapped to a site user group Techsupport stuff. Having this assignment made, the administrator enables the corporate network techsupport members to provide consultancy on the site.

The corporate user groups are given permissions to access the corporate network resources. The site user groups have permissions to access the site resources. For example, the Techsupport group users can access the corporate mail server; while the Techsupport stuff group users can access the Helpdesk module of the site.

According to this example, a Techsupport corporate user will be automatically added to the site Techsupport stuff user group upon successful authorization on the site. After that, the system automatically creates the user account stored on the corporate server.

A user can assigned to one or more user groups. The system may contain user groups not mapped to those of the corporate network. The administrator has to add users to such groups manually. All changes made to the user profile within the corporate server will be automatically transferred to the CMS user profile at the time of subsequent authorization. In this case, only the user groups mapped to those of the corporate network are updated.

The AD/LDAP module enables to:

  • integrate the Bitrix Site Manager CMS in the corporate network;
  • map the corporate network user groups to the site user groups;
  • automatically create a user profile as per the Assignment Table upon successful registration. (The system creates the profile using data requested from the corporate server database);
  • centrally manage user profiles via the corporate server.


LDAP: how it works

A common AD/LDAP module operation is as follows.

  1. A user opens the site and authorises. This implies typing the login and password used to authorise in the corporate network.
  2. The system connects to the server specified in the AD/LDAP module settings and verifies whether a user with the supplied credentials exist in the corporate server database:
    1. if no user with the supplied credentials exists in the corporate network, the system searches for this user in the Bitrix Site Manager database. If the user still cannot be found, the system declines authorization;
    2. if the user is found, the system determines the corporate network user group for this user. After that, the system searches for the site user group using the Assignment Table.
  3. The system verifies whether the user profile exists:
    1. if the user profile is not found, the system attempts to obtain the user data from the corporate server and then creates a new profile;
    2. if the user profile exists (which means a user had previously been authorised), the system checks whether any change has been made to the user profile on the corporate server. If so, the CMS user profile becomes updated to reflect changes.
  4. The user is granted permission to access the site resources and becomes authorised. The user permissions are defines as per his user group settings.

Note

A site user who is a member of any group or groups registered in the Assignment Table may be deleted from the corporate network user list. In this case, if the user attempts to authorise on the site, the authorisation attempt will fail. At the same time, the user profile is still stored in the CMS database.

To allow the user authorise on the site via the common interface, enable the authorisation internal check. To do so, set the value of the field Authorisation type to “internal check” in the administrative section and then update the user credentials (login and password).


Customizing the AD/LDAP module

You can adjust the module settings via the site administrative interface. A common set of customization operations include creating a record containing information about the corporate server whose database will be used to match user groups; setting parameters of the server schema and user group mapping.

Each record regulates access to a folder tree root. If the corporate network user groups are stored on several servers or in several databases on a single server, you should create a separate record for each storage point.

  1. Go to the list of Active Directory / LDAP servers (Administrative section -> AD / LDAP -> Servers)
  2. Click Add to open the new record creation form.
    1. The first group of controls are used to specify information about the corporate server as well as the database connection settings.

      The following is the description of the group settings.

      • Active: if this box is checked, this record is included in the user profile lookup when a user attempts to authorise. Otherwise, this record is ignored.
      • Name: the name of the record to be created as it will be shown in lists.
      • Description: type here the server description.
      • Mnemonic code: specify any mnemonic name for the new record. The mnemonic name can be used as the authorization prefix:

        <mnemonic_code>\<user_login>

        The prefix specifies the record that should be used to search for a user profile on the corporate server. This is useful when, for example, a corporate network user has common authentication credentials (login and password) and several profiles stored on different servers. In this case, the mnemonic name defines a record specifying the server and the catalogue tree root in which the system will search for the user profile to be user for authorisation. The mnemonic code can contain only Latin letters.

      • Server:port: the IP address and the port of a corporate server hosting the user group database. The port 389 is the technology standard to access an LDAP server.
      • Administrative login: login for administrative access to the server.
      • Administrative password: password for administrative access to the server.
      • Check: click this button after you have specified all required information. This will try to establish a trial connection to the server. If the check succeeds, the server should return a list of available tree roots. If the check fails, the page will display the error description in red.
      • Root: this field is used to select the catalogue tree root to be used for the user profile lookup when authorising.
    2. The Server schema group defines parameters of the user profiles stored on the server. The controls of this group are initialised with the standard values for LDAP or AD servers.
      • You can select the server type by clicking on the corresponding link in the section title.
      • If the corporate server overrides standard settings, the values in this group should be altered to reflect the server settings.
    3. The User Group Mapping section is used to load the corporate user groups and the site user groups in the Assignment Table and specify group mapping.
      • Click Refresh Group List to add more user groups to the table. This will also verify parameters specifies in other sections.
      • After the list is refreshed, this section will display the Assignment Table. The table entries are drop-down lists.
      • In the Remote server group column, select a corporate network user group. In the Remote server group column, select a site user group that would match the selected corporate network user group. Thus, a single table row contains the corporate network user group and the matching site user group.
      • To delete a row from the table, check the Delete box and click Apply.
      • You can add more rows to the table by clicking More.
  3. Click Save to save changes and go back to the list of servers. Saving a record adds it to the list of servers on the page Active Directory/LDAP servers.

To edit or delete a record, click the appropriate link in the Action column.


Overview

This section is aimed to developers and administrators with the knowledge of PHP and HTML. The section contains overviews and descriptions of technologies on which the Bitrix Site Manager is built, descriptions of the Kernel (main) module classes and functions.

In this section

  • Kernel settings - summary of system settings available to site administrators.
  • Technology Review - highlights upon technologies and architecture of the system.
  • Classes and functions - contains descriptions of classes and functions.


Technology Review

This section provides general information on the technologies and architecture on which the system is built.

  • Terms - contains the glossary of main terms used in the Kernel developer's guide.
  • Structure of system files and folders - contains the description of the system files storage structure.
  • Access permissions - describes the access permission distribution ideology.
  • Special constants - summarizes special constants used in the system.
  • Special variables - summarizes special variables used in the system.
  • Date and time - examples of common date and time operations.
  • Navigation chain - depicts the use of navigation chain.
  • Menu - describes the menu handling.
  • Technology - describes the main technologies implemented in the system.
  • Modules - contains the description of the modular architecture; highlights the main points of custom module development.
  • Sites - depicts the multiple site configuration architecture.
  • Languages - explains principles of translation of the system scripts into other languages.
  • Pages - depicts the page structure.
  • Components - delineates main principles of components handling.


Terms

List of Terms
A
  • Absolute path
  • Accept-Language
  • Administrative section
    •
    B
  • Binding of variable
  • Buffering
    •
    C
  • Component
  • cron
    •
    D
  • DocumentRoot
  • Domain name
  • Dump
    • E
  • Epilogue
    • H
  • Host
  • HTML safe format
    •
    I
  • Include areas
  • Index page
  • IP address
    •
    L
  • Language file
  • Language
  • Localization
    •
    M
  • Mail event type
  • Mail event
  • Mail template
  • META tag
    •
    N
  • Navigation chain
    •
    P
  • Page body
  • Page template
  • Path relative to the root
  • Path to component
  • Persistent connection
  • Portal
  • Prologue
  • Public section
    •
    S
  • Session
  • Site section
  • Site template
  • Site
  • Submit
    •
    T
  • Time in Unix format
    •
    U
  • Unix permissions
  • User account
    •

    Term | Description
    Component A component is a module constituent which is built of logically complete code stored in a file. Component may accept parameters, perform actions and display a result (e.g. as the HTML code). Using components is the preferred way of information processing and display, both in public and administrative section. The notion of component comprises the following concepts:
    • main file - script which implements the component logic, written in PHP, included by calling CMain::IncludeFile;
    • language file - used in components to display the result in other languages;
    • description - the PHP code used by the HTML editor to visually manage the component and its parameters.
    Language Account in the database which can be edited using the Languages menu in the administrative section. Contains the following fields:
    • ID
    • Name
    • Date format
    • Time format
    • Encoding
    Both public and administrative sections mainly use language to handle language files.

    For the administrative section, language defines the date and time format, page encoding. For the public section, these parameters are defined by the site settings.
    Language file A PHP script containing phrase translations. This file contains the array $MESS whose keys are the phrase identifiers, and values are the phrase translations in the corresponding language. Each language has own set of language files usually stored in folders /lang/.

    Language files are mainly used by the administrative scripts of modules and by components.

    The Translation module offers a front-end for handling the language files.
    META tag | Conveys hidden information about the page to the server and the client. The META tag allows to specify page encoding, keywords, author name, short description. Service element; for example, used by search engine robots. Can be only used within the <head> tag.
    Navigation chain Navigation chain is the design element which aims to helps users navigate through the site.
    Usually displayed in the prologue visual section; consists of the site section titles with links applied to them. In addition to the automatically displayed section titles, you can add arbitrary items to a navigation chain by calling CMain::AddChainItem.
    Page template File stored in one of the following folders:
    • /bitrix/templates/site template ID/page_templates/
    • /bitrix/templates/.default/page_templates/
    This file is a kind of draft of a public page. Commonly used to create a new page in the HTML editor (the Site Explorer module). A file .content.php stored in one of the above folders, is used to define the page template sorting order.
    Site The aggregate of the following notions:
    • database account - created in the Sites administrative menu. Includes the following principal parameters:
      • identifier - a set of symbols which identifies a site;
      • domain name - one or more domain names of a site;
      • site folder - path to the folder containing the site public section;
      • site language;
      • date format;
      • time format;
      • URL - default protocol and domain name (e.g. "http://www.site.com")
      • DocumentRoot - if multiple sites is implemented using the method 2, this parameter should contain the server file system path to the site root;
      • template inclusion conditions - each site may have one or more templates used to display the public section scripts; each template may be included using a condition.
    • public section - a set of scripts (pages) which belong to this site and are stored in the site folder;
    • settings - each module may have site related preferences; for example, the Information Blocks module settings are associations between blocks and sites; the Techsupport module settings are associations between status, categories etc. and sites.
    Site template The synonyms of this term are "site design", "site skin". Several templates may be used to display a site. In the strict sense, a site template comprises:
    • database account - created in the administrative menu Site templates;
    • set of files in the directory /bitrix/templates/template ID/, where the template ID is the ID field in the site template editing form. The structure of this directory is described below:
      • /module ID/ - directory with components of a module;
      • /lang/ - language files used by this template and components;
      • /images/ - directory with images used by this template;
      • /page_templates/ - directory with page templates and their descriptions stored in file .content.php;
      • header.php - prologue of this template;
      • footer.php - epilogue of this template;
      • styles.css - CSS used by this template;
      • .menu type.menu_template.php - template used to display a menu of the corresponding type;
      • chain_template.php - default template used to display the navigation chain;
      • other helper files used by this template.
    Absolute path | Includes the DocumentRoot and the path relative to the root.
    Accept-Language The Accept-Language request-header field restricts the set of natural languages that are preferred in the client browser

    Example

    MS Internet Explorer     allows to set languages in Tools -> Internet Options -> General -> Languages.
    Mozilla Firefox: Tools -> Settings -> Main -> Languages.
    Administrative section A set of scripts each including the administrative prologue and epilogue. The administrative script (page) must conform to the following conditions:
    • the page must not be a part of any site;
    • the page must be a part of a module;
    • the page design should follow that of the Administrative section;
    • all localization parameters depend on the user selected language;
    • the page should perform additional checks of permission specified in the module settings.
    Binding of variable | Applicable to the Oracle SQL queries. Implies binding names of variables to their values. Usually, this technique is used with fields BLOB, CLOB, LONG etc. intended for storing huge amount of data.
    Buffering In PHP, the buffering means a special output mode when all outcoming data (e.g. HTML code) is stored in memory without the immediate dispatch to the output stream (that is, not sent to a client). The buffering can be turned on by calling the ob_start PHP function. When the buffering is turned off using the ob_end_flush PHP function, all the buffered data is sent (flushed) to the client browser.

    The buffering allows to manipulate the outcoming stream as desired; the delay function technology is built on buffering.
    cron | In the Unix family operating systems, the cron tool schedules and runs scripts.
    DocumentRoot Path to the site root within the server file system. Specified in the web server settings.

    Example:
    • Apache - in the file httpd.conf, parameter DocumentRoot;
    • IIS - in the site settings, tab Home Directory -> Local Path.
    Domain name One of the DNS table fields that stores information about host names and domain names. Most importantly, it provides an IP address for each host name.

    For example: www.bitrixsoft.com
    Dump When applied to databases, means exporting the database content (and/or table structure) to a file in a special format which may be used later for importing in this or another database.

    A set of specially designed utilities exists for each database type. For example, the MySQL tool mysqldump allows exporting the database content in the format of common SQL queries. The Oracle tool exp exports data in the proprietary format.

    When applied to variables, the dump implies displaying the structure and value(s) of a variable in the text format.
    Epilogue

    Generally, this term means bottom right part of a page.

    For the public section, the epilogue of the corresponding site template is stored in the file /bitrix/templates/site template ID/footer.php.

    For the administrative section, the epilogue is stored in the file /bitrix/templates/site template ID/footer.php.

    The epilogue in its turn can be split in the service and visual sections. The service section perform the following actions: sending e-mail messages, firing the OnAfterEpilog event etc. The visual section displays the bottom right area of a page.

    If an undivided epilogue is to be included in the public section, the following code should be used: require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");

    If a epilogue is to be split in the service (epilog_before.php) and visual (epilog_after.php) sections, the following code should be used: require($_SERVER["DOCUMENT_ROOT"]. "/bitrix/modules/main/include/epilog_before.php"); ... require($_SERVER["DOCUMENT_ROOT"]. "/bitrix/modules/main/include/epilog_after.php");

    HTML safe format This term is usually applicable to a text portion in which the following substitutions are made:
    Source | Result
< | &lt;
> | &gt;
" | &quot;
& | &amp;
    This conversion allows to display text within the HTML code, avoiding interpretation collisions within the browser HTML engine.
    Host | In terms of the Kernel module, a host is the domain name or IP address that a client may use to access a site.
    IP address The unique address for each computer on the Internet. The IP address appears as a set of four numbers separated by periods. The numbers indicate the domain, the network, the subnetwork and the host computer. Each IP address usually has an equivalent domain name address, which is spelled out with letters.

    For example: 198.63.210.79 (the corresponding domain name is www.bitrixsoft.com)
    Include areas | Arbitrary text (HTML code) which is the part of the page body. The control toolbar button Show include areas causes all include areas to be framed in a border with control buttons in the upper right corner.
    Index page Name of the file used by a web server if a requested URL does not contain a filename. Different web servers use different rules to define an index file, for example:
    • Apache: parameter DirectoryIndex in the file httpd.conf.
    • IIS: defined in the site properties: tab Documents -> Enable default content page.
    The PHP does not allow to retrieve the index page name. To obtain the value of this parameter, call GetDirIndex.
    Localization | The adaptation of information to a particular language or region. Localization involves translating strings using proper encoding and providing proper conventions for sorting, date and time formats, currency and measurement units, calendars, numbers, and other culturally specific items such as icons.
    Mail event Mail message of a certain type sent using the appropriate mail template. Mail event initialises fields of the mail event type with specific values. The order of message fields, as well as the body is defined by the mail template.

    To create a mail event, use the CEvent class.

    Note
    Used in Mail subsystem.
    Mail event type Defines a set of special fields (placeholders) that can be used in the mail template. These fields are initialised with specific values when creating a mail event.

    The CEventType class is used with mail event types.

    Note
    Used in Mail subsystem.
    Mail template Defines the mail message text, and the order of fields (placeholders) assigned in the mail event type.
    Mail templates are available in the administrative menu (System settings -> Mail templates).

    The CEventMessage class is used to manage mail templates .

    Note
    Used in Mail subsystem.
    Page body | A page body is the part of the PHP or HTML code located in the script between the inclusion of prologue and epilogue. Page body is not the part of a site template; its content is the subject of a public or administrative page.
    Path relative to the root File path beginning from the folder specified in the DocumentRoot parameter of the web server settings, using the URL specification.

    Example: /en/about/index.php
    Path to component Used in CMain::IncludeFile as the first parameter. Represents the path to the main file of component relative to one of the following folders, in descending priority order:
    • /bitrix/templates/site template ID/
    • /bitrix/templates/.default/
    • /bitrix/modules/module ID/install/templates/
    In the path:
    site template ID - the ID of the current site template;
    module ID - the ID of the module whose component is being included.
    Persistent connection When establishing a database connection, a special connection descriptor is created in memory. In case of simple connection, the descriptor is closed after the script finishes. For persistent connection, the descriptor remains valid and may be used by other processes.

    The advantage of persistent connection is less amount of time required. At the same time, its weakness is that the maximum number of persistent connections is limited (in the database settings): a visitor is unable to open a site page until any connection becomes available.
    Portal | An aggregate of files stored in folder /bitrix/modules/ and a single database. Portal may comprise one or more sites. The synonyms of this term are: "a product copy", "single system installation", "single copy of the system".
    Prologue

    Generally, this term means upper left part of a page.

    For the public section, the prologue of the corresponding site template is stored in the file /bitrix/templates/site template ID/header.php.

    For the administrative section, the prologue is stored in the file /bitrix/modules/main/interface/prolog_admin.php.

    The prologue in its turn can be split in the service and visual sections. The service section includes all required classes, establishes the database connection, creates the system-wide objects $USER, $APPLICATION etc. The visual section displays the upper left area of a page.

    If an undivided prologue is to be included in the public section, the following code should be used: require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

    If a prologue is to be split in the service (prolog_before.php) and visual (prolog_after.php) sections, the following code should be used: require($_SERVER["DOCUMENT_ROOT"]. "/bitrix/modules/main/include/prolog_before.php"); ... require($_SERVER["DOCUMENT_ROOT"]. "/bitrix/modules/main/include/prolog_after.php");

    Public section Generally, this term implies a set of scripts each including the prologue and epilogue of a site template. Their inclusion stipulates:
    • the page is a part of a site;
    • the page design is defined by the current site template;
    • all localization parameters depend on the current site settings.
    Session | This implies the PHP session. Session opens when a visitor opens a site page and closes when he closes the browser window. Additionally, a new session opens upon the user authorization, and closes when he ends the authorized session. A possible synonym of this term is a single "site visit".
    Site section | A site section is just a directory (folder) in the server file system. The Bitrix Site Manager mirrors the site structure to the server file structure, which means that site pages are files, and site sections are file system folders.
    Submit | The process of forwarding data of an HTML form to a server.
    Time in Unix format | Number of seconds elapsed from 01.01.1970, to millisecond. Currently, the Unix format can be only used to specify dates up to 2038.
    Unix permissions The Unix family operating systems support the following permissions: read, write and execute assigned to a file or directory. These permissions are consecutively specified for: the file owner, the owner's user group and for all other users.

    The permissions are specified in the numeric form:
    • 4 - read
    • 2 - write
    • 1 - execute
    The sum of these numbers gives the final permission set, for example: 6 implies read and write access without execution, 7 - all permissions, 5 - read and execute.

    For example: a permission value of 764 means: 7 - all permissions for a owner, 6 - read and write permission for the owner's user group and 4 - read for all other users.

    The PHP syntax prescribes the permissions to be set in octal numbers, which imposes the use of prefix "0" before the number, for example: 0755.
    User account Record in the database containing parameters of a registered user. The following fields are required in the user account:
    • login name;
    • password;
    • e-mail address.
    User account may also include additional fields containing personal or work information, administrator notes etc.


Structure of system files and folders

The system is stored in the directory /bitrix/. This directory contains the following files and subdirectories.

  • /admin/ - administrative scripts;
  • /cache/ - cache files;
  • /help/ - help section;
  • /images/ - images used by the system and modules;
  • /modules/ - system modules. Each subdirectory of this directory has its own strict structure;
  • /php_interface/ - system service directory containing the following subdirectories and files:
    • /include/ - subdirectory containing module helper user-editable scripts:
      • /catalog_export/ - the Commercial catalog module export scripts;
      • /statistic/ - CSV file handlers containing events for loading in the Statistics module;
      • add_top_panel.php - included when displaying the control toolbar; allows adding buttons to the toolbar.
    • dbconn.php - database connection parameters;
    • init.php - portal-wide additional parameters;
    • after_connect.php - included right after the database connection is established;
    • dbconn_error.php - included when a database connection error occurs;
    • dbquery_error.php - included when a SQL query execution error occurs;
    • /site ID/init.php - additional parameters for the site; the file is included right after a special constant SITE_ID is defined.
  • /templates/ - directory containing site templates and components; contains the following subdirectories:
    • /.default/ - subdirectory with common files used by default templates; has the structure similar to the site template directory described below;
    • /site template ID/ - subdirectory with site template; contains the following subdirectories and files:
      • /module ID/ - directory containing components of a specific module;
      • /lang/ - language files used by this template and components;
      • /images/ - directory containing images used by this template;
      • /page_templates/ - directory containing page templates and their description (stored in file .content.php);
      • header.php - prologue of this template;
      • footer.php - epilogue of this template;
      • styles.css - CSS used by this template;
      • .menu type.menu_template.php - template used to display a menu of the corresponding type;
      • chain_template.php - default template used to display the navigation chain.
  • /tools/ - here the installation procedure copies additional files that may be used with any pages of the site: help, calendar, image slideshow etc.;
  • /updates/ - this directory is automatically created by the update system;
  • header.php - a standard file which in its turn includes the current site template prologue; this file must be used with all pages of the public section;
  • footer.php - a standard file including the current site template epilogue; this file must be used with all pages of the public section;
  • license_key.php - this file contains the license key;
  • spread.php - this file is used by the Kernel module to spread user cookies among additional site domains;
  • redirect.php - used by the Statistics module to register link redirect events;
  • bx.php - default file used by the Advertising module to register banner click events;
  • stop_redirect.php - used by the Statistics module to display a message to a visitor currently in the stop-list;
  • activity_limit.php - used by the Statistics module to emit a message to the robot if it exceeds the activity quota;
  • rss.php - used by the Information blocks module to export the RSS content.

Note
Depending on the used edition, some directories and files may be unavailable.


Access permissions

The Bitrix Site Manager supports the following two access permission levels.
  • Level 1. Files and directories access
  • Level 2. Module logic driven rights

Level 1. Files and directories access

This access permission level is checked in the prologue and is assigned in the service file .access.php containing a PHP array in the following format:

$PERM[file/folder][user group ID] = "access permission ID";
In this line:
  • file/folder - name of file or folder to which the permission is assigned;
  • user group ID - the ID of a user group to which the given permission is applicable (a wildcard symbol "*" is allowed, which means "all groups");
  • access permission ID - currently, the following values are supported (in ascending order):
    • D - deny (any access to a file object is denied);
    • R - read (read access is allowed);
    • U - workflow (a file can be modified in the workflow mode);
    • W - write (a file can be modified directly);
    • X - full access (implies write access and editing access permissions).

If the Site Explorer module is installed, you can assign permissions manually in the administrative section (menu Site Explorer->Manage->Access).

Note
If a user is a member of more than one group, the maximum permission among those groups is taken.

Note
If a current file or folder is not assigned the access permission explicitly, the access permission of a parent folder is taken.

Example
File /dir/.access.php
<?
   $PERM["index.php"]["2"] = "R";
   $PERM["index.php"]["3"] = "D";
?>

Upon attempt to open the page /dir/index.php, a user who is the member of the group ID=3 will have a permission D (deny), while a user from the group ID=2 will have a permission R (read). User who is the member of the both groups will have the maximum possible access permission R (read).

Example
File /.access.php
<?
   $PERM["admin"]["*"] = "D";
   $PERM["admin"]["1"] = "R";
   $PERM["/"]["*"] = "R";
   $PERM["/"]["1"] = "W";
?>
File /admin/.access.php
<?
   $PERM["index.php"]["3"] = "R";
?>

Upon attempt to open the page /admin/index.php, a user who is the member of the group ID=3 may be granted access, while a user from the group ID=2 cannot gain access. All users may access the page /index.php.

Level 2. Module logic driven rights

To common static public pages, the access level 1 may be only applied (see above).

If a user has a minimum permission R (read) to a file, and if the file is a functional part of a module, permissions of the access level 2 are checked. These permissions are assigned in settings of the corresponding module.

Example

When opening the Tickets techsupport page, the administrator views all tickets, while a techsupport member can view only those tickets for which he is in charge, and a common user can view his personal tickets only. This is the way the access permission functions within the Techsupport module logic.

Currently, two approaches are used with permissions of the access level 2:

  • permissions
  • roles

The main distinction between these methods is as follows: if a user has more that one permissions, the maximum permission is selected; while if a user has more than one role, he is assumed to have a total scope of roles.

Roles are currently supported by the following modules: Techsupport and Advertising. All other modules use permissions.

Example
  • Permissions. If you enter into two user groups to which the permissions Full access and View statistics without financial indices are assigned in the Statistics module, you will have the maximum permission: Full access.
  • Roles. If you enter into two user groups to which the roles Client and Demo are assigned in the Techsupport module, you will have capabilities of the two roles: you can view all tickets in demo mode and create your tickets as a techsupport client.


Special constants

  • SITE_ID
  • SITE_DIR
  • SITE_SERVER_NAME
  • SITE_CHARSET
  • FORMAT_DATE
  • FORMAT_DATETIME
  • LANGUAGE_ID
  • SITE_TEMPLATE_ID
  • START_EXEC_TIME
  • B_PROLOG_INCLUDED
  • SM_VERSION
  • SM_VERSION_DATE
  • ADMIN_SECTION
  • AUTH_404
  • HELP_FILE
  • NEED_AUTH
  • ERROR_EMAIL
  • LOG_FILENAME
  • STATISTIC_ONLY
  • NO_KEEP_STATISTIC
  • NOT_CHECK_PERMISSIONS
  • ONLY_EMAIL
  • BX_CRONTAB
  • BX_FILE_PERMISSIONS
  • BX_DIR_PERMISSIONS
  • SM_SAFE_MODE
  • DIRECTORY_INDEX
  • MYSQL_TABLE_TYPE
  • DBPersistent
  • BX_VALID_FILENAME_SYMBOLS
Constant | Type | Description
SITE_ID A
P
I 		The ID of the current site.
SITE_DIR | A | The field Site Folder of the current site settings. Usually used to implement multiple sites using the method 1.
SITE_SERVER_NAME | A | The field Server URL of the current site settings.
SITE_CHARSET | A | The field Encoding of the current site settings.
FORMAT_DATE | A | For the public section, this constant contains the date format from the current site settings. For the administrative section - the current language date format.
FORMAT_DATETIME | A | For the public section, this constant contains the time format from the current site settings. For the administrative section - the current language time format.
LANGUAGE_ID A For the public section, this constant stores the value of the field Language of the current site settings.
For the administrative section, this constant stores the current language ID.
SITE_TEMPLATE_ID | A | The ID of the current site template.
START_EXEC_TIME | A | Contains the time a page started to execute, in the format of the function getmicrotime.
B_PROLOG_INCLUDED | A | If a prologue service section is included, this constant is set to true. This constant is mainly used in included files for security purposes: to ensure the prologue is included and all the required permissions are checked.
SM_VERSION | A | The Kernel module current version.
SM_VERSION_DATE | A | Date the current version of the Kernel module has been released.
ADMIN_SECTION A
P 		If the administrative section prologue is to be included, this constant is set to true.
AUTH_404 P This constant is to be initialised prior to the prologue in the 404 error handler files ("page not found"). File handlers can be specified in the web server settings.

This constant, when initialised, allows to change the page to which a form is submitted from standard components: Authorization, Registration, Password Retrieval, Password Change. By default, the submit page is the current page. If the constant is initialised, the submit page is /SITE_DIR/auth.php.

This constant needs to be initialised as data cannot be POST'ed to invalid pages, while the above stated components use the POST method to transfer form data. That's why these components will not work unless the current page physically exist on the server.

Example: define("AUTH_404", "Y");
HELP_FILE P This constant is primarily used in administrative scripts for storing the context help file name, if the name is different than the current script file name. Context help can be invoked using the button on the control toolbar.

Example: define("HELP_FILE", "my_admin_script.php");
NEED_AUTH P If this constant is set to true before the prologue is included, a user authorization status is to be checked. If a current user is not authorised, an authorization form is displayed.

Example: define("NEED_AUTH", true);
ERROR_EMAIL P
I 		Stores an e-mail address (or a list of comma-separated addresses) to be used by the function SendError to send error messages.

Example: define("ERROR_EMAIL", "admin@site.ru, support@site.ru");
LOG_FILENAME P
I
C 		Stores the absolute path to a log file which is used by the function AddMessage2Log to journal errors and messages.

Example: define("LOG_FILENAME", $_SERVER["DOCUMENT_ROOT"]. "/log.txt");
STATISTIC_ONLY P
I
C 		This constant is mainly used in the Web Analytics edition. If it is not initialised, the following HTTP header is sent when dispatching pages of the public section:

Content-Type: text/html; charset=SITE_CHARSET

Example: define("STATISTIC_ONLY", true);
NO_KEEP_STATISTIC P
I
C 		If initialised, this constant suppresses collecting the site statistics.

Example: define("NO_KEEP_STATISTIC", true);
NOT_CHECK_PERMISSIONS P
I
C 		If set to true before the prologue is included, the first level permission checks are disabled.

Example: define("NOT_CHECK_PERMISSIONS", true);
ONLY_EMAIL P
I
C 		If you want the e-mail messages to be sent to only one e-mail address (or a group of e-mail addresses) regardless of the mail templates settings, set this constant to an e-mail address or a list of comma-separated addresses.

Example: define("ONLY_EMAIL", "admin@site.ru, support@site.ru");
BX_CRONTAB P
I
C 		If set to true, the agent execution function will run only those agents whose number of runs is not critical (that is, agents whose parameter period is set to "N" when adding it). This constant is mainly applied to agents executed using cron.

Example: define("NO_KEEP_STATISTIC", true);
BX_FILE_PERMISSIONS P
I
C 		Unix permissions for the newly created files.

Example: define("BX_FILE_PERMISSIONS", 0755);
BX_DIR_PERMISSIONS P
I
C 		Unix permissions for the newly created directories.

Example: define("BX_DIR_PERMISSIONS", 0755);
SM_SAFE_MODE P
I
C 		Setting this constant to true disables all modules except Kernel and Site Explorer.

Example: define("SM_SAFE_MODE", true);
DIRECTORY_INDEX P
I
C 		This constant is used by the function GetDirIndex to determine the folder index file.

Example: define("DIRECTORY_INDEX",
"index.php index.html index.htm index.phtml default.html index.php3");
MYSQL_TABLE_TYPE C This constant contains the default type name of tables created in MySQL. Can be "MyISAM" or "InnoDB".

Example: define("MYSQL_TABLE_TYPE", "InnoDB");
DBPersistent C If set to true, a persistent connection to the database is to be established.

Example: define("DBPersistent", true);
BX_VALID_FILENAME_SYMBOLS P
A
C 		Defines a set of symbols which are allowed in names of uploaded files. Set is specified in the form of regular expression. If the option "save_original_file_name" is set and a file name contains invalid symbols, the system behaviour depends on the convert_original_file_name option value: either the file name is transformed, or an error is displayed upon upload attempt.

The default value is: \x20-\x21\x2B-\x2E\x30-\x39\x41-\x5A\x5F\x61-\x7A\x7B\x7C\x7E.

Legend of constant types

  • A (auto) - the constant is initialised automatically by the system in the prologue;
  • P (page) - the constant can be defined in any public page before the prologue;
  • I (initialization) - the constant can be defined in one of the following files:
    • /bitrix/php_interface/init.php - additional parameters of the portal;
    • /bitrix/php_interface/site ID/init.php - additional parameters of the site.
  • C (database connection) - the constant can be only defined in the file containing database connection settings: /bitrix/php_interface/dbconn.php.


Special variables

  • APPLICATION
  • USER
  • DB
  • DBType
  • DBHost
  • DBName
  • DBLogin
  • DBPassword
  • DBDebug
  • DBDebugToFile
  • clear_cache
  • clear_cache_session
  • compress
  • show_page_exec_time
  • show_include_exec_time
  • show_lang_files
  • no_keep_statistic_KEY
  • no_agent_statistic_KEY
  • key
Variable name | Type | Description
APPLICATION | G | Global object of the class CMain. Used to perform common operations (display title, navigation chain, menu etc.)
USER | G | Global object of the class CUser. Stores the current user authorization data. Used to obtain and edit the current user parameters.
DB | G | Global object of the class CDataBase. Used to perform the database operations.
DBType C Type of the database: "mysql" or "oracle".

Example:$DBType = "mysql";
DBHost C Host name to connect to the database:
  • for MySQL - address of the database server, e.g. "localhost";
  • for Oracle - not used.
Example: $DBHost = "localhost"; $DBHost = "localhost:3307";
DBName C This variable contains different values for different database types:
  • for MySQL - database name;
  • for Oracle - connection string.
Example for MySQL:$DBName = "bitrix"; Example for Oracle: $DBName = " (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP) (HOST = 192.168.0.1) (PORT = 1521) ) ) (CONNECT_DATA = (SERVICE_NAME = BX) ) ) ";
DBLogin C Login name to connect to the database.

Example:$DBLogin = "root";
DBPassword C Password to connect to the database.

Example:$DBPassword = "123456";
DBDebug C
I 		If set to true, the browser will display the error message every time a database connection or SQL query error occurs. If set to false, full error description is visible to the site administrator only.

Example:$DBDebug = true;
DBDebugToFile C
I 		If set to true, all SQL queries and the execution duration are logged in /mysql_debug.sql (or /oracle_debug.sql). This option can be used to obtain information on the SQL query execution speed.

The SQL log creation and maintenance slows down the site operation significantly. Use this option for debugging only.

Example:$DBDebugToFile = true;
clear_cache P Setting this variable to "Y" disables caching for the current page.

Only users with administrator rights can use this option.

Example:http://www.site.ru/?clear_cache=Y
clear_cache_session P Setting this variable to "Y" disables caching for the current session. To enable caching, set this parameter to "N" once.

Only users with administrator rights can use this option.

Example: http://www.site.ru/?clear_cache_session=Y http://www.site.ru/?clear_cache_session=N
compress P If set to "Y", a table is shown at the page bottom with information on the page compression achieved using the Compression module: uncompressed page size, compressed page size, compression ratio. This is the per-session directive. To hide the compression report, set this parameter to "N" once.

Example: http://www.site.ru/?compress=Y http://www.site.ru/?compress=N
show_page_exec_time P If set to "Y", a table is shown at the page bottom with information on the page execution duration on the server. This is the per-session directive. To hide the report, set this parameter to "N" once.

This variable allows to obtain the impartial information on the site speed.

Example: http://www.site.ru/?show_page_exec_time=Y http://www.site.ru/?show_page_exec_time=N
show_include_exec_time P If set to "Y", the page will display the total duration of execution of all methods CMain::IncludeFile. This method includes (connects) both components and common scripts. This is the per-session directive. To hide the report, set this parameter to "N" once.

Only users with administrator rights can use this option.

Example: http://site.ru/?show_include_exec_time=Y http://site.ru/?show_include_exec_time=N
show_lang_files P If set to "Y", a list of language files used by the page is shown at the page bottom. The language file list allows searching. This is the per-session directive. To hide the report, set this parameter to "N" once.

This variable allows to locate a language phrase quickly.

Example: http://www.site.ru/?show_lang_files=Y http://www.site.ru/?show_lang_files=N
no_keep_statistic_KEY P Setting this variable to "Y" disables collecting statistics within a session. To enable statistics, set this parameter to "N" once. This variable is mainly used to disable statistics when viewing the site by the administrator.

KEY is the license key stored in file /bitrix/license_key.php

Example: http://www.site.ru/?no_keep_statistic_SM4-ML-PZDIO7TUMT3WP7H=Y http://www.site.ru/?no_keep_statistic_SM4-ML-PZDIO7TUMT3WP7H=N
no_agent_statistic_KEY P Setting this variable to "Y" disables statistics agents within a session. To enable agents in this session, set this parameter to "N" once.

KEY is the license key stored in file /bitrix/license_key.php

Example: http://www.site.ru/?no_agent_statistic_SM4-ML-PZDIO7TUMT3WP7H=Y http://www.site.ru/?no_agent_statistic_SM4-ML-PZDIO7TUMT3WP7H=N
key This variable can only be used when calling the script /bitrix/admin/phpinfo.php. If its value equals to the license key, this script is executed without the inclusion of the administrative prologue.

Example: http://www.site.ru/bitrix/admin/phpinfo.php?key=SM4-ML-PZDIRTH

Legend of variable types

  • G (global) - variable is created automatically in the prologue service section;
  • C (database connection) - variable can only be defined in the file containing the database connection parameters: /bitrix/php_interface/dbconn.php
  • I (initialisation) - variable can be defined in one of the following files:
    • /bitrix/php_interface/init.php - additional parameters of the portal;
    • /bitrix/php_interface/site ID/init.php - additional parameters of the site.
  • P (page) - variable can be defined in a page parameters specified in the browser.


Date and time

The following functions are used with date and time.

  • CDatabase::CharToDateFunction
  • CDatabase::DateToCharFunction
  • CDatabase::CurrentDateFunction
  • CDatabase::CurrentTimeFunction
  • CDataBase::DateFormatToPHP
  • CDataBase::FormatDate
  • ConvertDateTime
  • MakeTimeStamp
  • ConvertTimeStamp
  • CDataBase::IsDate
  • CDataBase::CompareDates
  • AddToTimeStamp
  • getmicrotime

The following format specifiers can be used with date and time:

  • YYYY - year;
  • MM - month;
  • DD - day;
  • HH - hours;
  • MI - minutes;
  • SS - seconds.

Methods for use with SQL queries

  • CDatabase::CharToDateFunction - returns a date and time value converted to the database SQL format.

    <?
$strSql = "
    SELECT
        ID
    FROM
        my_table
    WHERE
        DATE_CREATE <= ".$DB->CharToDateFunction("10.01.2003 23:59:59")."
    ";
$rs = $DB->Query($strSql, false, $err_mess.__LINE__);
?>
  • CDatabase::DateToCharFunction - converts the database SQL format to a date and time string.

    <?
$strSql = "
    SELECT
        ID,
        ".$DB->DateToCharFunction("DATE_CREATE")." DATE_CREATE
    FROM
        my_table
    ";
$rs = $DB->Query($strSql, false, $err_mess.__LINE__);
?>
  • CDatabase::CurrentDateFunction - used to obtain the SQL function returning the current date.

    <?
$strSql = "
    SELECT
        ID
    FROM
        my_table
    WHERE
        DATE_CREATE<=".$DB->CurrentDateFunction()
    ";
$rs = $DB->Query($strSql, false, $err_mess.__LINE__);
?>
  • CDatabase::CurrentTimeFunction - returns the SQL string used to obtain the current time in the database format.

    <?
$strSql = "
    UPDATE my_table SET
         TIME_CHANGE=".$DB->CurrentTimeFunction()."
    WHERE
         ID=45
    ";
$Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);
?>

Format conversion

  • CDataBase::DateFormatToPHP - converts the date and time format allowed by the site settings to the PHP format.

    <?
echo $DB->DateFormatToPHP("DD.MM.YYYY HH:MI:SS"); // d.m.Y H:i:s
?>
  • CDataBase::FormatDate - converts the date from the source format into another.

    <?
echo $DB->FormatDate("31.12.2005", "DD.MM.YYYY", "YYYY-MM-DD"); // 2005-12-31
?>
  • ConvertDateTime - takes the date and time specified in the format of the current site and converts it to an arbitrary format.

    <?
echo ConvertDateTime("25.12.2003", "YYYY-MM-DD", "ru"); // 2003-12-25
?>
  • MakeTimeStamp - converts the time to the Unix format.

    <?
echo MakeTimeStamp("07.04.2005 11:32:00", "DD.MM.YYYY HH:MI:SS"); // 1112862720
?>
  • ConvertTimeStamp - converts time from the Unix format to a string in the site format.

    <?
echo ConvertTimeStamp(mktime(0, 0, 0, 10, 25, 2003), "SHORT", "ru"); // 25.10.2003
?>

Service functions

  • CDataBase::IsDate - checks the date for validity.

    <?
echo $DB->IsDate("12.10.2005 22:34:15", "DD.MM.YYYY HH:MI:SS") ? "OK" : "ERROR"; // OK
echo $DB->IsDate("12.13.2005 22:34:15", "DD.MM.YYYY HH:MI:SS") ? "OK" : "ERROR"; // ERROR
echo $DB->IsDate("12.13..2005 ABS", "DD.MM.YYYY HH:MI:SS") ? "OK" : "ERROR"; // ERROR
?>
  • CDataBase::CompareDates - compares two dates.

    <?
echo $DB->CompareDates("01.01.2005", "01.01.2007"); // -1
echo $DB->CompareDates("01.01.2007", "01.01.2005"); // 1
echo $DB->CompareDates("01.01.2007", "01.01.2007"); // 0
?>
  • AddToTimeStamp - adds the specified time span to a date in Unix format.

    <?
$stmp = MakeTimeStamp("07.04.2005 11:32:00", "DD.MM.YYYY HH:MI:SS");
$stmp = AddToTimeStamp(array("DD" => -1, "MM" => 1), $stmp); // 1115454720
echo date("d.m.Y H:i:s", $stmp); // 06.05.2005 11:32:00
?>
  • getmicrotime - returns the current time in Unix format.

    <?
echo getmicrotime(); // 1115454720
?>


Navigation chain

In this topic

  • What is navigation chain
  • How to create
  • Displaying navigation chain
  • Design
  • Example of templates
  • More information

What is navigation chain

A navigation chain is the design element which aims to helps users navigate through the site. Navigation chain clearly shows the nesting depth of the current site section:

How to create

A common navigation chain includes site section titles with appropriate links applied to them. A site section title is defined in the service file .section.php, which can be found in the corresponding section. The following variables can be used in this file:

  • $sSectionName - section title;
  • $sChainTemplate - absolute path to the navigation chain template (used rarely).

The following is an example of the .section.php file.

<?
$sSectionName = "Company profile";
$sChainTemplate = $_SERVER["DOCUMENT_ROOT"]."/en/about/chain_template.php";
?>

You can assign a title to the site section using the visual editor of the Site Explorer module. To do so, go to Site Explorer->Manage and open properties of the desired section. An alternative way is using control toolbar button Folder properties (in the public section).

In addition to the automatically displayed section titles, you can add arbitrary items to the navigation chain by calling CMain::AddChainItem.

Displaying navigation chain

Navigation chain is usually displayed in the prologue visual section by calling the method CMain::ShowNavChain using the delay function technology.

Design

Design of navigation chain is described in a special PHP file - navigation chain template. You can specify the path to this file explicitly when displaying the navigation chain. If the path is not specified, the following algorithm is used to locate the template file.

  1. Navigation chain items are collected starting from the site root, to the current section. For each section, the corresponding file .section.php is included. If this file has the variable $sChainTemplate initialised, its value is used as the path to the navigation chain template. When enumerating sections, every new value of this variable replaces the old one. In other words, the deeper a section lies in the hierarchy, the more important is its variable $sChainTemplate.

  2. If, after building a chain, the template path is still not defined, the following file is checked:

    /bitrix/templates/current site template ID/chain_template.php

    If the file exists, its path is used as the menu template path. Otherwise, the default file path is used:

    /bitrix/templates/.default/chain_template.php

When displaying the navigation chain, the navigation chain template is included every time an item is added. It follows that its main task is to provide the design of a single chain item.

The following are the main variables used in the navigation chain template.

  • $sChainProlog - HTML code emitted before the navigation chain;
  • $sChainBody - HTML code defining the design of a chain item;
  • $sChainEpilog - HTML code emitted after the navigation chain;
  • $strChain - HTML code describing the whole navigation chain build by the time of including the template.
The variables listed above store the HTML code describing the navigation chain design.

In addition, the following variables are available in the template.

  • $TITLE - navigation chain item title;
  • $LINK - navigation chain item link;
  • $arCHAIN - copy of the navigation chain item array;
  • $arCHAIN_LINK - link to the navigation chain item array;
  • $ITEM_COUNT - number of items in the the navigation chain;
  • $ITEM_INDEX - navigation chain item ordinal.

Example of templates

<?
// simplest template displaying the standard chain

// HTML code displayed before chain
$sChainProlog = "";

// HTML code defining the design of a chain item
$sChainBody = "";
if (strlen($LINK)>0)
    $sChainBody .= "<a href=\"".$LINK."\" class='chainitem'>".$TITLE."</a>";
else
    $sChainBody .= "<font class='chainitem'>".$TITLE."</font>";

// HTML code displayed after the navigation chain
$sChainEpilog = "";
?>
<?
// template displaying the inverted navigation chain without links
// can be used in the <title> tag
// for better indexing by search engines

$sChainEpilog = "";

// if array is defined...
if (is_array($arCHAIN))
{
    // iterate on items
    reset($arCHAIN);
    foreach($arCHAIN as $item)
    {
        // if first item...
        if (strlen($sChainEpilog)<=0)
            $sChainEpilog = $item["TITLE"];
        else // otherwise
            $sChainEpilog = $item["TITLE"]." :: ".$sChainEpilog;
    }
}
?>

More information

  • CMain::ShowNavChain
  • CMain::AddChainItem
  • CMain::GetNavChain


Menu

In this topic

  • What is menu
  • Menu files
  • Examples of menu files
  • Menu display
  • Examples of menu display
  • A menu template
  • Menu item active state
  • Examples of menu templates
  • Additional information

What is menu

A menu is the design element which serves as the main navigation facility. Menu can be of two different types; each displayed in its proper place of the site design:

Menu files

Menu is attached to a site section using a service PHP file with the name .menu type.menu.php. This file resides in the corresponding section of the site. The following standard variables can be used in this file:

  • $sMenuTemplate - absolute path to the menu template (used rarely);
  • $aMenuLinks - array with elements each describing a menu item. This array has the following structure:

    Array
(
    [0] => menu item 1
        Array
            (
                [0] => menu item title
                [1] => menu item link
                [2] => array of additional links to highlight the menu item:
                    Array
                        (
                            [0] => link 1
                            [1] => link 2
                            ...
                         )
                [3] => array of additional variables passed to the menu template:
                    Array
                        (
                            [variable name 1] => variable value 1
                            [variable name 2] => variable value 2
                            ...
                         )
                [4] => condition which stipulates the menu item display
                       (the PHP expression returning "true")
            )
    [1] => menu item 2
    [2] => menu item 3
    ...
)

You can visually manage menu items using the Site Explorer module functionality. To do so, select Site Explorer -> Manage, then select the desired folder, click the link Add menu and select the required menu type. The system provides for two menu editing modes: Simple and Advanced.

You can make the process of menu management more simple by using the control toolbar in the public section. Click the button Show include areas to highlight areas editable through the user interface. Then click the button Edit menu items beside the desired menu.

Sometimes a task may arise when you need to define menu items programmatically. For example, you may want to display sections of the Information Blocks module catalog in a menu. To do so, you need to use service files .menu type.menu_ext.php. These files are to be stored in the required site section. The main purpose of these files is managing the array $aMenuLinks. Such files cannot be edited visually using the Site Explorer means, so they remain untouched when editing the menu in the visual editor.

Note
If you want to use files .menu type.menu_ext.php, you should pay attention to the second parameter of the functions CMain::GetMenuHtml and CMain::GetMenuHtmlEx when displaying the menu. This parameter should be set to true (false by default).

Note

If no menu is assigned to the current section explicitly (that is, no menu file exists in the folder), a menu of the first parent section that contains the menu file is used. It follows that a menu is hierarchically inheritable.

For example, a user is currently in the section /en/company/about/. The system uses the following sequence to search for the left type menu file:

1. /en/company/about/.left.menu.php
2. /en/company/.left.menu.php
3. /.left.menu.php

If the system succeeds to find the menu in one of the folders, the search is stopped and the system uses the found file.

Examples of menu files

<?
// file .left.menu.php

$aMenuLinks = Array(
    Array(
        "Phones",
        "/catalog/phone/",
        Array("/catalog/phone/index.php", "/catalog/phone/compare.php"),
        Array(),
        ""
    ),
    Array(
        "Accessories",
        "/catalog/accessory/",
        Array("/catalog/accessory/index.php"),
        Array(),
        ""
    ),
    Array(
        "Admin section",
        "/catalog/admin/",
        Array("/catalog/admin/index.php", "/catalog/admin/edit.php"),
        Array("PARAM_1" => "Y"),
        "\$GLOBALS["USER"]->IsAdmin()"
    )
);
?>
<?
// file .left.menu_ext.php

if (CModule::IncludeModule("iblock")):

    $CACHE_TIME = "0";
    $IBLOCK_TYPE = "catalog";   // information block type
    $IBLOCK_ID = 22;            // information block ID
    $CACHE_TIME = 86400;        // cache time

    $aMenuLinksNew = array();
    $ROOT_SECTION_ID = 0;
    $CACHE_ID = __FILE__.$IBLOCK_ID;
    $obMenuCache = new CPHPCache;
    if($_GET["SECTION_ID"]>0)
        $CACHE_ADD .= "|SECTION_ID=".$_GET["SECTION_ID"];
    elseif($_GET["ID"]>0)
        $CACHE_ADD .= "|ELEMENT_ID=".$_GET["ID"];
    else
        $CACHE_ADD = "";

    // if the array is cached...
    if($obMenuCache->InitCache($CACHE_TIME, $CACHE_ID.$CACHE_ADD, "/"))
    {
        // use cached data
        $arVars = $obMenuCache->GetVars();
        $aMenuLinksNew = $arVars["aMenuLinksNew"];
    }
    else
    {
        $CACHE_ADD = "";
        if($_GET["SECTION_ID"]>0)
        {
            $res = CIBlockSection::GetNavChain($IBLOCK_ID, $_GET["SECTION_ID"]);
            if($ar_res = $res->Fetch())
            {
                $ROOT_SECTION_ID = $ar_res["ID"];
                $CACHE_ADD = "|SECTION_ID=".$_GET["SECTION_ID"];
            }
        }
        elseif($_GET["ID"]>0)
        {
            $res = CIBlockElement::GetElementGroups($_GET["ID"]);
            if($ar_res = $res->Fetch())
            {
                $CACHE_ADD = "|ELEMENT_ID=".$_GET["ID"];
                $res = CIBlockSection::GetNavChain(
                    $IBLOCK_ID,
                    $ar_res["IBLOCK_SECTION_ID"]
                    );
                $ar_res = $res->Fetch();
                $ROOT_SECTION_ID = $ar_res["ID"];
            }
        }

        // otherwise, collect sections
        $rsSections = GetIBlockSectionList(
            $IBLOCK_ID,
            0,
            array("SORT" => "ASC", "ID" => "ASC"),
            false,
            array("ACTIVE"=>"Y")
            );
        while ($arSection = $rsSections->Fetch())
        {
            $aMenuLinksNew[] = array(
                $arSection["NAME"],
                SITE_DIR."catalog/accessory/section.php?SECTION_ID=".$arSection["ID"],
                ($ROOT_SECTION_ID==$arSection["ID"] ? Array("/") : Array())
            );
        }
    }
    // cache the data
    if($obMenuCache->StartDataCache($CACHE_TIME, $CACHE_ID.$CACHE_ADD, "/"))
    {
        $obMenuCache->EndDataCache(Array("aMenuLinksNew" => $aMenuLinksNew));
    }

    $aMenuLinks = array_merge($aMenuLinksNew, $aMenuLinks);
endif;
?>

Menu display

Menu is displayed in the visual section of either prologue or epilogue. The following two fundamentally different methods of menu display can be used.

  • Method 1. The menu template is included only once for all menu items. Menu is displayed using the following functions:
    • CMain::GetMenuHtmlEx
    • CMenu::GetMenuHtmlEx (an instance of the CMenu class must be initialised prior to calling this function)
  • Method 2. The menu template is included for each menu item. Menu is displayed using the following functions:
    • CMain::GetMenuHtml
    • CMenu::GetMenuHtml (an instance of the CMenu class must be initialised prior to calling this function)

Examples of menu display

<?
// display a menu of the type "top"
echo $APPLICATION->GetMenuHtmlEx("top");
?>
<?
// display a menu of the type "left"
// with support for files .menu type.menu_ext.php
echo $APPLICATION->GetMenuHtml("left", true);
?>
<?
// display a menu of the type "left"
// with support for files .menu type.menu_ext.php
// specifying the template and
// a folder for which the menu is to be built

$obMenu = $APPLICATION->GetMenu(
    "left",
    true,
    "/bitrix/php_interface/".SITE_ID."/left.menu_template.php",
    SITE_DIR
    );
echo $obMenu->GetMenuHtml();
?>

A menu template

A menu design is prescribed by a template, which is a PHP file itself. You can specify path to this file explicitly at the time of menu display. If you do not provide the template file path, the following algorithm is used to search for this file.

  1. As stated above, menu is hierarchically inherited. That is, if no menu is assigned to the current section explicitly (that is, no menu file exists in the folder), a menu of the first parent section that contains the menu file is used.

    For example, a user is currently in the section /en/company/about/. The system uses the following sequence to search for the left type menu file:

    1. /en/company/about/.left.menu.php
    2. /en/company/.left.menu.php
    3. /.left.menu.php

    If the system succeeds to find the menu in one of the folders, the search is stopped and the system uses the found file.

    Each of these files may have the $sMenuTemplate variable defined containing the menu template path. If the file exists, it will be used as the menu template.

  2. If the system is unable to find the menu template file, the following file is checked for existence:

    /bitrix/templates/current site template ID/.menu type.menu.php

    If the file exists, its path is used as the menu template path. Otherwise, the default file path is used:

    /bitrix/templates/.default/.menu type.menu.php

Different sets of variables are available in templates depending on the preferred menu display method.

  • For the method 1, the following variables are available in a menu template:
    • $sMenu - HTML code which defines the menu design;
    • $arMENU_LINK - link to the source array of menu items (synonym: $MENU_ITEMS);
    • $arMENU - copy of menu item array. Each menu item, in its turn, is an array with the following keys:
      • TEXT - menu item title;
      • LINK - menu item link;
      • SELECTED - defines whether the menu item is currently active; the following values are possible:
        • true - menu item is selected;
        • false - menu item is not selected.
      • PERMISSION - current user access permissions for the page to which the LINK points; the following values are possible:
        • D - access denied;
        • R - read (view the file contents);
        • U - workflow (file editing in the workflow mode);
        • W - write (direct file editing);
        • X - full access (direct file editing and access permission modification).
      • ADDITIONAL_LINKS - array of additional links which cause the menu item highlighting;
      • ITEM_TYPE - flag defining the LINK type; the following values are possible:
        • D - directory (LINK ends with "/");
        • P - page;
        • L - page with parameters.
      • ITEM_INDEX - menu item ordinal;
      • PARAMS - associated array containing the menu item parameters.
  • For the method 2, the following variables are available in a menu template:
    • $sMenuProlog - HTML code to be added before the menu;
    • $sMenuEpilog - HTML code to be added after the menu;
    • $sMenuBody - HTML code which defines the menu item design;
    • $arMENU_LINK - link to the source array of menu items (synonym: $MENU_ITEMS);
    • $arMENU - copy of menu item array (structure of this array is described above);
    • $TEXT - menu item title;
    • $LINK - menu item link;
    • $SELECTED - defines whether the menu item is currently active; the following values are possible:
      • true - menu item is selected;
      • false - menu item is not selected.
    • $PERMISSION - current user access permissions for the page to which the LINK points; the following values are possible:
      • D - access denied;
      • R - read (view the file contents);
      • U - workflow (file editing in the workflow mode);
      • W - write (direct file editing);
      • X - full access (direct file editing and access permission modification).
    • $ADDITIONAL_LINKS - array of additional links which cause the menu item highlighting;
    • $ITEM_TYPE - flag defining the $LINK type; the following values are possible:
      • D - directory (LINK ends with "/");
      • P - page;
      • L - page with parameters.
    • ITEM_INDEX - menu item ordinal;
    • PARAMS - associated array containing the menu item parameters.

Menu item active state

The menu item link ($LINK) and the array of additional links ($ADDITIONAL_LINKS) define the active menu item (selected, highlighted). If the menu item is active, the variable $SELECTED=true is available in the menu template.

In respect to the active state, menu item links can be classified in the following types.

  • Link to folder ($ITEM_TYPE=D). Such links always end with "/". Links of this type are always highlighted if a user views a page within the folder, regardless of the page parameters.
  • Link to page ($ITEM_TYPE=P). Such links always end with the page file name. Links of this type are highlighted if a user views the page, regardless of the page parameters.
  • Link to page with parameters ($ITEM_TYPE=L). Such links end with the page file name, symbol "?" and pairs in the format parameter=value separated with ampersand &. Links of this type are only highlighted if a user views the page and the variables listed have the specified values (regardless of the order of parameters).

The below is the example of the menu item active state (symbol "X") at different combinations of the current page and the menu link.

Current page | Menu item link
 | /dir/ | /dir/index.php | /dir/index.php?par1=val1
/dir/page.php | X |  |
/dir/index.php | X | X |
/dir/index.php?par1=val1 | X | X | X
/dir/index.php?par1=val2 | X | X |

The menu item link may be absolute or relative. If the link is relative, it is always evaluated relative to the directory containing the menu file.

Consider the following conditions:

  • a menu file resides in /dir/ and one of the menu items contains a relative link index.php;
  • a user views the page /dir/subdir/index.php;
  • the subfolder /dir/subdir/ does not have its own menu file to use for display (see Menu files).
These conditions stipulates that the current menu item is not highlighted as it is previously converted to the absolute format /dir/index.php relative to the folder containing the menu file. The menu link points to that absolute file, correspondingly.

Examples of menu templates

The following is the menu template file .left.menu_template.php used to display a menu using the method 1 using CMain::GetMenuHtmlEx:

<?
if (is_array($arMENU) && count($arMENU)>0)
{
    $sMenu = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";

    foreach($arMENU as $arMENU_ITEM)
    {
        extract($arMENU_ITEM);

        // if link points to a folder...
        if ($ITEM_TYPE=="D")
        {
            // if item is active...
            if ($SELECTED)
                $strDir = "<td width='0%' bgcolor='#A0C4E0' valign='middle' align='center'>".
                          "<img height='13' src='/bitrix/templates/demo/images/left_folder_open.gif' ".
                          "width='17' border='0'></td>";
            else // otherwise...
                $strDir = "<td width='0%' bgcolor='#CCDFEE' valign='middle' align='center'>".
                          "<img height='13' src='/bitrix/templates/demo/images/left_folder.gif' ".
                          "width='17' border='0'></td>";
        }
        else // otherwise...
        {
            // if item is active...
            if ($SELECTED)
            {
                $strDir = "<td width='0%' bgcolor='#A0C4E0' valign='middle' align='center'>".
                          "<img height='13' src='/bitrix/templates/demo/images/left_bullet.gif' ".
                          "width='17' border='0'></td>";
                $strDir_d = "<td width='0%' bgcolor='#A0C4E0' valign='middle' align='center'>".
                            "<img height='13' src='/bitrix/templates/demo/images/left_bullet_d.gif' ".
                            "width='17' border='0'></td>";
            }
            else // otherwise...
            {
                $strDir = "<td width='0%' bgcolor='#CCDFEE' valign='middle' align='center'>".
                          "<img height='13' src='/bitrix/templates/demo/images/left_bullet.gif' ".
                          "width='17' border='0'></td>";
                $strDir_d = "<td width='0%' bgcolor='#CCDFEE' valign='middle' align='center'>".
                            "<img height='13' src='/bitrix/templates/demo/images/left_bullet_d.gif' ".
                            "width='17' border='0'></td>";
            }
        }

        // if item is active...
        if ($SELECTED)
            $strtext = "leftmenuact";
        else
            $strtext = "leftmenu";

        // if SEPARATOR=Y...
        if ($PARAMS["SEPARATOR"]=="Y")
        {
            // show menu item differently
            $strstyle = " style='background-color: #D5ECE6; border-top: 1px solid #A6D0D7; ".
                        "border-bottom: 1px solid #A6D0D7; padding:8;'";
            $strDir = "<img height='13' src='/bitrix/templates/demo/images/1.gif' width='17' border='0'>";
            $strtext = "leftmenu";
        }
        else
            $strstyle = " style='padding:8;'";

        // if a user may access the page to which the item points...
        if ($PERMISSION > "D")
        {
            $sMenu .= '<tr><td colspan=2 background="/bitrix/templates/demo/images/l_menu_border.gif">'.
                      '<img src="/bitrix/templates/demo/images/1.gif" width="1" height="1"></td></tr>'.
                      '<tr>'.$strDir.'<td valign="top"'.$strstyle.' width="100%"><a href="'.$LINK.
                      '" class="'.$strtext.'">'.$TEXT.'</a></td></tr>';
        }
        else // otherwise...
        {
            $sMenu .= '<td colspan=2 background="/bitrix/templates/demo/images/l_menu_border.gif">'.
                      '<img src="/bitrix/templates/demo/images/1.gif" width="1" height="1"></td></tr>'.
                      '<tr>'.$strDir_d.'</td><td valign="top"'.$strstyle.' width="100%">'.
                      '<a href="'.$LINK.'" class='.$strtext.'>'.$TEXT.'</a></td></tr>';

        }
    }

    $sMenu .= '<tr><td colspan=2 background="/bitrix/templates/demo/images/l_menu_border.gif">'.
              '<img src="/bitrix/templates/demo/images/1.gif" width="1" height="1"></td></tr></table>';
}
?>

Similar menu template .left.menu_template.php, using the method 2 with a call to CMain::GetMenuHtml:

<?
$sMenuProlog = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";

// if link points to a folder...
if ($ITEM_TYPE=="D")
{
    // if menu item is active...
    if ($SELECTED)
        $strDir = "<td width='0%' bgcolor='#A0C4E0' valign='middle' align='center'>".
                  "<img height='13' src='/bitrix/templates/demo/images/left_folder_open.gif' ".
                  "width='17' border='0'></td>";
    else // otherwise
        $strDir = "<td width='0%' bgcolor='#CCDFEE' valign='middle' align='center'>".
                  "<img height='13' src='/bitrix/templates/demo/images/left_folder.gif' ".
                  "width='17' border='0'></td>";
}
else // otherwise
{
    // if menu item is active...
    if ($SELECTED)
    {
        $strDir = "<td width='0%' bgcolor='#A0C4E0' valign='middle' align='center'>".
                  "<img height='13' src='/bitrix/templates/demo/images/left_bullet.gif' ".
                  "width='17' border='0'></td>";
        $strDir_d = "<td width='0%' bgcolor='#A0C4E0' valign='middle' align='center'>".
                    "<img height='13' src='/bitrix/templates/demo/images/left_bullet_d.gif' ".
                    "width='17' border='0'></td>";
    }
    else // otherwise
    {
        $strDir = "<td width='0%' bgcolor='#CCDFEE' valign='middle' align='center'>".
                  "<img height='13' src='/bitrix/templates/demo/images/left_bullet.gif' ".
                  "width='17' border='0'></td>";
        $strDir_d = "<td width='0%' bgcolor='#CCDFEE' valign='middle' align='center'>".
                    "<img height='13' src='/bitrix/templates/demo/images/left_bullet_d.gif' ".
                    "width='17' border='0'></td>";
    }
}

// if menu item is active...
if ($SELECTED)
    $strtext = "leftmenuact";
else
    $strtext = "leftmenu";

// if SEPARATOR=Y...
if ($PARAMS["SEPARATOR"]=="Y")
{
    // show menu item differently
    $strstyle = " style='background-color: #D5ECE6; border-top: 1px solid #A6D0D7; ".
                "border-bottom: 1px solid #A6D0D7; padding:8;'";
    $strDir = "<img height='13' src='/bitrix/templates/demo/images/1.gif' width='17' border='0'>";
    $strtext = "leftmenu";
}
else
    $strstyle = " style='padding:8;'";

// if a user may access the page to which the item points...
if ($PERMISSION > "D")
{
    $sMenuBody = '<tr><td colspan=2 background="/bitrix/templates/demo/images/l_menu_border.gif">'.
                 '<img src="/bitrix/templates/demo/images/1.gif" width="1" height="1"></td></tr>'.
                 '<tr>'.$strDir.'<td valign="top"'.$strstyle.' width="100%"><a href="'.$LINK.
                 '" class="'.$strtext.'">'.$TEXT.'</a></td></tr>';
}
else // otherwise
{
    $sMenuBody = '<td colspan=2 background="/bitrix/templates/demo/images/l_menu_border.gif">'.
                 '<img src="/bitrix/templates/demo/images/1.gif" width="1" height="1"></td></tr>'.
                 '<tr>'.$strDir_d.'</td><td valign="top"'.$strstyle.' width="100%"><a href="'.$LINK.
                 '" class='.$strtext.'>'.$TEXT.'</a></td></tr>';

}

$sMenuEpilog = '<tr><td colspan=2 background="/bitrix/templates/demo/images/l_menu_border.gif">'.
               '<img src="/bitrix/templates/demo/images/1.gif" width="1" height="1"></td></tr></table>';
?>

Both of the above examples will generate similar output:

Additional information

  • CMain::GetMenuHtmlEx
  • CMain::GetMenuHtml
  • CMenu class
  • CMenu::GetMenuHtmlEx
  • CMenu::GetMenuHtml


URL Rewriting

What is URL Rewriting?

Using a URL rewrite engine, the website software can be presented with URL's in one form, while actual requests (and URL's seen by the user) are in another form. For example, rewriting can be configured in such a way that a script in /fld/c.php, responding at:

/fld/c.php?id=15

would also be available at:

/catalog/15.php

The address at which the script would be available must not physically exist; otherwise, the existing file will be retrieved instead. In this case, URL rewriting engine would not be activated.

Rewriting rules

The URL rewriting rules are configured for each site individually and stored in urlrewrite.php in the site root. This file contains an array $arUrlRewrite, each entry being a URL rewriting rule. The following code shows an example of urlrewrite.php:

<?
$arUrlRewrite = array(
    array(
        "CONDITION" => "#^/gallery/#",
        "RULE" => "",
        "ID" => "bitrix:photo",
        "PATH" => "/max/images/index.php",
    ),
    array(
        "CONDITION" => "#^/forum/#",
        "ID" => "bitrix:forum",
        "PATH" => "/forum/index.php",
    ),
    array(
        "CONDITION" => "#^/index/([0-9]+)/([0-9]+)/#",
        "RULE" => "mode=read&CID=$1&GID=$2",
        "ID" => "bitrix:catalog.section",
        "PATH" => "/newforum/index.php",
    ),
    array(
        "CONDITION" => "#(.+?)\\.html(.*)#",
        "RULE" => "$1.php$2",
    ),
);
?>

Each rule has a rule application condition that is unique within the site. The condition which is a Perl compatible regular expression is contained in the "CONDITION" key of the array. For example:

"CONDITION" => "#^/index/([0-9]+)/([0-9]+)/#"

specifies that the rule should be applied to all URL's starting with text like:

/index/<number>/<number>/

A rule can include and address of an existing script that will be activated when the condition is true. This address is specified in the "PATH" key. For example, if the following rule is active:

array(
    "CONDITION" => "#^/gallery/#",
    "PATH" => "/max/images/index.php",
)

and a user requests the page that does not exist physically:

/gallery/38.php

the URL rewrite engine will return the script:

/max/images/index.php

Rules can contain replacement options that can be specified in the "RULE" key. If the key exists, the final address is the result of the regular expression replacement operation on the source address. The rewrite engine takes the CONDITION as a search pattern and replaces the matching portion of the address with the concatenation of the PATH and the RULE keys, the latter containing the regular expression replacement switches.

Example 1

For example, the following rule:

array(
    "CONDITION" => "#^/index/([0-9]+)/([0-9]+)/#",
    "RULE" => "mode=read&CID=$1&GID=$2",
    "PATH" => "/newforum/index.php",
)

when applied to the address:

/index/5/48/

will execute the following code:

$url = preg_replace("#^/index/([0-9]+)/([0-9]+)/#",
                    "/newforum/index.php?mode=read&CID=$1&GID=$2",
                    "/index/5/48/");

which will produce the following result:

/newforum/index.php?mode=read&CID=5&GID=48
Example 2

The rule:

array(
    "CONDITION" => "#(.+?)\\.html(.*)#",
    "RULE" => "$1.php$2",
)

in reply to requesting the following page:

/about/company.html?show

will execute the following code to build the real address:

$url = preg_replace("#(.+?)\\.html(.*)#", "$1.php$2", "/about/company.html?show");

and call the script:

/about/company.php?show

A rule can contain the name of a component that created the rule. The component name should be specified in the "ID" key. When the rule definition file (urlrewrite.php) is recreated using the Control Panel tools, only the rules with the valid "ID" key are modified. These rules are recreated by analyzing files in the site directory. The rules whose ID key is empty are not changed.

Activating URL rewrite engine

The URL rewrite engine must be activated before it can be used. The following actions need to be performed to activate the engine:

  • if your web server is configured to trap the 404 error (e.g. directive ErrorDocument 404 /404.php for Apache), you will have to edit the file /404.php, by inserting the following command at the very beginning of the file:
    include_once($_SERVER['DOCUMENT_ROOT'].
                 '/bitrix/modules/main/include/urlrewrite.php');
  • if you use mod_rewrite with Apache, specify the following in its settings (e.g. in .htaccess):
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !/bitrix/urlrewrite.php$
    RewriteRule ^(.*)$ /bitrix/urlrewrite.php [L]
</IfModule>

Components 2.0 Support

When a SEF-enabled component is added to a page and latter is saved using API functions, a corresponding URL rewrite rule is created automatically. However, if a page is created not using API functions (e.g. uploaded via FTP), you will have to re-create rules manually by using tools in the URL rewrite administration form.

In a component, SEF support can be enabled by specifying a special input parameter SEF_MODE. This will set the predefined parameter SEF_FOLDER to the folder in which the component runs. The folder can be virtual (i.e. it may or may not physically exist). When a page with a SEF-enabled component (SEF_MODE is Y) is saved, a URL rewrite rule is created in the following way:

  • the CONDITION key is set to a regular expression obtained from the SEF_FOLDER parameter;
  • the ID key is set to the component name;
  • the PATH key is set to the physical address of the page.

Consider the following example. A "bitrix:catalog" component is added to /fld/c.php. It is activated by the following call:

$APPLICATION->IncludeComponent(
    "bitrix:catalog",
    "",
    Array(
        "SEF_MODE" => "Y",
        "SEF_FOLDER" => "/mycatalog/",
        "IBLOCK_TYPE_ID" => "catalog",
        "BASKET_PAGE_TEMPLATE" => "/personal/basket.php",
    )
);

When a page /fld/c.php is saved, the following record will appear in the URL rewrite rules:

array(
    "CONDITION" => "#^/mycatalog/#",
    "RULE" => "",
    "ID" => "bitrix:catalog",
    "PATH" => "/fld/c.php",
)

Thus, requesting a page starting from /mycatalog/ will return the file /fld/c.php. This script may analyse the requested address and act appropriately.

© 2001-2007 Bitrix Bitrix Site Manager


Technology

This section outlines general concepts on the technologies used in the system.

  • Agents - technology which allows running PHP functions (agents) at the specified time interval.
  • Mail subsystem - sends e-mail messages using e-mail templates.
  • Caching - enables caching of resource consuming code sections while increasing the site performance.
  • Delay functions - enable to specify the page title, navigation chain items, CSS, control toolbar buttons, meta tags etc. by calling functions within the page body.
  • User transfer - allows to synchronize cookies between different sites having different domain names within the same portal .
  • Control toolbar - technology making administration and maintenance easier.
  • Events - enables developers to handle system notifications, process them and change the site operation according to their needs.
  • External authorization - provides for implementing custom external authorization systems, in addition to standard built-in authorization system.


Agents

Agents is the technology which allows running PHP functions (agents) at the specified time interval.

When a page starts execution (before the OnPageStart event) the system automatically checks for pending agents and executes them if required.

Note
The agent run time precision depends on the site traffic density and uniformity. If you need to precisely run any PHP function at the time specified, you should use the system cron utility, which is supplied by most of hosting providers.

To run the agent at the specified time, the calling code should register it in the system using the method CAgent::AddAgent. You can unregister the agent function by calling CAgent::RemoveAgent.

If the agent function is a member of a module, that module will be automatically included which involves including the file /bitrix/modules/module ID/include.php. If this is the case, you have to ensure that the agent function is available after the above mentioned file is included.

If the agent function is not a member of a module, it should be placed in the file /bitrix/php_interface/init.php. This file is automatically included in the prologue.

The following should be considered when creating agent functions.

  • A global object $USER of the CUser class is not available in the agent function. If you intend to use this object, place the following code prior to calling any of the CUser class methods:

    global $USER;
if (!is_object($USER))
    $USER = new CUser;
  • As a return value, the agent function should return a PHP code that will be used at the next call to this function.

Example

<?
// add agent of the Statistics module
CAgent::AddAgent(
    "CStatistic::CleanUpStatistics_2();", // function name
    "statistic",                          // module ID
    "N",                                  // number of executions is not critical
    86400,                                // time out is 24 hours
    "07.04.2005 20:03:26",                // time of the first check
    "Y",                                  // agent is active
    "07.04.2005 20:03:26",                // time of the first execution
    30);
?>
<?
// add agent of the Techsupport module
CAgent::AddAgent(
    "CTicket::AutoClose();",  // function name
    "support",                // module ID
    "N",                      // number of executions is not critical
    86400,                    // time out is 24 hours
    "",                       // time of the first check; use current time
    "Y",                      // agent is active
    "",                       // time of the first execution; use current time
    30);
?>
<?
// add an agent which is not a member of any module
CAgent::AddAgent("My_Agent_Function();");
?>

<?
// file /bitrix/php_interface/init.php

function My_Agent_Function()
{
   // perform any action
   return "My_Agent_Function();";
}
?>
<?
// add an agent of my_module

CAgent::AddAgent(
   "CMyModule::Agent007(1)",
   "my_module",
   "Y",
    86400);
?>

<?
// execute this agent 7 times, once per 24 hours,
// and unregister it afterwards.

Class CMyModule
{
   function Agent007($cnt=1)
   {
      echo "Hello!";
      if($cnt>=7)
         return "";
      return "CMyModule::Agent007(".($cnt+1).")";
   }
}
?>

See Also

CAgent class
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Mail subsystem

Mail subsystem is the technology used to handle e-mail messages within a site.

The mail system operation includes the following stages:

  1. Creating a mail event type. A mail event type can be created using the function CEventType::Add only.
  2. Creating a mail template. Can be accomplished in the administrative menu Mail templates, as well as using the CEventMessage::Add function.
  3. Creating a mail event. A mail event can be created using the function CEvent::Send only.

When a page finishes execution, the function CEvent::CheckEvents is called automatically. This function is used to accomplish the following main tasks:

  1. select unprocessed mail events from the table b_event;
  2. use the above selected events to generate e-mail messages;
  3. send these messages;
  4. write one of the following values as the send result to the table b_event in the field SUCCESS_EXEC:
    • Y - all messages with all mail templates have been successfully sent;
    • F - all messages with all mail templates could not be sent;
    • P - some messages have been sent successfully, while some messages have failed to send;
    • 0 - mail templates could not found;
    • N - the mail event has not yet been processed by the function CEvent::CheckEvents.

Developers can can affect sending messages by modifying the following settings of the Kernel module:

  • Convert Unix new line symbols to Windows format during email sending
  • Convert 8-bit characters in the message header
  • One or comma-separated list of E-mail addresses to receive copies of all the outcoming messages
  • E-mail address in caption
  • Send email event and template identifiers in message

Besides the above parameters, the constant ONLY_EMAIL can be used. If initialized, it allows to send all messages only to the specified address or group of addresses.

Example of creating the mail event type

<?
$obEventType = new CEventType;
$obEventType->Add(array(
    "EVENT_NAME"    => "ADV_BANNER_STATUS_CHANGE",
    "NAME"          => "Banner status changed",
    "SITE_ID"       => "en",
    "DESCRIPTION"   => "
        #ID# - banner ID
        #CONTRACT_ID# - contract ID
        #TYPE_SID# - type ID
        "
    ));
?>

Example of creating the mail template

<?
$arr["ACTIVE"]      = "Y";
$arr["EVENT_NAME"]  = "ADV_BANNER_STATUS_CHANGE";
$arr["SITE_ID"]     = array("fr","en");
$arr["EMAIL_FROM"]  = "admin@site.com";
$arr["EMAIL_TO"]    = "admin@site.fr";
$arr["BCC"]         = "";
$arr["SUBJECT"]     = "Banner #ID# status changed";
$arr["BODY_TYPE"]   = "text";
$arr["MESSAGE"]     = "
Note! Banner # #ID# status changed.
Banner type: #TYPE_SID#
Contract ID: #CONTRACT_ID#
";
$obTemplate = new CEventMessage;
$obTemplate->Add($arr);
?>

Example of creating the mail event

<?
$arFields = array(
    "ID"          => 124,
    "CONTRACT_ID" => 1,
    "TYPE_SID"    => "LEFT"
    );
CEvent::Send("ADV_BANNER_STATUS_CHANGE",
             array("ru", "en"), $arFields);
?>

See Also

  • CEvent class
  • CEventMessage class
  • CEventType class
  • Kernel module settings


Caching

Caching is a technology which enables to cache the results of rarely updated and resource consuming code areas (for example, those handling the database).

The following two classes are used to implement this:

  • CPageCache - used to cache HTML;
  • CPHPCache - used to cache HTML and PHP variables.

Caching results are stored as files in the directory /bitrix/cache/. If the cache is not expired, a preliminary created caching file is included instead of the resource consuming code.

The correct use of cache allows to greatly increase the total site efficiency. However, it should be taken into account that unwise use of caching may bring about a serious grow of the /bitrix/cache/ directory size.

Example of HTML caching

<?
// create an object
$obCache = new CPageCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$IBLOCK_TYPE.$USER->GetUserGroupString();

// initialise buffered output
if($obCache->StartDataCache($life_time, $cache_id, "/")):

    // obtain the information block element parameters from the database
    if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
        echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
    endif;

    // write the preliminary buffered output to the cache file
    $obCache->EndDataCache();

endif;
?>

In this example, the method CPageCache::StartDataCache checks the existence of the cache file which is valid and not expired. If such file exists, it is included and displayed, otherwise buffering is turned on. The buffered output is written to the cache file using the method CPageCache::EndDataCache.

The first parameter of the method CPageCache::StartDataCache specifies the time interval, in seconds, during which the cache file is valid and is not expired (the interval is counted from the cache file create time).

The second parameter contains the unique identifier of the cache instance. It should be mentioned that if any variables may affect the result of the cached code execution, their values are to be included in this identifier.

For example:

  • If the current user authorization can affect the result of the cached code execution, the result of the CUser::GetUserGroupString function execution must be added to the identifier. This methos returns the string containing the current user groups ID.
  • If you use pagewise navigation in the cached code, the CDBResult::NavStringForCache return value must be added to this identifier.
  • It should be kept in mind that when using sorting, the sort order and values of variables containing the sorting field the must be included in this identifier.

Example of caching HTML and PHP variables

<?
// create an object
$obCache = new CPHPCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$SECTION_ID.$USER->GetUserGroupString();

// if the cache exists and is not expired...
if($obCache->InitCache($life_time, $cache_id, "/") :
    // obtain cached variables
    $vars = $obCache->GetVars();
    $SECTION_TITLE = $vars["SECTION_TITLE"];
else :
    // otherwise call the database
    $arSection = GetIBlockSection($SECTION_ID);
    $SECTION_TITLE = $arSection["NAME"];
endif;

// add a menu item to the navigation chain
$APPLICATION->AddChainItem($SECTION_TITLE, $SECTION_URL."SECTION_ID=".$SECTION_ID);

// start buffered output
if($obCache->StartDataCache()):

    // obtain the information block element parameters from the database
    if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
        echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
    endif;

    // write the preliminary buffered output to the cache file
    // together with an additional variable
    $obCache->EndDataCache(array(
        "SECTION_TITLE"    => $SECTION_TITLE
        ));
endif;
?>

This example differs from the previous in caching the PHP variable $SECTION_TITLE in addition to the HTML code. Structure and type of the cached PHP variables is arbitrary. The method CPHPCache::InitCache checks if the unexpired and valid cache file exists. If this file is found, it is included; all the cached variables are available after the method CPHPCache::GetVars returns. The method CPHPCache::EndDataCache writes PHP variables and the buffered HTML code to the cache file.

Note!
To disable caching for a single page, you should authorize with administrative rights and open this page with the parameter &clear_cache=Y. Calling a page with parameter &clear_cache_session=Y after authorization will disable caching for all the session pages. Cache files can be deleted in the administrative section on the settings page of the Kernel module.

See Also

  • CPageCache class
  • CPHPCache class


Delay functions

Delay functions enable to specify the page title, navigation chain items, CSS, control toolbar buttons, meta tags etc. by calling functions within the page body and emit the return values of these functions in the prologue , that is, place these values in the code generated earlier.

This technology has been developed mainly for use in components, which are usually placed in the page body but may want to set the page title, add items to navigation chain, add buttons to the control toolbar etc.

Note
The delay functions technology is used in the public section only. It is not intended for use in the administrative section.

How it works

This technology works by the following algorithm.

  1. All the PHP script output is buffered.
  2. If a script calls one of the following functions:
    • CMain::ShowTitle
    • CMain::ShowCSS
    • CMain::ShowNavChain
    • CMain::ShowProperty
    • CMain::ShowMeta
    • CMain::ShowPanel
    (or any other function for which delaying is enabled), the following operations are performed:
    1. the entire buffered output is stored in the next element of the stack A;
    2. an empty element is added to the stack A in which the result of the delay function execution is stored later;
    3. name of the delay function is stored in the stack B;
    4. the buffer empties and the buffering starts again.
    Thus, the stack A stores the entire page content split into sections. This stack also contains empty elements to be filled with the delay function execution results.

    The stack B stores names and parameters of the delay functions, in the order they appear in the code.

  3. When the script is about to finish execution, the epilogue service section performs the following actions:
    1. all the delay functions stored in the stack B are executed consequently;
    2. their results are placed in the previously allocated elements of the stack A;
    3. contents of the stack A is merged (concatenated) and displayed.

Therefore, this technology enables to fragment the page content splitting it into sections using functions that allow delaying execution of other functions. At the end of the page, all delay functions are executed consequently and their results are inserted in spots previously allocated in the fragmented page content. Then, all the fragmented content is merged, sent to the output stream and dispatched to a client's browser.

Consideration must be given to the fact that no operation may be performed on results of the functions that may cause other functions to be delayed. For example:

$page_title = $APPLICATION->ShowTitle(); // returns nothing
if (strlen($page_title)<=0)
    $page_title = "Default title";
echo
    $page_title;
This code is not functional because all delay functions are executed at the end of the page, in the epilogue service section.

Functions involved in this technology

Name of the delaying function Delays execution of these functions Additionally involved functions
CMain::ShowTitle CMain::GetTitle CMain::SetTitle
CMain::ShowCSS CMain::GetCSS CMain::SetTemplateCSS
CMain::SetAdditionalCSS
CMain::ShowNavChain CMain::GetNavChain CMain::AddChainItem
CMain::ShowProperty CMain::GetProperty CMain::SetPageProperty
CMain::SetDirProperty
CMain::ShowMeta CMain::GetMeta CMain::SetPageProperty
CMain::SetDirProperty
CMain::ShowPanel CMain::GetPanel CMain::AddPanelButton

See Also

  • CMain::AddBufferContent


User transfer

The Bitrix Site Manager system provides for creating and managing more than one site using a single product copy. Such multiple site system features the following peculiarities:
  • common permissions for all sites;
  • common set of user accounts for all sites;
  • unified statistics for all sites etc.
Hence, a problem arises to distinguish a user visiting different sites having different domain name. The problem in question concerns sites created in the context of a single portal.

User recognition is achieved using the stored cookie storing the information sent by the web server to a client browser. Cookies are stored on a client hard drive.

The following example will help you understand the gist of the problem.

  • When a visitor opens a site A for the first time, he is assigned a set of identifiers used by the variety of modules (e.g. a user ID in the Statistics module or a customer ID int the e-Store module etc.). These identifiers are stored in cookie of the site A.
  • When the visitor opens a site A later, he will be recognized by the information stored in cookie of the site A.
  • Now imagine the visitor open the site B. The problem is to recognize him as a visitor who opened the site A recently. By saying "to recognize" we imply obtaining identifiers that he have been given when opening the site A. Things may get worse if the site B domain name differs from that of the site A: information stored in cookie of the site A cannot be retrieved by the site B, and vice versa: cookie set by the site A cannot be assigned to the site B. This is stipulated by the browser security policy.

To overcome these difficulties, a technology has been developed allowing to transfer user cookie between different sites with different domain names but created within the same portal. This technology is also called UserMultiSiteTransfer.

The described technology functions by the following algorithm.

  • When a visitor opens the site A, identifiers that the system assigns to him are stored in cookie by calling CMain::set_cookie, whose main purpose is not only set cookie for the current site A, but also store the cookie data for further spread to other sites (B, C, D).
  • In the end of the epilogue visual section, the method CMain::ShowSpreadCookieHTML is called. This method displays a number of IFRAME's each calling the script /bitrix/spread.php of the domain for which the cookie is to be set. Thus, the system creates 3 IFRAME's for each of the sites B, C and D each calling the script http://site_domain_name/bitrix/spread.php. The system passes all the information required by this script to set cookie. The information passed is strongly encrypted and signed with the encrypted license key of the portal. The result is that the cookie set by the site A is copied (transferred) to sites B, C and D.
  • The similar operations are performed for other sites. If a visitor opens the site B and obtains an identifier that should be stored in cookie, this identifier will be stored for sites A, C and D. This ensures a unified set of cookie are set for all sites of the single portal.

This technology allows the Statistics module to register unique visitors of the whole portal. The Advertising and banners module becomes able to correctly count the number of a banner shows to a specific visitor. Other modules make an active use of this technology as well.

See Also

  • Sites
  • CMain::set_cookie
  • CMain::get_cookie
  • CMain::ShowSpreadCookieHTML


Control toolbar

Control toolbar is the HTML code viewable by an authorized user having enough permissions to execute operations provided by the toolbar buttons. This HTML code displays an area containing buttons, at the top of a page. Each of these buttons is used to perform a specific operation.

In the public section, the toolbar is displayed using the CMain::ShowPanel function which uses delay function technology, allowing to add buttons to the panel directly from the page body code.

A button can be added to the toolbar by calling CMain::AddPanelButton. This function can be used in the script /bitrix/php_interface/include/add_top_panel.php, which is automatically included when displaying the toolbar.

The toolbar is not the essential part of the Bitrix Site Manager system, but it is a convenient way to administer the site. Currently, the following standard buttons are supported, each of them performing the corresponding operation:

  • - creates a new folder in the Site Explorer module;
  • - edits the folder properties in the Site Explorer module;
  • - creates a new page in the in the Site Explorer module;
  • - edits the current page in the Site Explorer module;
  • - creates a new page using the Workflow module;
  • - edits the current page using the Workflow module;
  • - switches to the current page editing history in the Workflow module;
  • - creates a new information block in the Information blocks module;
  • - edits a new information block in the Information blocks module;
  • - creates a new section in the Information blocks module;
  • - edits a section in the Information blocks module;
  • - creates a new element in the Information blocks module;
  • - edits an element in the Information blocks module;
  • - switches to the element editing history in the Information blocks module;
  • - shows or hides include areas by framing them in borders. The include area frame can display the following buttons in the top right corner:
    • - edits the component included from the module distribution package;
    • - edits a file (component) stored in /bitrix/templates/.default/, or in /bitrix/templates/current site template ID/;
    • - edits a file using the Workflow module;
    • - edits the current banner in the Advertising module;
    • - switches to a list of banners in the Advertising module;
    • - edits menu template;
    • - edits menu items;
    • - edits the navigation chain template.
  • - switches to the Administrative section;
  • - logs off the authorised session.

See Also

  • CMain::ShowPanel
  • CMain::AddPanelButton
  • CMain::IncludeFile
  • CMain::IncludeString
  • CMain::GetShowIncludeAreas


External authorization

Sometimes, developers want to use their own user authorization algorithms or store users' credentials in external databases. For example, you may have an existing user database and want to allow those users to authorize at the site. In rare cases, it is possible to simply transfer user accounts to the CMS database using the CMS API. Nevertheless, in most cases this approach is not applicable due to the following reasons. The first reason is that user passwords are usually stored as unrecoverable hash values, so users will not be able to authorize after the transfer because of password failure. The second reason is that some system architectures require users' credentials to be stored in a centralized remote storage server for distributed authorization in different locations, including the CMS.

The Bitrix Site Manager provides for implementing custom external authorization systems, in addition to standard built-in authorization system. This section describes steps required for proper developing of such system. The PHP BB forum is used as an example to demonstrate basic guidelines that a developer should consider.

As a start-off, create a file /bitrix/php_interface/scripts/phpbb.php. This file will contain a class with the external authorization processor implementation: __PHPBB2Auth:

class __PHPBB2Auth
{
}

We have to implement and register a handler of the OnUserLoginExternal event that will be called upon each authorization attempt, immediately after a user enters the login and password and immediately before the built-in authorization routine. To do so, add a call to AddEventHandler to the file /bitrix/php_interface/init.php:

AddEventHandler(
     "main",
     "OnUserLoginExternal",
     Array("__PHPBB2Auth", "OnUserLoginExternal"),
     100,
     $_SERVER['DOCUMENT_ROOT'].'/bitrix/php_interface/scripts/phpbb.php'
);

The registered handler is a member of our class: __PHPBB2Auth::OnUserLoginExternal. As a parameter, the OnUserLoginExternal event handler accepts a reference to the array with fields to be verified:

define("PHPBB2_TABLE_PREFIX", "phpbb_");
function OnUserLoginExternal(&$arArgs)
{
    $table_user = PHPBB2_TABLE_PREFIX."users";
    $table_user_group = PHPBB2_TABLE_PREFIX."user_group";
    extract($arArgs);

    global $DB, $USER, $APPLICATION;

    $strSql = "SELECT * FROM ".$table_user.
              " WHERE username='".$DB->ForSQL($login).
              "' AND user_password='".
              $DB->ForSql(md5($password))."'";
    $dbRes = $DB->Query($strSql);
    if ($arRes = $dbRes->Fetch())
    {
        if ($arRes['user_active']!='0')
        {
            // both login and password match
        }
    }
}

Now that the login and password are verified using the PHPBB algorithm, we have to create an external user in the domestic database so that native objects (news, polls etc.) can be used with it. To perform this, a method CUser::GetList is called with a filter by login name and the external authorization source ID. If a user cannot be found, we have to create it. Otherwise, just refresh the users information in the database.

$arFields = Array(
    "LOGIN" => $login,
    "NAME" => $login,
    "PASSWORD" => $password,
    "EMAIL" => $arRes['user_email'],
    "ACTIVE" => "Y",
    "EXTERNAL_AUTH_ID"=>"PHPBB2",
    "LID" => SITE_ID
    );
$oUser = new CUser;
$res = CUser::GetList($O,
                      $B,
                      Array("LOGIN_EQUAL_EXACT" => $login,
                            "EXTERNAL_AUTH_ID"  => "PHPBB2"));
if (!($ar_res = $res->Fetch()))
    $ID = $oUser->Add($arFields);
else
{
    $ID = $ar_res["ID"];
    $oUser->Update($ID, $arFields);
}

if ($ID>0)
{
   // can be authorized
   return $ID;
}

Now we have the user ID valid in the scope of our database. At this stage, we can return it from the event handler. But remember that the user is still anonymous as it is not bound to any user group. We can use the existing PHPBB binding information and pass it to our database prior to authorization.

$USER->SetParam("PHPBB2_USER_ID", $arRes['user_id']);
$groups_map = Array(
    /*'PhpBB2 Group ID' => 'Local Group ID',*/
     '2' => '1'
    );

$user_groups = Array();
$dbUserGroup = $DB->Query('SELECT * FROM '.
                          $table_user_group.
                          ' WHERE user_id='.
                          $arRes['user_id']);
while ($arUserGroup = $dbUserGroup->Fetch())
    $user_groups[] = $arUserGroup['group_id'];

if (count($user_groups)>0)
{
    $arUserGroups = CUser::GetUserGroup($ID);
    foreach ($groups_map as $ext_group_id => $group_id)
    {
        if (in_array($ext_group_id, $user_groups))
            $arUserGroups[] = $group_id;
        else
        {
            $arUserGroupsTmp = Array();
            foreach($arUserGroups as $grid)
                if($grid != $group_id)
                    $arUserGroupsTmp[] = $grid;
            $arUserGroups = $arUserGroupsTmp;
        }
    }
    CUser::SetUserGroup($ID, $arUserGroups);
}

Now, the local user account corresponds to the remote one and we can return the user ID to finish authorization. The final touch is to made; clear the "remember me" flag just in case the user checked it as we cannot verify the permissions correctly:

$arArgs["store_password"] = "N";
return $ID;

To register the just created authorization algorithm in the system, we have to process the OnExternalAuthList event. Add the corresponding call to the file /bitrix/php_interface/init.php:

AddEventHandler(
     "main",
     "OnExternalAuthList",
     Array("__PHPBB2Auth", "OnExternalAuthList"),
     100,
     $_SERVER['DOCUMENT_ROOT'].'/bitrix/php_interface/scripts/phpbb.php'
     );

The event handler should return an array containing information on the provided authorization handlers: the ID and the name of the handler.

function OnExternalAuthList()
{
    return Array(
        Array("ID"=>"PHPBB2", "NAME"=>"PhpBB2")
        );
}

Now the user editing page displays a combo box containing a list of external authorization sources. The code below show a complete file /bitrix/php_interface/scripts/phpbb.php. In addition to the above described algorithm, it implements the reverse scheme: a user is automatically authorized in the forum upon authorization in the system.

<?
define("PHPBB2_TABLE_PREFIX", "phpbb_");

class __PHPBB2Auth
{
    function OnUserLoginExternal(&$arArgs)
    {
        ////////// <settings> ////////////
        $table_user = PHPBB2_TABLE_PREFIX."users";
        $table_user_group = PHPBB2_TABLE_PREFIX."user_group";
        $groups_map = Array(
            /*'PhpBB2 Group ID' => 'Local Group ID',*/
            '2' => '1'
            );
        ////////// </settings> ////////////
        extract($arArgs);

        global $DB, $USER, $APPLICATION;

        $strSql = "SELECT * FROM ".$table_user.
                  " WHERE username='".$DB->ForSQL($login).
                  "' AND user_password='".
                  $DB->ForSql(md5($password))."'";
        $dbRes = $DB->Query($strSql);
        if ($arRes = $dbRes->Fetch())
        {
            if ($arRes['user_active']!='0')
            {
                $arFields = Array(
                    "LOGIN" => $login,
                    "NAME" => $login,
                    "PASSWORD" => $password,
                    "EMAIL" => $arRes['user_email'],
                    "ACTIVE" => "Y",
                    "EXTERNAL_AUTH_ID"=>"PHPBB2",
                    "LID" => SITE_ID
                    );
                $oUser = new CUser;
                $res = CUser::GetList($O,
                                      $B,
                                      Array("LOGIN_EQUAL_EXACT" => $login,
                                            "EXTERNAL_AUTH_ID"  => "PHPBB2"));
                if (!($ar_res = $res->Fetch()))
                    $ID = $oUser->Add($arFields);
                else
                {
                    $ID = $ar_res["ID"];
                    $oUser->Update($ID, $arFields);
                }

                if($ID>0)
                {
                    $USER->SetParam("PHPBB2_USER_ID", $arRes['user_id']);

                    $user_groups = Array();
                    $dbUserGroup = $DB->Query('SELECT * FROM '.
                                              $table_user_group.
                                              ' WHERE user_id='.
                                              $arRes['user_id']);
                    while($arUserGroup = $dbUserGroup->Fetch())
                        $user_groups[] = $arUserGroup['group_id'];

                    if(count($user_groups)>0)
                    {
                        $arUserGroups = CUser::GetUserGroup($ID);
                        foreach($groups_map as $ext_group_id => $group_id)
                        {
                            if (in_array($ext_group_id, $user_groups))
                                $arUserGroups[] = $group_id;
                            else
                            {
                                $arUserGroupsTmp = Array();
                                foreach ($arUserGroups as $grid)
                                    if ($grid != $group_id)
                                        $arUserGroupsTmp[] = $grid;
                                $arUserGroups = $arUserGroupsTmp;
                            }
                        }
                        CUser::SetUserGroup($ID, $arUserGroups);
                    }
                    $arArgs["store_password"] = "N";

                    return $ID;
                }
            }
        }
    }

    function OnExternalAuthList()
    {
        return Array(
            Array("ID"=>"PHPBB2", "NAME"=>"PhpBB2 Board")
            );
    }

    function OnAuthorize(&$arArgs)
    {
        extract($arArgs);

        global $DB, $APPLICATION, $USER;
        $user_id = $USER->GetParam("PHPBB2_USER_ID");
        if($user_id<=0)
            return;
        $table_user = PHPBB2_TABLE_PREFIX."users";
        $table_sessions = PHPBB2_TABLE_PREFIX."sessions";
        $table_config = PHPBB2_TABLE_PREFIX."config";

        $dbConfig = $DB->Query("SELECT * FROM ".
                               $table_config.
                               " WHERE config_name IN ('cookie_name',
                                                       'cookie_path',
                                                       'cookie_domain',
                                                       'cookie_secure')");
        while($arConfig = $dbConfig->Fetch())
            ${$arConfig['config_name']} = $arConfig['config_value'];

        if(isset($HTTP_COOKIE_VARS[$cookie_name . '_sid']) ||
           isset($HTTP_COOKIE_VARS[$cookie_name . '_data']))
        {
            $session_id = isset($HTTP_COOKIE_VARS[$cookie_name . '_sid']) ?
                            $HTTP_COOKIE_VARS[$cookie_name . '_sid'] : '';
        }

        $ip_sep = explode('.', $_SERVER['REMOTE_ADDR']);
        $user_ip = sprintf('%02x%02x%02x%02x',
                           $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
        $current_time = time();
        $sql =
            "UPDATE ".$table_sessions." SET ".
            "    session_user_id = ".$user_id.", ".
            "    session_start = ".$current_time.", ".
            "    session_time = ".$current_time.", ".
            "    session_page = 0, ".
            "    session_logged_in = 1 ".
            "WHERE session_id = '".$DB->ForSQL($session_id)."' ".
            "    AND session_ip = '".$user_ip."'";

        $r = $DB->Query($sql);
        if($r->AffectedRowsCount()<=0)
        {
            $session_id = md5(uniqid($user_ip));
            $sql =
                "INSERT INTO ".$table_sessions.
                "(session_id, session_user_id,".
                " session_start, session_time, session_ip,".
                " session_page, session_logged_in)".
                "VALUES ('".$session_id."', ".
                $user_id.", ".$current_time.", ".
                $current_time.", '".$user_ip."', 0, 1)";
            $DB->Query($sql);
        }

        $sql =
            "UPDATE ".$table_user." SET ".
            "    user_session_time = ".$current_time.", ".
            "    user_session_page = 0, ".
            "    user_lastvisit = ".$current_time." ".
            "WHERE user_id = ".$user_id;

        $DB->Query($sql);

        $sessiondata = Array('userid' => $user_id);

        setcookie($cookie_name.'_data',
                  serialize($sessiondata),
                  $current_time + 31536000,
                  $cookie_path, $cookie_domain,
                  $cookie_secure);
        setcookie($cookie_name.'_sid',
                  $session_id, 0,
                  $cookie_path, $cookie_domain,
                  $cookie_secure);
    }
}
?>

The following lines should be added to /bitrix/php_interface/init.php:

<?
AddEventHandler(
    "main",
    "OnUserLoginExternal",
    Array("__PHPBB2Auth", "OnUserLoginExternal"),
    $_SERVER['DOCUMENT_ROOT'].
    '/bitrix/php_interface/scripts/phpbb.php'
    );
AddEventHandler(
    "main",
    "OnExternalAuthList",
    Array("__PHPBB2Auth", "OnExternalAuthList"),
    $_SERVER['DOCUMENT_ROOT'].
    '/bitrix/php_interface/scripts/phpbb.php'
    );
AddEventHandler(
    "main",
    "OnAfterUserAuthorize",
    Array("__PHPBB2Auth", "OnAuthorize")
    );
?>

The following example shows a script for use with the Invision Power Board forum.

<?
define("IPB_TABLE_PREFIX", "ibf_");
define("IPB_VERSION", "2");

AddEventHandler("main",
                "OnUserLoginExternal",
                Array("__IPBAuth", "OnUserLoginExternal"));
AddEventHandler("main",
                "OnExternalAuthList",
                Array("__IPBAuth", "OnExternalAuthList"));

class __IPBAuth
{
    function OnUserLoginExternal(&$arArgs)
    {
        extract($arArgs);

        ////////// <settings> ////////////
        $table_user = IPB_TABLE_PREFIX."members";
        $table_converge = IPB_TABLE_PREFIX."members_converge";
        $groups_map = Array(
            /*'IPB Group ID' => 'Local Group ID',*/
            '4' => '1'
            );
        ////////// </settings> ////////////

        global $DB, $USER, $APPLICATION;

        if(IPB_VERSION == '1')
        {
            $strSql = "SELECT * FROM ".$table_user.
                      " WHERE name='".$DB->ForSql($login).
                      "' AND password='".md5($password)."'";
        }
        else
        {
            $strSql =
                "SELECT t1.* ".
                "FROM ".$table_user." t1, ".$table_converge." t2 ".
                "WHERE t1.name='".$DB->ForSql($login)."' ".
                "    AND t1.email = t2.converge_email ".
                "    AND t2.converge_pass_hash = ".
                "MD5(CONCAT(MD5(t2.converge_pass_salt), '".
                md5($password)."'))";
        }

        $dbAuthRes = $DB->Query($strSql);
        if($arAuthRes = $dbAuthRes->Fetch())
        {
            $arFields = Array(
                "LOGIN" => $login,
                "NAME" => $arAuthRes['title'],
                "PASSWORD" => $password,
                "EMAIL" => $arAuthRes['email'],
                "ACTIVE" => "Y",
                "EXTERNAL_AUTH_ID"=>"IPB",
                "LID" => SITE_ID
                );

            $oUser = new CUser;
            $res = CUser::GetList($O,
                                  $B,
                                  Array("LOGIN_EQUAL_EXACT"=>$login,
                                        "EXTERNAL_AUTH_ID" =>"IPB"));
            if(!($ar_res = $res->Fetch()))
                $ID = $oUser->Add($arFields);
            else
            {
                $ID = $ar_res["ID"];
                $oUser->Update($ID, $arFields);
            }

            if($ID>0)
            {
                $USER->SetParam("IPB_USER_ID", $arAuthRes['id']);

                $user_group = $arAuthRes['mgroup'];
                $arUserGroups = CUser::GetUserGroup($ID);
                foreach($groups_map as $ext_group_id => $group_id)
                {
                    if($ext_group_id==$user_group)
                        $arUserGroups[] = $group_id;
                    else
                    {
                        $arUserGroupsTmp = Array();
                        foreach($arUserGroups as $grid)
                            if($grid != $group_id)
                                $arUserGroupsTmp[] = $grid;
                        $arUserGroups = $arUserGroupsTmp;
                    }
                }
                CUser::SetUserGroup($ID, $arUserGroups);
                $arArgs["store_password"] = "N";

                return $ID;
            }
        }
    }

    function OnExternalAuthList()
    {
        return Array(
            Array("ID"=>"IPB", "NAME"=>"Invision Power Board")
            );
    }
}
?>

The above script file should be registered in /bitrix/php_interface/init.php for it to become effective.

See Also

  • AddEventHandler
  • OnUserLoginExternal
  • OnExternalAuthList
  • Handling events


Handling events

Sometimes, a developer needs to affect execution of an API function in some aspect. But, if a function is changed manually, these modifications will be lost during the next update session. To enable developers affect the system logic, the events system has been developed. Many API functions call the event handlers during their execution.

To install an appropriate handler function for a specific event, a handler registration function should be called. Currently, the system provides the following two methods: AddEventHandler and RegisterModuleDependences. A set of events for each module is described in the corresponding module help section. For example, the events of the Kernel module can be found in this topic.

The information below highlights upon the handler function registration.

RegisterModuleDependences registers module specific handlers (located in modules) used for the system modules interaction. This function is to be called once when a module is being installed. After calling this function, the event hander will be called automatically; the module will included prior to calling the handler.

Example

// the compression module handlers are registered twice:
// at the beginning and in the end of each page
RegisterModuleDependences("main", "OnPageStart", "compression",
                          "CCompress", "OnPageStart", 1);
RegisterModuleDependences("main", "OnAfterEpilog", "compression",
                          "CCompress", "OnAfterEpilog");

// the advertising module installer registers an empty handler:
// when the event OnBeforeProlog occurs,
// the advertising module is included for each page, which enables
// calling its API functions without including it in the page body explicitly
RegisterModuleDependences("main", "OnBeforeProlog", "advertising");

AddEventHandler registers arbitrary handlers which are not located in any module. It is to be called before an event occurs on pages where this event is to be handled. For example, if an event is to be handled on all pages, the function can be called in /bitrix/php_interface/init.php.

Example

// register handler in /bitrix/php_interface/init.php
AddEventHandler("main",
                "OnBeforeUserLogin",
                "MyOnBeforeUserLoginHandler");

function MyOnBeforeUserLoginHandler($arFields)
{
   if (strtolower($arFields["LOGIN"]) == "guest")
   {
       global $APPLICATION;
       $APPLICATION->throwException("User with the username Guest cannot be authorized.");
       return false;
   }
}

Usually, events are divided into the following groups: according to the location of origin and purpose:

  • events intended to cancel further execution of a method. For example, the event OnBeforeDeleteUser allows to cancel a user removal with the conditions specified (critical bound objects), the event OnBeforeUserLogin allows to prohibit authorization;
  • events which are fired after performing some operation. For example, OnAfterUserLogin fires after verifying the username and password, the event OnUserDelete - before the user is removed from the database. Allows to delete the bound objects;
  • events which are fired during a page execution to enable a developer to include the custom code in the definite location of the page. For example, the event OnBeforeProlog (see also page execution order).

The more detailed information about an event rise locations and possible use can be found in the description of each event.

See Also

  • AddEventHandler
  • RegisterModuleDependences
  • Interaction of modules
  • Events
  • Page execution order


Modules

Introduction

The Bitrix Site Manager ships in different editions. Each edition is a set of standard modules. Additionally, custom modules may be created for use with the system. The number of modules that can be installed in the system is unlimited.

This section discloses principles of creating custom modules.

In this section

  • Structure of files - depicts the structure of files required to be included in a module ;
  • Administrative scripts - describes how the module scripts run in the administrative section;
  • Administrative menu - describes how the module administrative menu functions;
  • Language files - outlines the language files' storage layout and how to include them in administrative scripts and module components;
  • Module description - describes the class used to manipulate the module (install, uninstall, get a list of rights etc.);
  • Installation - outlines actions required to be performed during the installation;
  • Uninstallation - outlines actions required to be performed during the uninstallation;
  • Module parameters - describes how to store and manipulate the module parameters;
  • Interaction of modules - outlines the technology of explicit module interaction and the event-driven interaction;
  • Identifiers - shows the table of the standard module identifiers.


Structure of files

The following is the structure of files required to be included in a module:

  • /bitrix/modules/module ID/ - module root folder
    • /admin/ - directory containing module administrative scripts
      • menu.php - file with the module administrative menu
    • /classes/ - scripts with the module classes
      • /general/ - database independent module classes
      • /mysql/ - the MySQL only module classes
      • /oracle/ - the Oracle only module classes
    • /lang/language ID/ - directory containing language files used by the module scripts
      • /install/ - directory containing files used to install and uninstall a module
        • /admin/ - directory with scripts including module administrative scripts (calling scripts)
          • /db/ - directory containing SQL scripts used to install/uninstall the database
            • /mysql/ - SQL scripts used to install/uninstall MySQL tables
            • /oracle/ - SQL scripts used to install/uninstall Oracle tables
          • /images/ - directory containing images used by module; after the module installation they should be copied to the directory /bitrix/images/module ID/
            • /templates/ - directory with the module components
              • /module ID/ - directory containing the main component files
              • /lang/language ID/module ID/ - contains language files of the module components
            • index.php - file containing the module description
          • include.php - this file is included when a function that includes the module is called; the file should include all files implementing functions and classes of the module
            • default_option.php - contains an array $module ID_default_option, in which the default values of the module parameters are specified
              • options.php - this file is included by the module settings page in the Settings menu
                • prolog.php - file included by all administrative scripts of the module; it should initialise the following two variables:
                  • ADMIN_MODULE_NAME - the module ID;
                  • ADMIN_MODULE_ICON - HTML code of the module large icon displayed above the page title.


Administrative scripts

Administartive scripts are the scripts used by a module in the administrative section of the system. They are to be stored in the directory /bitrix/modules/module ID/admin/.

It should be considered that administrative scripts cannot be directly called in browser (as well as other scripts of the directory /bitrix/modules/). Thus, additional scripts (with the same name; hereinafter referred to as calling scripts) found in the directory /bitrix/admin/ are used to call the administrative scripts. Usually, they just include the administrative script having the same name:

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/module ID/admin/script name");
?>

When a module is being installed, the calling scripts must be copied from the directory /bitrix/modules/module ID/install/admin/ to the directory /bitrix/admin/.

When a module is being uninstalled, the calling scripts must be removed from the directory /bitrix/admin/.

Account must be taken of the fact that the calling scripts of all the installed modules are located in the directory /bitrix/admin/. Thus, to avoid file duplicates, they should be given names beginning with a prefix peculiar to the corresponding module.

Each administrative script must define the following two constants, before the administrative prlogue visual section is included:

  • ADMIN_MODULE_NAME - the custom module ID (for the example see standard module ID's);
  • ADMIN_MODULE_ICON - the HTML code of a module large icon displayed above the page title.
These are required to form the icon above the page title.

The following example shows how to define these constants:

define("ADMIN_MODULE_NAME", "statistic");
define("ADMIN_MODULE_ICON", "<a href=\"stat_list.php?lang=".LANGUAGE_ID."\">
<img src=\"/bitrix/images/statistic/statistic.gif\"
width=\"48\" height=\"48\" border=\"0\" alt=\"".GetMessage("STAT_MODULE_TITLE")."\"
title=\"".GetMessage("STAT_MODULE_TITLE")."\"></a>");


Administrative menu

The menu of administrative section is displayed by the standard function CMain::GetMenuHtmlEx.

The menu template is stored in the file:

/bitrix/modules/main/interface/.left.menu_template.php

The main file that builds the menu items is:

/bitrix/modules/main/interface/.left.menu.php

This file enumerates all files in /bitrix/modules/module ID/admin/menu.php. Each of these files contains the definition of array $aModuleMenuLinks which contains menu items of the corresponding module. All these arrays will be further combined into a standard array $arMenuSections containing the information of all menu items (see also Menu).

The array $aModuleMenuLinks structure:

Array
(
    [0] => Array
        (
            [0] => menu item title
            [1] => menu item link
            [2] => Array
                (
                    [0] => additional links for highlighting the menu item 1
                    [1] => additional links for highlighting the menu item 2
                    ...
                    [N] =>  additional links for highlighting the menu item N
                )
            [3] => Array
                (
                    [ALT] => menu item tooltip text
                    [SECTION_ID] => the unique ID of a menu section,
                                    has the value of the module ID,
                                    or one of the following:
                                       FAVORITE - the Favorites section
                                       GENERAL - the Users section
                                       MAIN - the System Settings section

                    [SEPARATOR] => "Y" - menu item is a menu section title
                    [SORT] => menu section sort weight
                              relative to other menu section (only if SEPARATOR is "Y")
                    [ICON] => link to a small icon used
                              in a menu section title (only if SEPARATOR is "Y")
                    [BIG_ICON] => link to a large icon used
                                  on the Desktop page (only if SEPARATOR is "Y")
                    [INDEX_PAGE] => link for the icon BIG_ICON (only if SEPARATOR is "Y")
                )

        )
    [1] => Array( -//- )
    [2] => Array( -//- )
    ...
    [M] => Array( -//- )
)

Example

The following is the example of file /bitrix/modules/support/admin/menu.php which builds the Techsupport module menu:

<?
// include language file
IncludeModuleLangFile(__FILE__);

// determine the current user permissions
$SUP_RIGHT = $APPLICATION->GetGroupRight("support");

// if access is allowed
if($SUP_RIGHT>"D")
{
    // add menu items according to permissions

    $aModuleMenuLinks[] = Array(
            GetMessage("SUP_M_SUPPORT"),
            "",
            Array(),
            Array(
                "SEPARATOR"  => "Y",
                "SORT"       => 1000,
                "ICON"       => "/bitrix/images/support/mnu_support.gif",
                "BIG_ICON"   => "/bitrix/images/support/support.gif",
                "INDEX_PAGE" => "/bitrix/admin/ticket_desktop.php?lang=".
                                LANGUAGE_ID."&set_default=Y"
                )
            );

    if ($SUP_RIGHT>="T")
    {
        $aModuleMenuLinks[] = Array(
                GetMessage("SUP_M_REPORT_TABLE"),
                "/bitrix/admin/ticket_desktop.php?lang=".
                LANGUAGE_ID."&set_default=Y",
                Array("/bitrix/admin/ticket_desktop.php"),
                Array("ALT"=>GetMessage("SUP_M_REPORT_TABLE_ALT"))
                );
    }

    $aModuleMenuLinks[] = Array(
            GetMessage("SUP_M_TICKETS"),
            "/bitrix/admin/ticket_list.php?lang=".
            LANGUAGE_ID."&set_default=Y",
            Array(
                "/bitrix/admin/ticket_list.php",
                "/bitrix/admin/ticket_edit.php",
                "/bitrix/admin/ticket_message_edit.php"
                ),
            Array("ALT"=>GetMessage("SUP_M_TICKETS_ALT"))
            );

    if ($SUP_RIGHT>="T")
    {
        $aModuleMenuLinks[] = Array(
                GetMessage("SUP_M_REPORT_GRAPH"),
                "/bitrix/admin/ticket_report_graph.php?lang=".
                LANGUAGE_ID."&set_default=Y",
                Array("/bitrix/admin/ticket_report_graph.php"),
                Array("ALT"=>GetMessage("SUP_M_REPORT_GRAPH_ALT"))
                );
    }

    if ($SUP_RIGHT>="V")
    {
        $aModuleMenuLinks[] = Array(
                GetMessage("SUP_M_CATEGORY"),
                "/bitrix/admin/ticket_dict_list.php?lang=".
                LANGUAGE_ID."&find_type=C&set_filter=Y",
                Array(
                    "/bitrix/admin/ticket_dict_edit.php?find_type=C",
                    "/bitrix/admin/ticket_dict_list.php?find_type=C"
                    )
                );
    }
}
?>

If you need to add an item to the administrative menu, even if you are not developing your own module, initialise the array $aMenuLinks with the corresponding values in the file /bitrix/admin/.left.menu.php.

Example

The file /bitrix/admin/.left.menu.php adds an arbitrary menu item.

<?
// add menu item "Import equipment"
// to section "Information blocks"
$aMenuLinks = Array(
    Array(
        "Import equipment",
        "/bitrix/admin/equipment_import.php?lang=ru",
        Array(),
        Array(
            "ALT" => "Import equipment from DBF files",
            "SECTION_ID" => "iblock",
            "SORT" => "100"
        )
    )
);
?>

See Also

  • Menu
  • CMain::GetMenuHtmlEx


Language files

For use by the module administrative scripts, language files must be stored in the following directory: /bitrix/modules/module ID/lang/language ID/

The language files must reside in the same directory as the files that include them, relative to /bitrix/modules/module ID/. In this case, the language files may only be included using the function IncludeModuleLangFile.

For example, for the script:

/bitrix/modules/module ID/admin/body/my_script.php

the language file must be:

/bitrix/modules/module ID/lang/language ID/admin/body/my_script.php

The language file must be included using the code:

IncludeModuleLangFile(__FILE__);


Module description

Each module should be correctly described in a system, for the latter to know how to handle this module. Modules described incorrectly can cause total or partial inoperability of the system (for example, the Update subsystem may become inoperative).

The main file the system uses to manipulate a module is /bitrix/modules/module ID/install/index.php. The main function of this file is to implement the class with the same name as module ID in it.

The following are the required methods of this class:

  • DoInstall runs after a user clicks Install in the administrative menu Modules. Performs the module installation (see also CModule::DoInstall);
  • DoUninstall runs after clicking Delete in the administrative menu Modules. Uninstalls a module (see also CModule::DoUninstall).

Optional method of the class:

  • GetModuleRightList returns a list of unique permissions (or roles) of a module (see also CModule::GetModuleRightList).

The following properties are required in this class:

  • MODULE_ID stores the module ID;
  • MODULE_VERSION - the current version of the module in the format XX.XX.XX;
  • MODULE_VERSION_DATE - string containing the module version date; the date is to be specified in the format YYYY-MM-DD HH:MI:SS;
  • MODULE_NAME - the module name;
  • MODULE_DESCRIPTION - the module description;
  • MODULE_GROUP_RIGHTS - if the method GetModuleRightList is implemented, this property should be set to "Y".

Example of a file describing the Web forms module

<?
global $MESS;
$PathInstall = str_replace("\\", "/", __FILE__);
$PathInstall = substr($PathInstall, 0, strlen($PathInstall)-strlen("/index.php"));

IncludeModuleLangFile($PathInstall."/install.php");
include($PathInstall."/version.php");

if (class_exists("form"))
    return;

Class form extends CModule
{
    var $MODULE_ID = "form";
    var $MODULE_VERSION;
    var $MODULE_VERSION_DATE;
    var $MODULE_NAME;
    var $MODULE_DESCRIPTION;
    var $MODULE_GROUP_RIGHTS = "Y";

    function form()
    {
        $this->MODULE_VERSION = FORM_VERSION;
        $this->MODULE_VERSION_DATE = FORM_VERSION_DATE;
        $this->MODULE_NAME = GetMessage("FORM_MODULE_NAME");
        $this->MODULE_DESCRIPTION = GetMessage("FORM_MODULE_DESCRIPTION");
    }

    function DoInstall()
    {
        global $DB, $APPLICATION, $step;
        $FORM_RIGHT = $APPLICATION->GetGroupRight("form");
        if ($FORM_RIGHT=="W")
        {
            $step = IntVal($step);
            if ($step<2)
                $APPLICATION->IncludeAdminFile(GetMessage("FORM_INSTALL_TITLE"),
                $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/install/step1.php");
            elseif ($step==2)
                $APPLICATION->IncludeAdminFile(GetMessage("FORM_INSTALL_TITLE"),
                $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/install/step2.php");
        }
    }

    function DoUninstall()
    {
        global $DB, $APPLICATION, $step;
        $FORM_RIGHT = $APPLICATION->GetGroupRight("form");
        if ($FORM_RIGHT=="W")
        {
            $step = IntVal($step);
            if ($step<2)
                $APPLICATION->IncludeAdminFile(GetMessage("FORM_UNINSTALL_TITLE"),
                $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/install/unstep1.php");
            elseif ($step==2)
                $APPLICATION->IncludeAdminFile(GetMessage("FORM_UNINSTALL_TITLE"),
                $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/install/unstep2.php");
        }
    }

    function GetModuleRightList()
    {
        global $MESS;
        $arr = array(
            "reference_id" => array("D","R","W"),
            "reference" => array(
                GetMessage("FORM_DENIED"),
                GetMessage("FORM_OPENED"),
                GetMessage("FORM_FULL"))
            );
        return $arr;
    }
}
?>

See Also

  • Access permissions within the module logic
  • CModule::DoInstall
  • CModule::DoUninstall
  • CModule::GetModuleRightList
  • CMain::IncludeAdminFile


Module installation

Module installation is performed in the menu Modules of the administrative interface, by clicking the Install button. This will cause calling the method DoInstall of the class whose name is the same as the module ID. This class is to be implemented in file /bitrix/modules/module ID/install/index.php (see also Module description ).

During the module installation, the following actions are to be performed without fail:

  • module registration, which is implemented using the function RegisterModule;
  • if the module contains administrative scripts, their calling scripts must be copied to the directory /bitrix/admin/;
  • all images used by the module must be copied to the directory /bitrix/images/module ID/.

See Also

  • Module description
  • Structure of module files
  • RegisterModule
  • RegisterModuleDependences
  • CAgent::AddAgent
  • COption::SetOptionString
  • CDataBase::RunSQLBatch
  • CopyDirFiles


Module uninstallation

Module uninstallation is performed in the menu Modules of the administrative interface, by clicking the Delete button. This will cause calling the method DoUninstall of the class whose name is the same as the module ID. This class should be implemented in file /bitrix/modules/module ID/install/index.php (see also: Module description ).

During the module uninstallation, the following actions are to be performed without fail:

  • removal of the module registration, which is performed using the function UnRegisterModule;
  • if the module contains administrative scripts, their calling scripts must be deleted from the directory /bitrix/admin/.
  • all images used by the module must be deleted from the directory /bitrix/images/module ID/.

See Also

  • Module description
  • Structure of module files
  • UnRegisterModule
  • UnRegisterModuleDependences
  • CAgent::RemoveModuleAgents
  • COption::RemoveOption
  • CDataBase::RunSQLBatch
  • DeleteDirFiles


Module parameters

Module parameters are available in administrative interface in the Settings menu. When choosing the module on this page, the system includes the file /bitrix/modules/module ID/options.php which manages the module parameters, assigns permissions to the module etc.

Note!
The module parameters are stored in the database.

The COption class is used to handle the module parameters; contains the following methods:

  • COption::SetOptionString sets string parameters;
  • COption::SetOptionInt sets numeric parameters;
  • COption::GetOptionString gets string parameters;
  • COption::GetOptionInt gets numeric parameters;
  • COption::RemoveOption removes a parameter.
When getting the module parameters, the default value specified in the file /bitrix/modules/module ID/default_option.php can be used. This file defines an array $module ID_default_option storing the default values.

Example

The file /bitrix/modules/module ID/default_option.php.

<?
$support_default_option = array(
    "SUPPORT_DIR"                => "#SITE_DIR#support/",
    "SUPPORT_MAX_FILESIZE"       => "100",
    "ONLINE_INTERVAL"            => "900",
    "DEFAULT_VALUE_HIDDEN"       => "N",
    "NOT_IMAGE_EXTENSION_SUFFIX" => "_",
    "NOT_IMAGE_UPLOAD_DIR"       => "support/not_image",
    "DEFAULT_AUTO_CLOSE_DAYS"    => "7"
    );
?>

Example

<?
// set the string parameter
COption::SetOptionString("my_module_id",
                         "MY_PARAMETER_ID", "VALUE");

// get the string parameter
$value = COption::GetOptionString("my_module_id",
                                  "MY_PARAMETER_ID",
                                  "DEFAULT_VALUE");
?>

See Also

  • COption
  • Page parameters


Interaction of modules

Modules can interact in two ways: explicitly (via the direct call) and implicitly (via the event system).

Explicit interaction

Explicit interaction stipulates:

  • including module using the function CModule::IncludeModule;
  • direct call of a class method or a module function.

Example of explicit interaction:

<?
// include module mymodule
if (CModule::IncludeModule("mymodule"))
{
    // call its method
    CMyModuleClass::DoIt();
}
?>

Interaction via events

Each module can expose the interface for the implicit interaction with other modules through the set of events. The interaction allows for maximum independence of modules. A module knows nothing about features of another module, but they can interact via the event interface.

The scheme of handling the events is as follows: the module initiating an event should perform the following operations where an event is to occur:

  • collect all the registered handlers using the function GetModuleEvents;
  • execute them one after another using the function ExecuteModuleEvent, processing the returned values appropriately.
The module that needs to execute any action upon the event arrival, in its turn should do the following:
  • during the installation, register the handler using the function RegisterModuleDependences;
  • implement the handler and ensure that the script containing this function is included in file /bitrix/modules/module ID/include.php.

Thus, event is an action which implies collecting all handlers of the event and executing them one by one.

A striking example of such interaction is the interaction of the system modules with the Search module. The Search module has no information about features of other modules, neither of storing nor of processing peculiarities; it just exposes interface for the data indexing. Any system module, which is to be indexed by the Search module, registers the OnReindex event handler. Each handler returns the indexing data, which is used by the Search module to populate its database.

Note!
A list of the Kernel module events is available in the section Events.

Example of interaction via events:

<?
// register handler:
// when the event OnSomeEvent fires in the module init_module,
// the method CMyModuleClass::Handler
// of the module handler_module is called

RegisterModuleDependences(
    "init_module", "OnSomeEvent",
    "handler_module", "CMyModuleClass", "Handler"
    );
?>
<?
// arbitrary function of the module init_module,
// that generates the event

function MyFunction()
{
    // code generating the event
    // the registered handlers are collected
    $rsHandlers = GetModuleEvents("anothermodule", "OnSomeEvent");
    while($arHandler = $rsHandlers->Fetch())
    {
        // execute one by one
        if(!ExecuteModuleEvent($arHandler, $param1, $param2))
        {
            // if the handler returns false,
            // print "I can't do it..."
            return "I can't do it...";
        }
    }
    return "I have done it!";
}
?>
<?
// handler

class CMyModuleClass
{
    function Handler($param1, $param2)
    {
        if($param1=="delete all")
            return false;
        return true;
    }
}
?>


The module identifiers (ID's)

The table summarizes the standard module identifiers.
ID | Name
main | Kernel (main module)
fileman | Site explorer
iblock | Information blocks
sale | E-store
currency | Currencies
catalog | Commercial catalog
form | Web forms
workflow | Workflow
statistic | Statistics
advertising | Advertising and Banners
support | Helpdesk
mail | Mail
vote | Polls and Surveys
forum | Forum
subscribe | Newsletter
translate | Localization
ldap | AD/LDAP
search | Search
compression | Compression


Sites

Introduction

The Bitrix Site Manager 4.0 enables the creation and maintenance of an unlimited number of sites using a single installation of the product.

After the Bitrix Site Manager 4.0 has been released, developers gained possibility to create and maintain an unlimited number of sites using a single installation of the product.

A synonym of the term installation of the product is portal. Portal consists of one or more sites.

Strictly speaking, site is an aggregate of the following notions:

  • database account - created in the Sites administrative menu. Includes the following main parameters:
    • identifier - a set of symbols which identifies a site;
    • domain name - one or more domain names of a site;
    • site folder - path to the folder containing the site public section;
    • site language;
    • date format;
    • time format;
    • URL - default protocol and domain name (e.g. "http://www.site.com");
    • DocumentRoot - if multiple sites architecture is implemented using the method 2, this parameter should contain the server file system path to the site root;
    • template inclusion conditions - each site may have one or more templates used to display the public section; each template may be included using a condition.
  • public section - a set of scripts (pages) which belongs to this site and are stored in the site folder;
  • settings - each module may have site related preferences; for example: the Information Blocks module settings are relations between blocks and sites; the Techsupport module settings are associations between status, categories etc. and sites.

Note!
In the public section, the current site ID is to be stored in the constant SITE_ID.

In this section

  • Multiple sites - ways to organize multiple sites.
  • Site templates - outlines the structure of a site template and methods that can be used to connect it to a site.


Support for Multiple Sites

Multisite version features

The multisite version of the product allows the following two configuration modes.

  • Mode 1: the software and sites are operated by a single instance of the Apache web server.
  • Mode 2: each site runs on a separate instance of the Apache web server or a virtual web server.

The product distribution package is shipped configured to operate in the first configuration mode.

Creating the multiple site system using both configuration modes is considered in this topic. The example will explain how to create a system consisting of the two sites:

  • www.site1.com - company corporate web site;
  • www.site2.com - company on-line store.

Mode 1. Single web server for all sites

The first mode presumes the use of a single Apache web server whose DocumentRoot configured to contain the sites in /home/www/allsites/.

Let us install the Bitrix Site Manager 4.0 in this catalog.

The first mode requires that each site resides in a separate subdirectory of the common directory, for example:

  • /home/www/allsites/s1/
  • /home/www/allsites/s2/

You can choose any other names for catalogs s1 and s2, for example shop and company, or en and de respectively. You can also make one of the sites to reside in the root directory, whereas the other will be placed in its subdirectory.

You have to keep in mind that it is extremely important to separate one site from the other and ensure that the file structure does not interfere.

The configuration file httpd.conf of an Apache web server should contain the following lines, which will reflect the selected configuration:

<VirtualHost *:80>
    ServerAdmin admin@site1.com
    DocumentRoot "/home/www/allsites/"
    ServerName www.site1.com
    ErrorLog logs/allsite.log
    CustomLog logs/allsite.log  common
</VirtualHost>

Please note that the record DocumentRoot value /home/www/allsites/ explicitly defines the directory containing the installed software. The variable DocumentRoot has common value for all sites.

The line <VirtualHost *:80> means that the web server will reply to requests for any domain name and any IP address. That is, having the DNS configured properly, the web server will support both www.site1.com and www.site2.com.

The next step requires that we properly configure and specify both sites in the installed Bitrix software.

You can customize your sites in the administrative section of any site, for example www.site1.com/bitrix/.

Select the menu System Settings -> Sites.

Click the link Modify of the site #1 (www.site1.com) and specify the following parameters:

  • Name: site1
  • Domain name: www.site1.com
  • Site folder: /s1/
  • Server URL: www.site1.com
  • Site name: Corporate web site of "Company name"
  • Path to web server root folder of this site: leave blank

It is always a good idea to specify the domain name without www. If the DNS is configured so that your site is accessible by the address http://site1.com, the Domain name should not www. You can specify as many as needed domain names that users can indicate in their browsers to access your site; each domain name in the list should start from the new line.

Please bear in mind that the values you specify in the field Domain name are used by the system to deliver the user information to these domains through the user transfer technology. It might be as well to specify a full list of registered domain names by which your site can be accessed.

Do not include in this list sites not running on the current instance of the Bitrix Site Manager. Invalid domains will slow down the system response to users; user information will not be transferred to sites running on other instances of the software.

The Site folder should indicate the existing path relative to the root directory containing the site public section. The Path to web server root folder is not used in this mode; this field should be blank for all sites.

Now set the preferences of the site #2 (www.site2.com):

  • Name: site2
  • Domain name: site2.com
  • Site folder: /s2/
  • Server URL: www.site2.com
  • Site name: The "Company name" company e-store
  • Path to web server root folder of this site: leave blank

The system is now almost ready to go. The only thing to do is customize the site selection preferences on the main portal page /index.php.

When site visitors type www.site1.com or www.site2.com in their browsers, they actually open the page /index.php which is located in the directory indicated in the DocumentRoot parameter of the web server. In the multiple site world, this file has slightly different function: it should contain the PHP code used to select one of the sites depending on the current domain name, rather than the index page content.

The following methods of the class CMainPage may help to solve this task:

  • CMainPage::GetSiteByHost - returns the site ID, determining it by the current host.
  • CMainPage::GetSiteByAcceptLanguage - returns the site ID by the Accept-Language variable in the user browser settings.
  • CMainPage::GetIncludeSitePage - returns the absolute path to the index page of the specified site, for further inclusion using require() or include().
  • CMainPage::RedirectToSite - redirects to the index page of the specified site.

The following is an example of the index page for the plural site configuration. The code resolves the site by the current domain name.

<?
// include file with CMainPage class
require($_SERVER['DOCUMENT_ROOT']."/bitrix/modules/main/include/mainpage.php");

// obtain current site ID by domain name
$site_id = CMainPage::GetSiteByHost();

// get absolute path to the site index page
$page = CMainPage::GetIncludeSitePage($site_id);

// if the site and index page are both defined...
if(strlen($site_id)>0 && strlen($page)>0)
{
    // include page
    require_once($page);
}
else // if the site is not defined
{
    require($_SERVER['DOCUMENT_ROOT']."/bitrix/header.php");
    // place code that will display if the site
    // is not defined
    ?>

    <?require($_SERVER['DOCUMENT_ROOT']."/bitrix/footer.php");
}
?>

The above algorithm checks the domain name that the visitor typed in the browser to view the site by calling the function CMainPage::GetSiteByHost; searches the list of domain names (the field Domain name) for this domain name to get the site ID and includes the real code of the site index page by calling the function CMainPage::GetIncludeSitePage.

In our case, this means that a visitor who typed www.site1.com in the browser will get the document /s1/index.php without the redirect, whereas a visitor who typed www.site2.com in the browser will get /s2/index.php.

Note
The described algorithm allows to avoid using redirects for both visitors and search engine robots as well as makes handling multiple sites more convenient. This algorithm is recommended for use with multiple sites, though other variations are possible.

If your sites represent language mirrors of a single web resource, you may choose to determine the site by languages installed in the visitor browser.

The following is an example of the index page of the portal containing several sites. The code determines the required site by languages installed in the visitor browser.

<?
// include file with CMainPage class
require($_SERVER['DOCUMENT_ROOT']."/bitrix/modules/main/include/mainpage.php");

// get the site id by Accept-Language
$site_id = CMainPage::GetSiteByAcceptLanguage();

// if the site is defined...
if(strlen($site_id)>0)
{
    // redirect to index page
    CMainPage::RedirectToSite($site_id);
}
else // if the site is not defined
{
    require($_SERVER['DOCUMENT_ROOT']."/bitrix/header.php");
    // place code that will display if the site
    // is not defined
    ?>

    <?require($_SERVER['DOCUMENT_ROOT']."/bitrix/footer.php");
}
?>

The function CMainPage::GetSiteByAcceptLanguage checks the variable Accept-Language in the client browser, compares it to the site language ID and returns the appropriate web site.

In the example above, the function CMainPage::RedirectToSite will perform redirect (HTTP response code 302) and take a visitor to the index page of a site, for example www.site1.com/en/ or www.site2.com/de/.

Create your index page or choose the code of one of the examples. Your sites are now ready to operate in the mode 1.

Mode 2. Separate web servers for each site

The second mode requires that you make special adjustments to both web server and the installed software.

We shall consider configuration of the two sites:

  • www.site1.com - company corporate web site;
  • www.site2.com - company on-line store.

Each of the sites needs a separate virtual Apache web server to be configured. The sites will reside in the following direcories

  • /home/www/site1/
  • /home/www/site2/

The configuration file httpd.conf of an Apache web server should contain the following two records, each describing a separate virtual server:

<VirtualHost *:80>
    ServerAdmin admin@site1.com
    DocumentRoot "/home/www/site1/"
    ServerName site1.com
    ServerAlias *.site1.com
    ErrorLog logs/site1.log
    CustomLog logs/site1.log  common
</VirtualHost>
<VirtualHost *:80>
    ServerAdmin admin@site2.com
    DocumentRoot "/home/www/site2/"
    ServerName site2.com
    ServerAlias *.site2.com
    ErrorLog logs/site2.log
    CustomLog logs/site2.log  common
</VirtualHost>

Please note that the records DocumentRoot points to different directories containing the corresponding site.

Lines <VirtualHost *:80> denote that the web server will respond to any domain name and IP address. But the variable ServerAlias tells the web server to respond to a specific domain name only.

That is, requests to www.site1.com are processed by the web server instance working with the directory /home/www/site1/, but www.site2.com is managed by the web server that is responsible for the directory /home/www/site1/.

You can configure your web servers to serve specific IP addresses. Example below shows how to configure an Apache web server to support different IP addresses:

<VirtualHost 192.168.0.1:80>
    ServerAdmin admin@site1.com
    DocumentRoot "/home/www/site1/"
    ServerName site1.com
    ErrorLog logs/site1.log
    CustomLog logs/site1.log  common
    Options +FollowSymLinks
</VirtualHost>
<VirtualHost 192.168.0.2:80>
    ServerAdmin admin@site2.com
    DocumentRoot "/home/www/site2/"
    ServerName site2.com
    ErrorLog logs/site2.log
    CustomLog logs/site2.log  common
    Options +FollowSymLinks
</VirtualHost>

Having the DNS server properly configured for different domain names, each virtual web server will run on a separate IP address and respond to a specific domain name.

Next step is to install the product with this configuration. The commands rendered in green text illustrate how to install the system on UNIX-based systems.

  1. Install the Bitrix Site Manager 4.0 to the directory of the first site /home/www/site1/
  2. Create the folder /home/www/shared/. It will contain files common to all sites.
    mkdir /home/www/shared
  3. Move the entire directory /home/www/site1/bitrix/ to /home/www/shared/bitrix/:
    mv /home/www/site1/bitrix /home/www/shared/bitrix
  4. Move the entire directory /home/www/site1/upload/ to /home/www/shared/upload/:
    mv /home/www/site1/upload /home/www/shared/upload
  5. Create the symbolic link to the directory /bitrix/ for each site:
    1. ln -s /home/www/shared/bitrix /home/www/site1/
    2. ln -s /home/www/shared/upload /home/www/site1/
    3. ln -s /home/www/shared/bitrix /home/www/site2/
    4. ln -s /home/www/shared/upload /home/www/site2/
  6. Please ensure that the directory /home/www/shared/ of a web server (Apache, IIS) has write permissions. This is essential for the update system and image uploads.
  7. Copy the public pages of the second site to the directory/home/www/site2/

Note
Windows based web servers require third-party tools for the symbolic link creation. For example, Far Manager or Junction by Sysinternals.

Next step is to properly configure sites in the installed Bitrix software.

You can perform adjustments in the administrative section. Select the menu command System Settings -> Sites.

Click the link Modify of the site #1 (www.site1.com) and specify the following parameters:

  • Name: site1
  • Domain name: www.site1.com
  • Site folder: /
  • Server URL: www.site1.com
  • Site name: Corporate web site of "Company name"
  • Path to web server root folder of this site: /home/www/site1/

If the DNS is configured so that your site is accessible by the address http://site1.com, the Domain name should not www. You can specify as many as needed domain names that users can indicate in their browsers to access your site; each domain name in the list should start from the new line.

Please bear in mind that the values you specify in the field Domain name are used by the system to deliver the user information to these domains through the user transfer technology. It might be as well to specify a full list of registered domain names by which your site can be accessed.

Do not include in this list sites not running on the current instance of the Bitrix Site Manager. Invalid domains will slow down the system response to users; user information will not be transferred to sites running on other instances of the software.

Now set the preferences of the site #2 (www.site2.com):

  • Name: site2
  • Domain name: site2.com
  • Site folder: /
  • Server URL: www.site2.com
  • Site name: The "Company name" company e-store
  • Path to web server root folder of this site: /home/www/site2/

Please note that both sites has the same Site folder "/". This is possible due to the fact that the sites run on separate web servers with different physical files location.

An attention should be paid to the Path to web server root folder of this site parameter. For different sites, it has different values taken from the DocumentRoot parameter of the corresponding virtual server settings (see the example of the file httpd.cnf above).

Note
Please bear in mind that if you implement your multiple site environment using this model, you can use virtual servers of a single Apache web server instance as well as different instances of a web server. The same applies to other web severs: IIS, EServ etc.

The configuration is now ready to run.

Unlike the first configuration mode, this mode does not require any special site selection algorithm to be defined in the portal index page, as the site is unambiguously determined by the domain name.

Conclusion

The described recommendations allow configuring the Bitrix Site Manager to work in the multiple site mode.

The Bitrix Site Manager does not give preference to any of the versions. The first mode is generally used if you use the virtual hosting or feel uncertainty at configuring web servers. The second variant can be recommended if you use a dedicated server or the shared hosting allows several web server instances. This mode allows to exclude catalogs like /s1/ or /s2/ from URL's and start addresses from the root directory "/".


Site template

The synonyms of the term "site template" are "site design", "site skin". Several templates may be used to display a site. In the strict sense, a site template comprises:

  • database account - created in the administrative menu Site templates;
  • set of files in the directory /bitrix/templates/template ID/,
    where the template ID is the ID field in the site template editing form (the Site templates administrative menu). The structure of this directory is described below:
    • header.php - prologue of this template;
    • footer.php - epilogue of this template;
    • styles.css - CSS used by this template;
    • .menu type.menu_template.php - template used to display a menu of the corresponding type;
    • chain_template.php - default template used to display the navigation chain;
    • /module ID/ - directory with components of a module;
    • /lang/ - language files used by this template and components;
    • /images/ - directory with images used by this template;
    • /page_templates/ - directory with page templates and their descriptions stored in file .content.php;
    • other helper files used by this template.

A template can be applied to a site in the administrative menu Sites, in the site settings (click the Modify link), the Design section:

The site template is selected by calling CSite::GetCurTemplate; its algorithm can be described as follows:

  1. All site templates are chosen in the following order:
    1. those containing the PHP condition (the highest priority);
    2. sort weight (the less is the value the higher is the priority);
    Thus, templates containing either the PHP condition or the less sort weight value, will have the highest priority.
  2. Then, the loop iterates on all the chosen templates. If the template contains the PHP condition, it is evaluated and if the result is "true", the path /bitrix/templates/site template ID/ is checked for existence. It this path exists, the loop breaks and the function CSite::GetCurTemplate returns this site template ID.
  3. In case none of the templates could be matched, the default template .default.php is returned.

When specifying the PHP condition, it should be considered that the check is implemented by the function which has its own scope of variables. That's why the global variables should be specified by using the array $GLOBALS, the request variables - through the array $_REQUEST (or $_GET, $_POST) etc.

The current site template is determined at the end of the prologue service section (prolog_before.php). Hence, the following can be used:

  • $APPLICATION object of the CMain class;
  • $USER object of the CUser class;
  • all the system constants of the type A;
  • all the standard PHP arrays: $GLOBALS, $_REQUEST, $_SERVER, $_SESSION, $_ENV, $_COOKIE etc.

When specifying the PHP condition for choosing the site template, it should be considered that the use of section properties is allowed, while page properties are not allowed. This is because the section properties are stored in a separate file .section.php, and the page properties are specified usually in a page body, after the including the prologue service section.

Note!
In the public section, the current site template ID is stored in the constant SITE_TEMPLATE_ID.

Examples of specifying the conditions for inclusion of a site template

If a request (GET or POST) contains the parameter print equal to "Y":

$_REQUEST["print"]=="Y"

If the section property phone is "Y":

$APPLICATION->GetDirProperty("phone")=="Y"

If the current section is "/en/catalog/phone/":

$APPLICATION->GetCurDir()=="/en/catalog/phone/"

Is the current user is an administrator:

$USER->IsAdmin()


Languages

Introduction

Language is an account in the database available for editing in the administrative menu Languages and containing the following fields:

  • ID
  • Name
  • Date format
  • Time format
  • Encoding

In both public and administrative sections, language is primarily used to choose a language file.

In the administrative section, language defines the format of time, date and page encoding. In the public section, these parameters are defined by the site settings.

In this section

  • Encoding - table of encoding and language ID's
  • Date and time format - table of date and time formats used in different countries
  • Language files - description of the main functions and principles to handle language files


Language encoding

The following table summarizes the language encoding and identifiers:

Language | ID | Encoding
Russian | ru | iso-8859-5, windows-1251, koi8-r
English | en | iso-8859-1, windows-1252
Afrikaans | af | iso-8859-1, windows-1252
Albanian | sq | iso-8859-1, windows-1252
Arabic | ar | iso-8859-6
Basque | eu | iso-8859-1, windows-1252
Bulgarian | bg | iso-8859-5
Byelorussian | be | iso-8859-5
Catalan | ca | iso-8859-1, windows-1252
Croatian | hr | iso-8859-2, windows-1250
Czech | cs | iso-8859-2
Danish | da | iso-8859-1, windows-1252
Dutch | nl | iso-8859-1, windows-1252
Esperanto | eo | iso-8859-3
Estonian | et | iso-8859-15
Faroese | fo | iso-8859-1, windows-1252
Finnish | fi | iso-8859-1, windows-1252
French | fr | iso-8859-1, windows-1252
Galician | gl | iso-8859-1, windows-1252
German | de | iso-8859-1, windows-1252
Greek | el | iso-8859-7
Hebrew | iw | iso-8859-8
Hungarian | hu | iso-8859-2
Icelandic | is | iso-8859-1, windows-1252
Irish | ga | iso-8859-1, windows-1252
Italian | it | iso-8859-1, windows-1252
Japanese | ja | shift_jis, iso-2022-jp, euc-jp
Korean | ko | euc-kr
Latvian | lv | iso-8859-13, windows-1257
Lithuanian | lt | iso-8859-13, windows-1257
Macedonian | mk | iso-8859-5, windows-1251
Maltese | mt | iso-8859-3
Norwegian | no | iso-8859-1, windows-1252
Polish | pl | iso-8859-2
Portuguese | pt | iso-8859-1, windows-1252
Romanian | ro | iso-8859-2
Scottish | gd | iso-8859-1, windows-1252
Serbian cyrillic | sr | iso-8859-5, windows-1251
Serbian latin | sr | iso-8859-2, windows-1250
Slovak | sk | iso-8859-2
Slovenian | sl | iso-8859-2, windows-1250
Spanish | es | iso-8859-1, windows-1252
Swedish | sv | iso-8859-1, windows-1252
Turkish | tr | iso-8859-9, windows-1254
Ukrainian | uk | iso-8859-5


Date and time format

The following table summarizes the main date and time formats used in different countries.

Country/language | Date format | Time format | Date example | Time example
Russia | DD.MM.YYYY | HH:MI:SS | 26.01.1993 | 18:24:00
USA | MM-DD-YYYY | HH:MI:SS | 01-26-1993 | 18:24:00
International English | DD-MM-YYYY | HH:MI:SS | 26-01-1993 | 18:24:00
Great Britain | DD/MM/YYYY | HH:MI:SS | 26/01/1993 | 18:24:00
German | DD.MM.YYYY | HH:MI:SS | 26.01.1993 | 18:24:00
Belgium | DD/MM/YYYY | HH:MI:SS | 26/01/1993 | 18:24:00
Brazil | DD/MM/YYYY | HH:MI:SS | 26/01/1993 | 18:24:00
Hungary | YYYY-MM-DD | HH:MI:SS | 1993-01-26 | 18:24:00
Denmark | DD-MM-YYYY | HH.MI.SS | 26-01-1993 | 18.24.00
Italy | DD/MM/YYYY | HH.MI.SS | 26/01/1993 | 18.24.00
Spain | DD/MM/YYYY | HH:MI:SS | 26/01/1993 | 18:24:00
Canada (French) | YYYY-MM-DD | HH:MI:SS | 1993-01-26 | 18:24:00
Latin America | DD/MM/YYYY | HH:MI:SS | 26/01/1993 | 18:24:00
Netherlands | DD-MM-YYYY | HH:MI:SS | 26-01-1993 | 18:24:00
Norway | DD.MM.YYYY | HH:MI:SS | 26.01.1993 | 18:24:00
Poland | YYYY-MM-DD | HH:MI:SS | 1993-01-26 | 18:24:00
Portugal | DD-MM-YYYY | HH:MI:SS | 26-01-1993 | 18:24:00
Serbia/Yugoslavia | DD.MM.YYYY | HH.MI.SS | 26.01.1993 | 18.24.00
Slovakia | YYYY-MM-DD | HH:MI:SS | 1993-01-26 | 18:24:00
Slovenia | YYYY-MM-DD | HH:MI:SS | 1993-01-26 | 18:24:00
Finland | YYYY-MM-DD | HH.MI.SS | 1993-01-26 | 18.24.00
France | DD.MM.YYYY | HH:MI:SS | 26.01.1993 | 18:24:00
Czech | YYYY-MM-DD | HH:MI:SS | 1993-01-26 | 18:24:00
Switzerland | DD.MM.YYYY | HH,MI,SS | 26.01.1993 | 18,24,00
Sweden | YYYY-MM-DD | HH.MI.SS | 1993-01-26 | 18.24.00


Language files

Language file is a PHP script storing phrases translated into other languages. The script contains an array $MESS whose keys are the language phrases ID's and values are the translations into a correspondent language.

Example of a language file for the English language:

<?
$MESS ['SUP_SAVE'] = "Save";
$MESS ['SUP_APPLY'] = "Apply";
$MESS ['SUP_RESET'] = "Reset";
$MESS ['SUP_EDIT'] = "Edit";
$MESS ['SUP_DELETE'] = "Delete";
?>
Example of a language file for the French language:

<?
$MESS ['SUP_SAVE'] = "Enregistrer";
$MESS ['SUP_APPLY'] = "Appliquer";
$MESS ['SUP_RESET'] = "Reset";
$MESS ['SUP_EDIT'] = "Modifier";
$MESS ['SUP_DELETE'] = "Supprimer";
?>

For each language, there is a number of language files stored in subdirectories /lang/ (see also: The structure of system files , The structure of module files).

Usually, the language files are used in administrative scripts of modules or in components. They are included using one of the following appropriate functions:

  • IncludeModuleLangFile used in administrative scripts;
  • IncludeTemplateLangFile used in components.

Note!
For the easier search and further modification of the language phrases, the page parameter show_lang_files=Y can be used. It allows to quickly find or edit any language phrase in the Translation module.


Pages

This section outlines the following concepts.

  • Page structure describes the ways to include the prologue and epilogue of a page.
  • Page template describes the algorithm of building the list of page templates when creating a new page in the Site Explorer module.
  • Execution order describes the page execution order.
  • Properties and meta tags describes the principles of handling the page (section) properties and a tag <meta> using the page (section) properties.
  • Page parameters describes the concept "page parameter" and principles of handling it.


Page structure

In the Bitrix Site Manager, a page is a PHP file consisting of prologue, page body and epilogue.

A common page structure looks as follows:

<?
// include the prologue
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
?>
page body
<?
// include the epilogue
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
?>

Due to the delay function technology, some visual elements displayed in prologue can be specified in the page body. Among these elements are:

  • page title (displayed by the CMain::ShowTitle function);
  • navigation chain (displayed by the CMain::ShowNavChain function);
  • CSS styles (displayed by the CMain::ShowCSS function);
  • Meta tags (displayed by the CMain::ShowMeta function);
  • etc.

The distinctive feature of this technology is allowing to delay execution of some functions by means of running them in the epilogue and placing the results of their execution in the preceding code.

But there is a number of tasks which cannot be settled using the delay function technology. This is referred to those cases when any actions are to be performed in the prologue with the values which would be specified in the page body in the previous example (for example: page properties). In this case it is essential to split the prologue into the service and visual sections and to specify those values between them. This is achieved in the following way:

<?
// include the prologue service section
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");

// for example, page property can be specified here
// using the function $APPLICATION->SetPageProperty
// and then process it in the epilogue visual section

// include the prologue visual section
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
Page content
<?
// include the epilogue
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
?>

The prologue service section:

  • performs the database connection;
  • runs agents;
  • initialises service constants;
  • checks permissions of the level 1;
  • includes the required modules;
  • executes the OnPageStart and OnBeforeProlog events handlers;
  • performs other actions.

The main feature of the prologue service part is that it does not display any data (that is, does not send header to browser).

The prologue visual section includes the file /bitrix/templates/site template ID/header.php (site template ID is the current site template ID). This file stores the upper left part of the current site template.

As well as the prologue, the epilogue can be split into the visual and service sections.

<?
// include the prologue service section
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");

// include the prologue visual section
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");

?>
Page content
<?

// include the epilogue visual section
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_before.php");

// include the epilogue service section
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");
?>

The epilogue visual section includes the file /bitrix/templates/site template ID/footer.php (site template ID is the current site template ID). This file stores the lower right part of the current site template. Besides, a set of invisible IFRAME's used by the user transfer technology is displayed.

The epilogue service section:

  • sends e-mail messages;
  • performs disconnecting from the database;
  • executes the OnAfterEpilog event handlers;
  • performs other service tasks.

Often there appear tasks when the visual sections of prologue and epilogue are not necessarily to be included (for example, when using the Bitrix Web Analytics edition). In this case, it is enough to include the service sections of prologue and epilogue:

<?
// include the prologue service section
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
?>
page body
<?
// include the epilogue service section
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");
?>

Note!
The service sections of both prologue and epilogue must be included for the system to operate correctly.

See Also

  • Page execution order


Page templates

A page template is a PHP file whose content conforms to the rules of forming the page structure. Page templates can be used when creating a new page in the module Site Explorer.

Page templates are stored in the following folders:

  • /bitrix/templates/.default/page_templates/
  • /bitrix/templates/site template ID/page_templates/

Each of these folders may contain page template files and a service file .content.php whose main task is to store the descriptions and of page template sort order. This information is stored in the array $TEMPLATES, whose structure is presented below:

Array
(
    [file name] => Array
        (
            [name] => page template title
            [sort] => sort weight
        )

)

When building the list of page templates, the following algorithm is used.

  1. Obtain the site template ID for the current site which is included without the PHP condition;
  2. Consecutively include files:
    1. /bitrix/templates/.default/page_templates/.section.php
    2. /bitrix/templates/site template ID/page_templates/.section.php
    In each of these files, a correspondent array $TEMPLATES is described. After including these files, we will have a combined array $TEMPLATES. Then, perform the following actions for each element of this array, being a description of a page template:
    1. check whether the page template physically exists;
    2. if it does, add it to the list of templates.
  3. Sort the obtained list of templates by the sort weight (see the structure of the array $TEMPLATES above).

See Also

  • Page structure


Page execution order

The below table outlines execution order of the page whose structure conforms to the rules described in the Page structure section.

No | Operation | Definable constants and variables | Remarks
1. Prologue service section
1.1 | Includes /bitrix/php_interface/dbconn.php |  | The included file is to contain debugging constants, access permissions and definitions of variables used to connect to the database.
1.2 | Connects to the database | $DB | In case of an error, the file /bitrix/php_interface/dbconn_error.php is included.
1.3 | Includes /bitrix/php_interface/after_connect.php |  | The file included may contain operations which are to be executed right after the connection to the database is established.
1.4 | Determines the current site | $APPLICATION, SITE_ID, SITE_DIR, SITE_SERVER_NAME, SITE_CHARSET, FORMAT_DATE, FORMAT_DATETIME, LANGUAGE_ID, all the classes and functions of the Kernel module are defined. | If the constant SITE_ID with the site ID is defined, the site is not determined by the current folder and domain; all other constants are determined using the site SITE_ID.
1.5 | Includes /bitrix/php_interface/init.php |  | May initialise event handlers and include additional functions common for all sites.
1.6 | Includes /bitrix/php_interface/site ID/init.php |  | Contains parameters and function definitions for the specific site.
1.7 | Checks agents |  | Variables $USER, $_SESSION as well as those determined below cannot be used in agents.
1.8 | The OnPageStart event is fired |  |
1.9 | Opens session | All the session variables $_SESSION. |
1.10 | Defines user, authorizes user, completes session, registers (depending on parameters in request) | $USER |
1.11 | Determines the current site template | SITE_TEMPLATE_ID |
1.12 | The OnBeforeProlog event is fired |  |
1.13 | Checks access permissions of the first level |  | If the user has not enough permissions, the authorization form is displayed and the page completes the execution.
1.14 | Starts buffered output |  | After the buffered output is started, you can emit any visual data. The output may precede or follow setting cookies.
1.15 | OnProlog Event |  |
2. Prologue visual section
2.1 | Includes /bitrix/templates/site template ID/header.php |  |
3. Page body
4. Epilogue visual section
4.1 | Includes /bitrix/templates/site template ID/footer.php |  |
4.2 | Calls the function CMain::ShowSpreadCookieHTML |  | This function displays a set of invisible IFRAME's used in user transfer technology.
5. Epilogue service section
5.1 | The OnEpilog event is fired |  |
5.2 | Completes the page buffering |  | Completes and flushes the buffer initialised in 1.14
5.3 | Sends e-mails |  | For more information about e-mail messages, you may read in the Mail system section.
5.4 | The OnAfterEpilog event is fired |  |
5.5 | Completes the database connection | Variable $DB is no more available |

See Also

  • Page structure


Page properties and meta tags

In the Bitrix Site Manager, both section and page properties are supported.

The section properties are stored in the file .section.php of the correspondent folder (site section).

The page properties are specified in the page body, or between the service and visual sections of the prologue.

The following functions are used to handle properties:

  • CMain::SetPageProperty
  • CMain::SetDirProperty
  • CMain::ShowProperty
  • CMain::GetProperty
  • CMain::GetPageProperty
  • CMain::GetPagePropertyList
  • CMain::GetDirProperty
  • CMain::GetDirPropertyList

The page and section properties are used in meta tags. The system exposes the following functions to handle meta tags:

  • CMain::ShowMeta
  • CMain::GetMeta

Methods for setting properties

  • CMain::SetPageProperty sets the page property.

    <?
$APPLICATION->SetPageProperty("keywords", "web, development, programming");
?>
  • CMain::SetDirProperty sets the section property.

    <?
$APPLICATION->SetDirProperty("keywords", "design, web, site");
?>

Showing properties

  • CMain::ShowProperty displays the page or section properties using the delay function technology.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title><?$APPLICATION->ShowProperty("page_title")?></title>
</head>
<body link="#525252" alink="#F1555A" vlink="#939393" text="#000000">
...

Obtaining property value

  • CMain::GetProperty returns the page or section property.

    <?
$keywords = $APPLICATION->GetProperty("keywords");
if (strlen($keywords)>0) echo $keywords;
?>
  • CMain::GetPageProperty returns the page property.

    <?
$keywords = $APPLICATION->GetPageProperty("keywords");
if (strlen($keywords)>0) echo $keywords;
?>
  • CMain::GetPagePropertyList returns an array of all page properties.

    <?
$arProp = $APPLICATION->GetPagePropertyList();
foreach($arProp as $key=>$value)
    echo '<meta name="'.$key.'" content="'.htmlspecialchars($value).'">';
?>
  • CMain::GetDirProperty returns the section property.

    <?
$keywords = $APPLICATION->GetDirProperty("keywords");
if (strlen($keywords)>0) echo $keywords;
?>
  • CMain::GetDirPropertyList returns an array of the section properties, collected recursively up to the site root.

    <?
$arProp = $APPLICATION->GetDirPropertyList();
foreach($arProp as $key=>$value)
    echo '<meta name="'.$key.'" content="'.htmlspecialchars($value).'">';
?>

Handling meta tags

  • CMain::ShowMeta emits the page or section property as the META tag using delay function technology.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<?$APPLICATION->ShowMeta("keywords_prop", "keywords")?>
<?$APPLICATION->ShowMeta("description_prop", "description")?>
</head>
<body link="#525252" alink="#F1555A" vlink="#939393" text="#000000">
...
  • CMain::GetMeta returns the page or section property decorated in the <meta> tag.

    <?
$meta_keywords = $APPLICATION->GetMeta("keywords_prop", "keywords");
if (strlen($meta_keywords)>0) echo $meta_keywords;
?>


Page parameters

Page parameters are used to pass parameters to the module functions to modify their standard behaviour. For example, it can be used to disable storing the last session page (if pagewise navigation is used) or to modify the standard date format in the functions of the Information blocks module.

Note!
Page parameters are available only within the page and are not stored neither in database nor in session.

The CPageOption class is used to handle page parameters. It contains the following methods:

  • CPageOption::SetOptionString - sets string parameters;
  • CPageOption::SetOptionInt - sets numeric parameters;
  • CPageOption::GetOptionString - gets string parameters;
  • CPageOption::GetOptionInt - gets numeric parameters;
  • CPageOption::RemoveOption - removes parameter.

Page parameters supported by the standard modules:

Module ID | Name | Parameter | Description | Default value
main | Kernel | nav_page_in_session | If "Y", the last opened page in pagewise navigation will be stored in session, otherwise "N". | Y
iblock | Information blocks | FORMAT_ACTIVE_DATES | If "FULL", the dates of an information block element (fields "ACTIVE_FROM" and "ACTIVE_TO") are returned in full format (with the time). If "SHORT" they are returned in short format (without the time). | SHORT

Example:

<?
CPageOption::SetOptionString("main", "nav_page_in_session", "N");
?>

<?
CPageOption::SetOptionString("iblock", "FORMAT_ACTIVE_DATES", "FULL");
?>

See Also

  • CPageOption
  • Module parameters


Components

A Component is a part of a module realized as a logically complete code stored in a file. Component can accept a set of parameters, accomplish a number of actions and display a result (for example, as an HTML code).

The concept of component includes the following elements:

  • main file is a PHP script implementing the component logic;
  • language files is used to display result in various languages;
  • description is used by the HTML editor to visually manage component and its parameters.

Using components is the most preferable way to organize the output of information in both public and administrative sections.


Main file of component

In this section

  • What is main file of component?
  • How to include
  • How to create
  • Additional information

What is main file of component?

Main file of component is a PHP file implementing the component logic. In its turn, the main file can use language files to translate messages into various languages.

How to include

The component is attached by inclusion of the main file using the function CMain::IncludeFile:

  • The first parameter of this function should specify the path to the main file of component relative to the following folders in priority descending order:
    1. /bitrix/templates/current site template ID/ - folder containing the current site template;
    2. /bitrix/templates/.default/ - folder containing the default site template;
    3. /bitrix/modules/module ID/install/templates/ - the module folder.
    Thus, the component may have more than one copy of the main file, but only one is included. This algorithm allows to:
    1. create the sets of components unique for each site template;
    2. create the sets of components common for all site templates;
    3. create a standard set of components for each module replenishing them using the Update system.
  • The second parameter of this function should specify an array of parameters passed to component. See also: How to create.
Example of inclusion of component
<?
// component displaying the information block element details
$APPLICATION->IncludeFile(
    "iblock/catalog/element.php",              // path to the main file of component
    Array(                                     // array of component parameters

        "IBLOCK_TYPE"       => "catalog",      // information block type
        "IBLOCK_ID"         => "21",           // information block
        "ELEMENT_ID"        => $_REQUEST["ID"],// element ID
        "SECTION_URL"       => "section.php",  // URL of the page with section content
        "arrFIELD_CODE"     => Array(          // fields
             "DETAIL_TEXT",
             "DETAIL_PICTURE"),
        "arrPROPERTY_CODE"  => Array(          // properties
             "YEAR",
             "STANDBY_TIME",
             "TALKTIME",
             "WEIGHT",
             "STANDART",
             "SIZE",
             "BATTERY",
             "SCREEN",
             "WAP",
             "VIBRO",
             "VOICE",
             "PC",
             "MORE_PHOTO",
             "MANUAL"),
        "CACHE_TIME"        => "3600",         // cache time (in seconds)

        )
    );
?>

How to create

When creating the main file of component, each and all system functions can be used. But it should be considered that the main file is included using the function CMain::IncludeFile, which has its own scope of variables. Hence, there are only two ways to pass the parameters to component:

  1. The first way is to use the second parameter of the function CMain::IncludeFile. You can pass an associated array in this parameter, which will be further available as $arParams in the main file of component. Besides, the array $arParams will be transformed into a set of variables with the same names as the array keys and the same values as those of the corresponding array keys (for details, see description of the standard PHP function extract).
  2. The second way is to pass the parameters to component via the global arrays of variables. This way of parameter is quite the same as passing parameters to a common PHP function. You may use the standard PHP arrays:
    • $GLOBALS
    • $_REQUEST
    • $_GET
    • $_POST
    • $_SERVER
    • etc.
    as well as your own global arrays defined prior to including component.

    The following variables are defined as global in the function CMain::IncludeFile:

    • $APPLICATION
    • $USER
    • $DB
    • $MESS
    • $DOCUMENT_ROOT

The variable scope confinement within the main component file stipulates special conditions of using certain functions. It refers to those functions which initialise the global variables. If these global variables will be further used within the main file of component, you have to address them via the standard PHP array $GLOBALS, or preliminary define these variables as global using the standard PHP directive global. Mainly, it refers to the following functions:

  • InitFilterEx
  • DelFilterEx
  • InitSorting
  • CDataBase::InitTableVarsForEdit
  • CDataBase::PrepareFields
  • CDBResult::NavNext
Example of the main file of component
<?
/**************************************************************************
                component displaying the information block element
                iblock/catalog/element.php
***************************************************************************/

if (CModule::IncludeModule("iblock")):

    IncludeTemplateLangFile(__FILE__);

    /*************************************************************************
                Initialise the original parameters of the component
    *************************************************************************/

    /*
    $IBLOCK_TYPE        = $arParams["IBLOCK_TYPE"];       // information block type
    $IBLOCK_ID          = $arParams["IBLOCK_ID"];         // information block ID
    $ELEMENT_ID         = $arParams["ELEMENT_ID"];        // element ID
    $SECTION_URL        = $arParams["SECTION_URL"];       // URL of the page with section content
    $arrFIELD_CODE      = $arParams["arrFIELD_CODE"];     // an array of field ID's
    $arrPROPERTY_CODE   = $arParams["arrPROPERTY_CODE"];  // an array of property ID's
    $CACHE_TIME         = $arParams["CACHE_TIME"];        // cache time (in seconds)
    */

    $arrFIELD_CODE = (is_array($arrFIELD_CODE)) ? $arrFIELD_CODE : array();
    $arrPROPERTY_CODE = (is_array($arrPROPERTY_CODE)) ? $arrPROPERTY_CODE : array();
    $ELEMENT_ID = intval($ELEMENT_ID);

    /*************************************************************************
                                Using cache
    *************************************************************************/

    $obCache = new CPHPCache;
    $CACHE_ID = __FILE__.md5(serialize($arParams).$USER->GetGroups());
    if($obCache->InitCache($CACHE_TIME, $CACHE_ID, "/"))
    {
        $arVars = $obCache->GetVars();
        $ELEMENT_NAME  = $arVars["ELEMENT_NAME"];
        $IBLOCK_ID     = $arVars["IBLOCK_ID"];
        $SECTION_ID    = $arVars["SECTION_ID"];
        $SECTION_NAME  = $arVars["SECTION_NAME"];
        $KEYWORDS      = $arVars["KEYWORDS"];
        $DESCRIPTION   = $arVars["DESCRIPTION"];
        $arrPath       = $arVars["arrPath"];
        $found = "Y";
    }
    else
    {
        if ($ELEMENT_ID>0)
        {
            $arSelect = array(
                "ID",
                "NAME",
                "IBLOCK_ID",
                "IBLOCK_SECTION_ID"
                );
            if ($rsElement = GetIBlockElementListEx($IBLOCK_TYPE,
                                                    false, false, array(),
                                                    false,
                                                    array("ID" => $ELEMENT_ID),
                                                    $arSelect))
            {
                if ($obElement = $rsElement->GetNextElement())
                {
                    $found = "Y";
                    $arElement = $obElement->GetFields();
                    $arProperty = $obElement->GetProperties();
                    $KEYWORDS = $arProperty["KEYWORDS"]["VALUE"];
                    $DESCRIPTION = $arProperty["DESCRIPTION"]["VALUE"];
                    $ELEMENT_NAME = $arElement["NAME"];
                    $IBLOCK_ID = $arElement["IBLOCK_ID"];
                    $SECTION_ID = $arElement["IBLOCK_SECTION_ID"];
                    if ($rsSection = CIBlockSection::GetByID($SECTION_ID))
                    {
                        $arSection = $rsSection->Fetch();
                        $SECTION_NAME = $arSection["NAME"];
                    }
                }
            }

            $arrPath = array();
            $rsPath = GetIBlockSectionPath($IBLOCK_ID, $SECTION_ID);
            while($arPath=$rsPath->GetNext())
                $arrPath[] = array("ID" => $arPath["ID"],
                                   "NAME" => $arPath["NAME"]);
        }
    }

    // if the element is found
    if ($found == "Y"):

        $APPLICATION->SetPageProperty("keywords", $KEYWORDS);
        $APPLICATION->SetPageProperty("description", $DESCRIPTION);

        CIBlock::ShowPanel($IBLOCK_ID, $ELEMENT_ID, $SECTION_ID, $IBLOCK_TYPE);
        $APPLICATION->SetTitle($ELEMENT_NAME);
        if (is_array($arrPath))
        {
            while(list($key, $arS) = each($arrPath))
            {
                if ($SECTION_ID==$arS["ID"]) $SECTION_NAME = $arS["NAME"];
                $APPLICATION->AddChainItem($arS["NAME"],
                                           $SECTION_URL."SECTION_ID=".$arS["ID"]);
            }
        }

        CIBlockElement::CounterInc($ELEMENT_ID);

        if($obCache->StartDataCache()):

            $arSelect = array(
                "ID",
                "IBLOCK_ID",
                "IBLOCK_SECTION_ID",
                "DETAIL_TEXT_TYPE",
                "PREVIEW_TEXT_TYPE",
                "DETAIL_PICTURE",
                "PREVIEW_PICTURE",
                );
            $arSelect = array_merge($arSelect, $arrFIELD_CODE);
            if ($rsElement = GetIBlockElementListEx($IBLOCK_TYPE, false,
                                                    false, array(), false,
                                                    array("ID" => $ELEMENT_ID),
                                                    $arSelect)) :

                if ($obElement = $rsElement->GetNextElement()) :

                    $arElement = $obElement->GetFields();
                    $arProperty = $obElement->GetProperties();

                    /****************************************************************
                                            HTML form
                    ****************************************************************/
                    ?>
                    <table width="70%" border="0" cellspacing="0" cellpadding="7">
                        <tr>
                            <?
                            if (in_array("PREVIEW_PICTURE", $arrFIELD_CODE))
                            {
                                $image = intval($arElement["PREVIEW_PICTURE"])>0 ?
                                    $arElement["PREVIEW_PICTURE"] :
                                    $arElement["DETAIL_PICTURE"];
                            }
                            if (in_array("DETAIL_PICTURE", $arrFIELD_CODE))
                            {
                                $image = intval($arElement["DETAIL_PICTURE"])>0 ?
                                    $arElement["DETAIL_PICTURE"] :
                                    $arElement["PREVIEW_PICTURE"];
                            }
                            ?>
                        </tr>
                    </table>

                    <?if (strlen($arElement["PREVIEW_TEXT"])>0):?>
                    <font class="text"><p><?=$arElement["PREVIEW_TEXT"]?></p></font>
                    <?endif;?>

                    <?if (strlen($arElement["DETAIL_TEXT"])>0):?>
                    <font class="text"><p><?
                    echo ($arElement["DETAIL_TEXT_TYPE"]=="html") ?
                              $arElement["DETAIL_TEXT"] :
                              TxtToHTML($arElement["~DETAIL_TEXT"]);
                    ?></p></font>
                    <?endif;

                endif;
            endif;

            $obCache->EndDataCache(array(
                "ELEMENT_NAME"    => $ELEMENT_NAME,
                "IBLOCK_ID"        => $IBLOCK_ID,
                "SECTION_ID"    => $SECTION_ID,
                "SECTION_NAME"    => $SECTION_NAME,
                "KEYWORDS"        => $KEYWORDS,
                "DESCRIPTION"    => $DESCRIPTION,
                "arrPath"        => $arrPath
                ));
        endif;
    else:
            ShowError(GetMessage("CATALOG_ELEMENT_NOT_FOUND"));
    endif;
endif;
?>

Additional information

  • CMain::IncludeFile


Language files of component

Components include the language files using the function IncludeTemplateLangFile. This function searches for language files using the following algorithm:

  1. Firstly, language file is looked up in the folder

    /bitrix/templates/current site template ID/lang/language ID/path to component

  2. If the file cannot be found, it is looked up in the folder

    /bitrix/templates/.default/lang/language ID/path to component

  3. Then, if the file still cannot be found, the following folder is searched:

    /bitrix/modules/module ID/install/templates/lang/language ID/path to component
The "path to component" description can be found in this topic.

See also

  • What is language files
  • IncludeTemplateLangFile


Components explained

In this topic

  • General information
  • Structure
  • Example
  • Language files
  • Additional information

General information

To visually manage component and its parameters in the HTML editor, the component description file needs to be created.
The component description is a PHP file with the name .description.php which can reside in one of the following directories (or subdirectories):

  • /bitrix/templates/.default/module ID/ - directory with the default site template;
  • /bitrix/modules/module ID/install/templates/module ID/ - the module directory;

Structure of the file .description.php

This file can describe both a single component and a group of components. The following standard variables are available in it:

  • $sSectionName - the module title for the drop-down list of modules;
  • $iSort - sort weight of the module name in the drop-down list;
  • $arCurrentValues - an array of the current values of the component parameters;
  • $arTemplateDescription - an array describing the list of components and their parameters. The array has the following structure:

    Array
(
  [the unique ID of separator 1] => an array describing separator 1:
    Array
      (
        ["SEPARATOR"] => "Y"
        ["NAME"] => separator name
        ["DESCRIPTION"] => separator description
      )
  [relative path to component 1] => an array describing component 1 and its parameters:
    Array
      (
        ["PARENT"] => ID of separator to whose group this component belongs
        ["NAME"] => component name (required)
        ["DESCRIPTION"] => component description
        ["ICON"] => path from the root to the component icon
        ["PARAMS"] => an array describing the set of the component parameters:
          Array
            (
              [parameter 1 ID] => an array describing parameter 1:
                Array
                  (
                    ["NAME"] => parameter name

                    ["TYPE"] => type of the input field for the parameter value, the following values are possible:
                      "STRING" - single line text field
                      "LIST" - list

                    ["SIZE"] => if TYPE is "LIST", the number of list strings visible without scrolling can be specified here

                    ["VALUES"] => if TYPE is "LIST", specify here an array of elements of this list in the form of:
                      Array
                        (
                          ["element 1 ID"] => element 1 value
                          ["element 2 ID"] => element 2 value
                          ["element 3 ID"] => element 3 value
                          ...
                        )
                    ["ADDITIONAL_VALUES"] => if TYPE is "LIST", setting this parameter to "N"
                                             disables the additional field used to manually input
                                             the value of the list
                    ["MULTIPLE"] => if "Y", the value of the parameter is
                      an array with the arbitrary number of elements
                    ["COLS"] => number of columns in the input fields
                    ["ROWS"] => number of strings in the input fields
                    ["DEFAULT"] => the default value of the parameter
                    ["CNT"] => number of fields to enter values of component parameters
                    ["REFRESH"] => if "Y", the button to reset the page containing the component parameters
                                   will be available beside the parameter input field
                      (usually, it is used when the values of component parameters
                      depend on each other: for example, choosing the type of information block
                      changes the list of available blocks)
                  )
              [parameter 2 ID] => an array describing parameter 2
              [parameter 3 ID] => an array describing parameter 3
              ...
            )
      )
  [relative path to component 2] => an array describing component 2 and its parameters
  [relative path to component 3] => an array describing component 3 and its parameters
  [the unique ID of separator 2] => an array describing separator 2
  ...
)

    In the above structure:

    • the unique ID of separator is an arbitrary set of symbols which is unique within all components of the specific module;
    • relative path to component is the path to the main file of the component relative to the directory containing the file .description.php

Example of file .description.php

Sometimes, additional code is required to be added to the file .description.php. For example, when a list of information blocks or web forms is to be obtained. It is to emphasize that in this case no constrains and limitations are applied to this file. All the available modules and functions of the system can be used in it.

<?
// file
// /bitrix/modules/iblock/install/templates/iblock/catalog/.description.php

IncludeTemplateLangFile(__FILE__);
if (!CModule::IncludeModule("iblock")) return;

/*************************************************************************
                    Initialise required arrays
**************************************************************************/

// obtain an array of the information blocks types $arIblockType
$rsType = CIBlockType::GetList(array("sort"=>"asc"), array("ACTIVE"=>"Y"));
while ($arr=$rsType->Fetch())
{
    if($ar=CIBlockType::GetByIDLang($arr["ID"], LANGUAGE_ID))
        $arIblockType[$arr["ID"]] = "[".$arr["ID"]."] ".$ar["NAME"];
}

// obtain an array of the information blocks $arIblock
$rsIblock = CIBlock::GetList(
    Array("sort" => "asc"),
    Array("TYPE" => $arCurrentValues["IBLOCK_TYPE"], "ACTIVE"=>"Y")
    );
while($arr=$rsIblock->Fetch())
    $arIblock[$arr["ID"]] = "[".$arr["ID"]."] ".$arr["NAME"];

// obtain an array of the information blocks properties $arProperty
$rsProp = CIBlockProperty::GetList(
    Array("sort"=>"asc", "name"=>"asc"),
    Array("ACTIVE"=>"Y", "IBLOCK_ID"=>$arCurrentValues["IBLOCK_ID"])
    );
while ($arr=$rsProp->Fetch())
{
    $arProperty[$arr["CODE"]] = "[".$arr["CODE"]."] ".$arr["NAME"];
}

/***************************************************************************
                    "Product catalog" separator
****************************************************************************/

$arTemplateDescription = Array(
    ".separator" =>
        Array(
            "NAME"        => GetMessage("T_IBLOCK_DESC_CAT"),
            "DESCRIPTION" => "",
            "SEPARATOR"   => "Y",
        )
    );

/***************************************************************************
                    Detail view of catalog element
****************************************************************************/

$arTemplateDescription["element.php"] = array(
    "PARENT"       => ".separator",
    "NAME"         => GetMessage("IBLOCK_ELEMENT_TEMPLATE_NAME"),
    "DESCRIPTION"  => GetMessage("IBLOCK_ELEMENT_TEMPLATE_DESCRIPTION"),
    "ICON"         => "/bitrix/images/iblock/components/cat_detail.gif",
    "PARAMS" => array(
        "IBLOCK_TYPE" => array(
            "NAME"              => GetMessage("IBLOCK_TYPE"),
            "TYPE"              => "LIST",
            "ADDITIONAL_VALUES" => "Y",
            "VALUES"            => $arIblockType,
            "REFRESH"           => "Y"
            ),
        "IBLOCK_ID" => array(
            "NAME"              => GetMessage("IBLOCK_IBLOCK"),
            "TYPE"              => "LIST",
            "ADDITIONAL_VALUES" => "Y",
            "VALUES"            => $arIblock,
            "REFRESH"           => "Y"
            ),
        "ELEMENT_ID" => array(
            "NAME"              => GetMessage("IBLOCK_ELEMENT_ID"),
            "TYPE"              => "STRING",
            "DEFAULT"           => '={$_REQUEST["ID"]}'
            ),
        "SECTION_URL" => array(
            "NAME"              => GetMessage("IBLOCK_SECTION_URL"),
            "TYPE"              => "STRING",
            "DEFAULT"           => "section.php"
            ),
        "LINK_IBLOCK_TYPE" => array(
            "NAME"              => GetMessage("IBLOCK_LINK_IBLOCK_TYPE"),
            "TYPE"              => "LIST",
            "ADDITIONAL_VALUES" => "Y",
            "VALUES"            => $arIblockType,
            "REFRESH"           => "Y"
            ),
        "arrFIELD_CODE" => array(
            "NAME"              => GetMessage("IBLOCK_FIELD"),
            "TYPE"              => "LIST",
            "MULTIPLE"          => "Y",
            "ADDITIONAL_VALUES" => "N",
            "VALUES" => array(
                "NAME"           => GetMessage("IBLOCK_NAME"),
                "PREVIEW_TEXT"   => GetMessage("IBLOCK_PREVIEW_TEXT"),
                "DETAIL_TEXT"    => GetMessage("IBLOCK_DETAIL_TEXT"),
                "DETAIL_PICTURE" => GetMessage("IBLOCK_DETAIL_PICTURE"),
                )
            ),
        "arrPROPERTY_CODE" => array(
            "NAME"              => GetMessage("IBLOCK_PROPERTY"),
            "TYPE"              => "LIST",
            "MULTIPLE"          => "Y",
            "ADDITIONAL_VALUES" => "N",
            "VALUES"            => $arProperty
            ),
        "CACHE_TIME" => array(
            "NAME"              => GetMessage("IBLOCK_CACHE_TIME"),
            "TYPE"              => "STRING",
            "DEFAULT"           => "3600"
            ),
        )
    );
?>

Language files

To include the language files within the file .description.php, the function IncludeTemplateLangFile is used. In the above example, the description file has the following path:

/bitrix/modules/iblock/install/templates/iblock/catalog/.description.php.

The language file is included in it using the instruction:

IncludeTemplateLangFile(__FILE__);
The language file should be one of the following (in priority descending order):
  • /bitrix/templates/current site template ID/lang/language ID/iblock/catalog/.description.php
  • /bitrix/templates/.default/lang/language ID/iblock/catalog/.description.php
  • /bitrix/modules/iblock/install/templates/lang/language ID/iblock/catalog/.description.php

Additional information

Note
The component description requires the following files:

/bitrix/templates/.default/module ID/.description.php

/bitrix/modules/module ID/install/templates/module ID/.description.php

which initialise the variable $sSectionName containing the module name for the drop-down list of modules in the the HTML editor. If this file cannot be found, the corresponding item is not shown in the drop-down list of modules.

If an additional PHP code is required to be added when modifying parameters, the following syntax can be used:
"={...}".

For example:

={$_REQUEST["BID"]}

={(isset($_REQUEST["BID"]) ? $_REQUEST["BID"] : "15")}


Introduction to Components 2.0

The Component

Components are blocks, or bricks, with which the whole public section is built. The components fully implement the Carrier Rider Mapper pattern.

Carrier
Persistent object containing information which can be accessed by more than one client simultaneously.
Rider
Riders (Reader or Writer) are objects created by Carrier thereby providing access to persisted data. Clients can read and write information only via Reader or Writer. Thus, Reader and Writer are data access interfaces.
Mapper
Mappers (Scanner or Formatter) are wrappers for Reader and Writer functionality. Mappers are able to convert data to formats required by client.

Read flow is as follows: Carrier -> Reader -> Scanner -> Client.

Write flow is as follows: Carrier <- Writer <- Formatter <- Client.

Adding a mapping tier between Carrier/Rider and clients allows to connect a single Carrier/Rider to different clients by means of appropriate mappers.

Components allow developers to reuse their once created and tested code. The visual editor empowers site administrators with handy tools to add components to pages and and configure them without having to change the source code. The standard set of visual components is constantly updated.

What's so special about Components 2.0

  • Components 2.0 can segregate view from logic. A "logic" object can have more than one views attached to it which may depend on site template conditions. A view (display template) can be created in any templating language recognizable by PHP (e.g. PHP, Smarty, XSL etc.). A developer can thereby avoid changing the component logic code to alter the display. The view code is generally smaller than the component in the whole.

    In other words, a "logic" is the component core, while a "view" is the component display template.
  • All components are stored in a single folder. This makes the site structure more robust and comprehensive. This folder is available to components; they can easily access their or shared resources if required.

    Attention!
    Files access to which is forbidden must start with the following code:

    <?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>
  • The component stores all the private files in its own folder; you can easily share components between projects by copying. Component is atom (indivisible entity).
  • Compound components (e.g. Forum or Catalog) has the following distinctions.
    • Developers do not have to create many pages manually to add all the required child components. Common properties can be specified once for all subcomponents.
    • Developers avoid establishing complex relationships between subcomponents. For example, in forum message pages, you do not need to worry about links to forum topic list and user profile pages.
    • You can add a new page even to a component with customized display template. For example, if you enhance the forum with a top ten users page (subcomponent), this page will be available in the public section.
    • Changing a display template can be a single call instead of altering the visual aspect for every subcomponent.
© 2001-2007 Bitrix Bitrix Site Manager


Compound components

Definitions

Simple (single page) components create an area in a given single page. For example, the news display component creates a news display area in which it renders the news title and body, in a page where it is placed.

Compound (multiple page) components create site sections. For example, the catalog component creates the whole catalog section: catalog entries, catalog groups, product pages. In other words, a compound component form a set of pages. Compound components are built on the basis of simple components.

MVC

The foundation of compound components is the MVC (Model View Controller) design pattern. This concept breaks application data model, user interface and logic into three separate, individual parts in such a way that any change in one of the areas makes a minimum impact on others.

MVC
  • Model is the system core. The Model represents data and business logic, and can respond to requests of the View.
  • View is a set of simple components (in reality, things are more complicated but we shall omit details to make the first insight easier). The View displays data to a user, requests data from the Model, sends user actions to the Controller (usually via HTTP requests).
  • Controller is a compound component. The Controller selects an appropriate View based on user actions and the Model's response.

A typical flow of the MVC pattern is as follows.

  • The Controller reacts to user actions and selects a View to be displayed to a user, and passes control to a selected view.
  • The View requests data from the Model, receives data and displays them to a user.
  • A user sends new requests to the Controller by means of controls granted by the View.

When applied to compound components, the MVC algorithm works in the following way.

  • The compound component (controller) reacts to user actions (generally, HTTP requests) by selecting an appropriate page (view) to be displayed to a user, and activates (includes) the template for this page.
  • The page template (view) connects simple components and configures their settings as required.
  • Simple components do what they are supposed to: request data from kernel (model); format and render it to a user; display required controls (links, forms, buttons etc.).
  • User sends new requests (HTTP requests) to the compound component (controller) by activating the controls.

Example

Consider a simple example of how a news compound component may function. Say we have the following simple components: "list of news" and "news details", the latter takes the ID of news to be displayed as input parameter.

The news site section can be created, for example, by adding the "list of news" component to a section index page, and creating a news.php page and adding the "news details" component to it. The components must be properly configured: the list of news is to be able to build links to a news details page including the news ID; the news details component should have input parameters configured in such a way that it would be able to display a link to the list of news.

Configuring the components properly requires that we know the path to the news details page, the name of all parameters that the components can take on input, etc. Even in this example, configuring may be a headache. But imagine tenths of forum components!

An easier alternative that a web developer can take is using the news compound component. You can simply add this component to the index page. The component will take full control over maintaining correct links and parameters; this will not require any additional actions on the developer side. Creating the news complex component requires that you check the news ID in URL's. If an URL contains the news ID, the component will activate the page that would display the news text. Otherwise, the component would display the list of news.

Pages of the compound component template would connect simple components and configure their input parameters properly. Simple components will carry out their functions as usual; the only important thing is configuring the input parameters correctly.

Thus, the MVC pattern flow works as follows:

  • the compound component (controller) receives HTTP requests (user actions);
  • then, it verifies whether an HTTP request contains the news ID, and connects either the list of news template, or the news details template;
  • the template, in its turn, connects an appropriate simple component and sets its input parameters as required;
  • the simple component performs its functions: acquires data from the model, formats and renders them; displays user controls;
  • user sends new requests (HTTP requests) to the compound component (controller) by activating the controls;
  • the whole procedure loops as needed.
© 2001-2007 Bitrix Bitrix Site Manager


Storage of components

Physical layout

All components reside in /bitrix/components/. System components reside in /bitrix/components/bitrix/. Contents of this folder is updated by the update system and must not be changed by user.

Note!
Changing the contents of the folder /bitrix/components/bitrix/ may cause unpredictable effects.

Custom components may be stored in other subfolders of /bitrix/components/ or in /bitrix/components/ immediately.

Naming

A name of a subfolder of /bitrix/components/ creates a component namespace. For example, all system components reside in the bitrix namespace. When creating custom components, it is a good practice to create a new namespace and place new components in it.

For example, there is a system component named catalog, which exists in the bitrix namespace. If you need to create your own component with the same name (catalog), you will have to create a new namespace (subfolder) in /bitrix/components/ (e.g., mycompany), and place a new component catalog in this folder. Thus, there will be two catalog components in different namespace: bitrix:catalog and mycompany:catalog.

Names of components follow the format "identifier1.identifier2....". For example: «catalog», «catalog.list», «catalog.section.element» etc. A good idea is to create hierarchical names, from common to particular, e.g. "catalog.section.elements" for a component that would display a list of products of a given group.

The full component name is a component name forestalled by the namespace name (namespace:component). For example: bitrix:catalog.list. If a component exists outside the namespace, the namespace is void and is omitted, e.g. catalog.section.

© 2001-2007 Bitrix Bitrix Site Manager


Component folder structure

The component folder can contain the following subfolders and files.

Subfolders

Folder | Description
help | The help folder contains component help files. Help sections can be represented in many languages, each of which should be stored in a folder named after the language abbreviation. Each language folder must have a index.php file, which is the main help file for the corresponding language. For example, the path name of the English help file can be /help/en/index.php. Note! You should describe the structure of an array in which the component returns data to a template. The help folder is optional.
install | Contains installation and uninstallation scripts. The installation script must have name install.php, and the uninstallation script - uninstall.php. The install folder is optional.
lang | This folder contains subfolders with text messages. Subfolder names are the abbreviations of languages in which the text messages are stored. A good practice is to save a text message file under the same name as a corresponding file of the component, and store it in the same folder hierarchy. For example, the file with English messages for /install/uninstall.php is to be saved in /lang/en/install/uninstall.php. The lang folder is optional if the component does not use language-dependent messages.
templates | Contains component display templates. This folder is optional if the component does not use display templates.

Files

File | Description
component.php | This is the core file containing the component logic. This file must exist.
.description.php | Contains the name and the description of the component. Also it describes the component disposition in the visual editor component pane. This file must exist.
.parameters.php | Contains the description of the component input parameters. This file must exist if the component uses input parameters.
Any other files and folders with resources required by the component. All the private component resources must be located inside the component folder.
© 2001-2007 Bitrix Bitrix Site Manager


Component description file - .description.php

The file .description.php contains the component description. The description is used when manipulating the component from within Bitrix Site Manager (e.g. in the visual editor), and in the site editing mode. The component itself does not use this file; it is not included when the component is activated (for example, when loading a page containing the component).

The file .description.php must reside in the component subfolder. The corresponding language message file is loaded automatically (it must reside in /lang/<language>/.description.php relative to the component folder).

A typical .description.php file has the following structure:

<?
$arComponentDescription = array(
   "NAME" => GetMessage("COMP_NAME"),
   "DESCRIPTION" => GetMessage("COMP_DESCR"),
   "ICON" => "/images/icon.gif",
   "PATH" => array(
      "ID" => "content",
      "CHILD" => array(
         "ID" => "catalog",
         "NAME" => "Product catalog"
      )
   ),
   "AREA_BUTTONS" => array(
      array(
         'URL' => "javascript:alert('This is a button!!!');",
         'SRC' => '/images/button.jpg',
         'TITLE' => "This is a button!"
      ),
   ),
   "CACHE_PATH" => "Y",
   "COMPLEX" => "Y"
);
?>

As you can see, the file declares the array $arComponentDescription, which describes the component. This array can have the following keys:

  • "NAME" - the name of the component;
  • "DESCRIPTION" - the description of the component;
  • "ICON" - the path to a component icon relative to the component folder. This icon is used, for example, in the visual editor;
  • "PATH" - disposition of the component in the virtual tree of components in the visual editor. The value of this key is an array with the following keys:
    • "ID" - the ID of a tree branch;
    • "NAME" - the name of a tree branch;
    • "CHILD" - child or subordinate branch. This value can define a subordinate branch of a tree of the same structure as a parent branch.
    The maximum number of tree levels is 3. Usually, a two-level tree is used in which the components occupy the second level. The following names of the first level are reserved and cannot be used:: "content", "service", "communication", "e-store", "utility".

    If the "PATH" key does not exist, the component will not be visible in the visual editor;
  • "AREA_BUTTONS" - custom buttons that are visible in the site editing mode;
  • "CACHE_PATH" - if "Y", the cache flush button is displayed in the site editing mode. The cache is supposed to reside in /<site ID>/<relative path to component>). A value of non-empty string other than "Y" indicates that this value is the non-standard path to the cache, and the cache flush button is also displayed;
  • "COMPLEX" - "Y" for compound components. This key is meaningless for simple components.
© 2001-2007 Bitrix Bitrix Site Manager


Component parameters file - .parameters.php

The file .parameters.php contains description of the component input parameters. The description of parameters is used when manipulating the component from within Bitrix Site Manager (e.g. in the visual editor), and in the site editing mode. The component itself does not use this file; it is not included when the component is activated (for example, when loading a page containing the component).

The contents of this file is used solely to create the parameters input form (e.g. in the visual editor).

The file .parameters.php must reside in the component's subfolder. The corresponding language message file is loaded automatically (it must reside in /lang/<language>/.parameters.php relative to the component folder).

A typical .parameters.php file has the following structure:

<?
CModule::IncludeModule("iblock");

$dbIBlockType = CIBlockType::GetList(
   array("sort" => "asc"),
   array("ACTIVE" => "Y")
);
while ($arIBlockType = $dbIBlockType->Fetch())
{
   if ($arIBlockTypeLang = CIBlockType::GetByIDLang($arIBlockType["ID"], LANGUAGE_ID))
      $arIblockType[$arIBlockType["ID"]] = "[".$arIBlockType["ID"]."] ".$arIBlockTypeLang["NAME"];
}

$arComponentParameters = array(
   "GROUPS" => array(
      "SETTINGS" => array(
         "NAME" => GetMessage("SETTINGS_PHR")
      ),
      "PARAMS" => array(
         "NAME" => GetMessage("PARAMS_PHR")
      ),
   ),
   "PARAMETERS" => array(
      "IBLOCK_TYPE_ID" => array(
         "PARENT" => "SETTINGS",
         "NAME" => GetMessage("INFOBLOCK_TYPE_PHR"),
         "TYPE" => "LIST",
         "ADDITIONAL_VALUES" => "Y",
         "VALUES" => $arIblockType,
         "REFRESH" => "Y"
      ),
      "BASKET_PAGE_TEMPLATE" => array(
         "PARENT" => "PARAMS",
         "NAME" => GetMessage("BASKET_LINK_PHR"),
         "TYPE" => "STRING",
         "MULTIPLE" => "N",
         "DEFAULT" => "/personal/basket.php",
         "COLS" => 25
      ),
      "SET_TITLE" => array(),
      "CACHE_TIME" => array(),
      "VARIABLE_ALIASES" => array(
         "IBLOCK_ID" => array(
            "NAME" => GetMessage("CATALOG_ID_VARIABLE_PHR"),
         ),
         "SECTION_ID" => array(
            "NAME" => GetMessage("SECTION_ID_VARIABLE_PHR"),
         ),
      ),
      "SEF_MODE" => array(
         "list" => array(
            "NAME" => GetMessage("CATALOG_LIST_PATH_TEMPLATE_PHR"),
            "DEFAULT" => "index.php",
            "VARIABLES" => array()
         ),
         "section1" => array(
            "NAME" => GetMessage("SECTION_LIST_PATH_TEMPLATE_PHR"),
            "DEFAULT" => "#IBLOCK_ID#",
            "VARIABLES" => array("IBLOCK_ID")
         ),
         "section2" => array(
            "NAME" => GetMessage("SUB_SECTION_LIST_PATH_TEMPLATE_PHR"),
            "DEFAULT" => "#IBLOCK_ID#/#SECTION_ID#",
            "VARIABLES" => array("IBLOCK_ID", "SECTION_ID")
         ),
      ),
   )
);
?>

The file declares the array $arComponentDescription, which describes the component's input parameters. If required, additional data is fetched. For example, all the active information block types may be selected to create a list of information block types for the input parameter IBLOCK_TYPE_ID.

This array can have the following keys:

  • "GROUPS" - value is an array of groups of component parameters. In the user interface of Bitrix Site Manager, parameters are joined in groups. Groups are displayed in the same order as they are defined in the file. An array of groups of parameters consists of entries in the following format:
    "код группы" => array(
    "NAME" => "name of the group in the current language"
    )
  • "PARAMETERS" - value is an array of component's parameters. Each group displays parameters in the same order as they are defined in the file. A common array of parameters contains the following elements:
    "parameter ID" => array(
    "PARENT" => "parent group ID",
    "NAME" => "name of the parameter in the current language",
    "TYPE" => "type of the control to display the parameter",
    * * *
    )

Special standard parameters does not require full description; you can only mention them. For example:

"SET_TITLE" => array(),
"CACHE_TIME" => array(),

The first parameter tells the component engine to set the page title, and the second one tells to display the caching time.

If the component supports human friendly URL's, or it can redefine HTTP request variables (parameters), the following two special parameters are to be specified:

  • "VARIABLE_ALIASES" - array with variables that the component can receive from a HTTP request. Each entry has the following format:
    "internal variable name" => array(
  "NAME" => "variable name in the current language",
)
  • "SEF_MODE" - array containing path templates in the human friendly mode. Each entry has the following format:
    "path template ID" => array(
    "NAME" => "template name in the current language",
    "DEFAULT" => "default path template",
    "VARIABLES" => "array of internal names of variables
                        that can be used in the temlpate"
)
© 2001-2007 Bitrix Bitrix Site Manager


Notes on $arParams and $arResult

$arParams

$arParams is the predefined variable containing an array of the component input parameters. Keys are the names of parameters, and the values are parameter values.

Before the component is activated, htmlspecialcharsEx is called on values of all parameters.

The original parameter values are stored in this array but have the prefix of tilde "~". For example, $arParams["NAME"] is an input parameter processed with htmlspecialcharsEx, and $arParams["~NAME"] is the original parameter.

The variable $arParams is a reference to the corresponding component class member, so all changes to this variable affect the class member. On startup, the component should verify input parameters, initialize variables, cast types (e.g. IntVal). The template will have access to these altered parameters; that is, parameters will be verified and safe. The template does not have to verify and prepare parameters again.

$arResult

$arResult is the predefined variable accumulating the component's output before trensferring it to the template. Before the component is activated, this variable is set to an empty array().

$arResult is a reference to the corresponding component class member, so all changes to this variable affect the class member. Do not pass this variable to the template explicitly; it is performed by the component internal logic.

PHP references

PHP references are used to address a piece of information by different names. All changes to $arParams and $arResult will be available in the template as well.

References are powerful, but you may come across some pitfalls.

  • The code:
    $arParams = & $arSomeArray;
    unbinds $arParams from the component class member and attaches it to $arSomeArray. In this case, all changes to $arParams will not affect the component template.
  • The code:
    unset($arParams);
    also breaks relationship between $arParams and the component class member.
© 2001-2007 Bitrix Bitrix Site Manager


Component cache

To boost client request processing and reduce server load, components ought to use caching. Generally, components should cache information that does not depend on the client. For example, the list of site news is identical to all visitors and it is senseless to call database routines every time this information is required. Caching time depends on how frequent new information arrives to the database. Sometimes visitor dependent information can also be cached.

Built-in cache

Components 2.0 offer the built-in caching support. The following example illustrates how a component can use the built-in caching.

// Verify and initialise input parameters
if ($arParams["ID"] <= 0)
   $arParams["ID"] = 10;

// Check whether valid cache exists
// if not, fetch data and create cache
if ($this->StartResultCache())
{
   // Execute query and fill in $arResult
   $arResult = array(
      "ID" => rand(1, 100)
   );

   for ($i = 0; $i < 5; $i++)
      $arResult["FIELDS"][] = rand(1, 100);

   // If some condition is true -
   // do not cache
   if ($arParams["ID"] < 10)
      $this->AbortResultCache();

   // Connect display template
   $this->IncludeComponentTemplate();
}

// Call delay function to set page title
$APPLICATION->SetTitle($arResult["ID"]);
Notes

StartResultCache has the following prototype:

bool $this->StartResultCache($cacheTime = False,
                             $additionalCacheID = False,
                             $cachePath = False)
where:
  • $cacheTime - caching time (False sets this parameter to IntVal($arParams["CACHE_TIME"]) ).
  • $additionalCacheID - specifies additional cache dependencies in addition to the current SITE_ID, component name, file path and the output $arParams. If False, the cache depends only on the mentioned parameters.
  • $cachePath - the path to the cache file (False sets this parameter to "/".SITE_ID.<path to component relative to bitrix/components>).

If the valid cache exists, the method displays its contents, fills in $arResult and returns False; otherwise, it returns True.

If the cache depends on some other parameters in addition to the site ID, input parameters, component name and the site path, you have to pass these parameters as a string in the second parameter. For example, if the cache depends on user groups whose member is the current user, the following code applies:

if ($this->StartResultCache(false, $USER->GetGroups()))
{
   // No valid cache.
   // Select data from database to $arResult
}

If, when creating a new cache, it turned out that the information should not be cached, call the following method:

$this->AbortResultCache();

For example, you may need to abort creating the cache if there is no news with a specified ID. If you do not abort cache, criminals can grow the cache to the maximum available disk space by calling the page with arbitrary ID's.

The method

$this->IncludeComponentTemplate();

connects the component template and stores the output and $arResult in the cache. All changes made to $arResult and the output emitted after calling this method will not be stored in cache.

If the following condition is false:

if ($this->StartResultCache())

it means that there is a valid cache for the given component, page and input parameters. Calling this method displays cached HTML and fills in $arResult. Now we can perform some required actions, e.g. set the page title using delay functions.

The following method allows to clear the cache if required (e.g. upon data change):

$this->ClearResultCache($additionalCacheID = False,
                        $cachePath = False)

Parameters of this method are identical to those of StartResultCache.

Complex caching

If your component requires special caching algorithm that cannot be implemented using the built-in functions, you can use the CPHPCache class. A sample caching solution could be the following:

// Verify and initialise input parameters
if ($arParams["ID"] <= 0)
   $arParams["ID"] = 10;

$arParams["CACHE_TIME"] = IntVal($arParams["CACHE_TIME"]);
$CACHE_ID = SITE_ID."|".$APPLICATION->GetCurPage()."|";

// Cache depends only on preprocessed parameters (without "~")
foreach ($this->arParams as $k => $v)
   if (strncmp("~", $k, 1))
      $CACHE_ID .= ",".$k."=".$v;
$CACHE_ID .= "|".$USER->GetGroups();

$cache = new CPageCache;
if ($cache->StartDataCache($arParams["CACHE_TIME"],
                           $CACHE_ID,
                           "/".SITE_ID.$this->GetRelativePath()))
{
   // Query data and build $arResult
   $arResult = array("a" => 1, "b" => 2);

   // Connect temlpate
   $this->IncludeComponentTemplate();

   $templateCachedData = $this->GetTemplateCachedData();

   $cache->EndDataCache(
      array(
         "arResult" => $arResult,
         "templateCachedData" => $templateCachedData
      )
   );
}
else
{
   extract($cache->GetVars());
   $this->SetTemplateCachedData($templateCachedData);
}
Notes

The cache should depend only on prepared and verified (properly initialised and type cast using IntVal etc.). $arParams contain both prepared and original parameters (prefixed with "~"). If the cache depends on unprepared parameters, hackers get a chance to grow the cache up to the top by calling the page with the ID of "8a", "8b", ... (whose IntVal() is 8).

The method

$this->IncludeComponentTemplate()

does not sends queries to the database. However, you should also call it since it performs some disk operations.

Before calling the caching completion method (EndDataCache), you have to call the template and obtain parameters that should be used even if the cache is valid. In the current implementation, such parameters are CSS styles that are attached by delay functions and do not get into cache. The structure of data returned by template is not documented; it is meaningless to component. It is just data that is to be put into cache, obtained from cache and returned to a template.

To bring data stored in cache (upon the template request) back to a template, call

$this->SetTemplateCachedData($templateCachedData);

This method should be called in the block that is executed if there is a valid cache. When calling the method, pass the template data to it.

© 2001-2007 Bitrix Bitrix Site Manager


Structure of compound components

Complex components are used to create site sections (forum, catalog etc.); they connect simple components to display information. In fact, complex components are controllers that manage simple components. The complex component takes an HTTP request, defines the page to be displayed, and connects the template of this page.

The following code shows an example of a complex component.

<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?><?

$arDefaultUrlTemplates404 = array(
   "list" => "index.php",
   "element" => "#ELEMENT_ID#.php"
);

$arDefaultVariableAliases404 = array();

$arDefaultVariableAliases = array();

$arComponentVariables = array("IBLOCK_ID", "ELEMENT_ID");

$SEF_FOLDER = "";
$arUrlTemplates = array();

if ($arParams["SEF_MODE"] == "Y")
{
   $arVariables = array();

    $arUrlTemplates =
        CComponentEngine::MakeComponentUrlTemplates($arDefaultUrlTemplates404,
                                                    $arParams["SEF_URL_TEMPLATES"]);
    $arVariableAliases =
        CComponentEngine::MakeComponentVariableAliases($arDefaultVariableAliases404,
                                                       $arParams["VARIABLE_ALIASES"]);

   $componentPage = CComponentEngine::ParseComponentPath(
      $arParams["SEF_FOLDER"],
      $arUrlTemplates,
      $arVariables
   );

   if (StrLen($componentPage) <= 0)
      $componentPage = "list";

   CComponentEngine::InitComponentVariables($componentPage,
                                            $arComponentVariables,
                                            $arVariableAliases,
                                            $arVariables);

   $SEF_FOLDER = $arParams["SEF_FOLDER"];
}
else
{
   $arVariables = array();

    $arVariableAliases =
       CComponentEngine::MakeComponentVariableAliases($arDefaultVariableAliases,
                                                      $arParams["VARIABLE_ALIASES"]);
    CComponentEngine::InitComponentVariables(false,
                                             $arComponentVariables,
                                             $arVariableAliases, $arVariables);

   $componentPage = "";
   if (IntVal($arVariables["ELEMENT_ID"]) > 0)
      $componentPage = "element";
   else
      $componentPage = "list";

}

$arResult = array(
   "FOLDER" => $SEF_FOLDER,
   "URL_TEMPLATES" => $arUrlTemplates,
   "VARIABLES" => $arVariables,
   "ALIASES" => $arVariableAliases
);

$this->IncludeComponentTemplate($componentPage);
?>

First of all, the following arrays are defined:

  • $arDefaultUrlTemplates404 - used to define default paths for the human friendly mode. Each entry represent a single template and has the following format:
    "код шаблона пути" => "шаблон пути"
    Path templates can contain macros in the format "#macro#", which are replaced with the values of respective variables when building the path. For example, the following template:
    "element" => "#ELEMENT_ID#.php"
    can be replaced with 195.php or 7453.php. Templates can include parameters:
    "element" => "#IBLOCK_ID#/#ELEMENT_ID#.php?SECTION_ID=#SECTION_ID#"
    You have to provide templates of all paths that can be used by the component.
  • $arDefaultVariableAliases404 - used to define default aliases of variables for use in the human friendly mode. Usually, this array is empty (real names are used). However, if you want to show a variable under a different name in a HTTP request, you can assign an alias to the name, and then restore the real name from the mapped alias.

    The array has the following format:
    "path template ID" => array(
    "variable name 1" => "variable name alias 1",
    "variable name 2" => "variable name alias 2",
    ...
    )
    For example, if you want a link to an information block element (e.g. product details page) to look like the following:
    "/<information block mnemonic code>/.php?SID=<element group ID>"
    you can define the following template:
    "element" => "#IBLOCK_ID#/#ELEMENT_ID#.php?SID=#SECTION_ID#"
    and add the following alias to $arDefaultVariableAliases404:
    "element" => array(
    "SECTION_ID" => "SID"
    )
    In this case, URL's will contain the parameter SID, and the component's variable SECTION_ID will be set appropriately.
  • $arDefaultVariableAliases - used to define default aliases of variables for non-human friendly mode. Usually, this array is empty (real variable names are used). But, if you want to show a variable under a different name in a HTTP request, you can assign an alias to the name, and then restore the real name from the mapped alias.

    The array has the following format:
    "variable name" => "variable alias"
    For example, the following code will map the alias SID to the variable SECTION_ID:
    "SECTION_ID" => "SID"
    In this case, URL's will contain the parameter SID, and the component's variable SECTION_ID will be set appropriately. All these arrays can be redefined using the component input parameters, when the component is called. Consider the following code for the SEF_URL_TEMPLATES parameter in the human friendly mode:
    "SEF_URL_TEMPLATES" => array(
    "element" => "#IBLOCK_CODE#/#ELEMENT_ID#.php?GID=#SECTION_ID#"
    )
    and the input parameter VARIABLE_ALIASES:
    "VARIABLE_ALIASES" => array(
    "element" => array(
    "SECTION_ID" => "GID",
    ),
)
    As a result, the links will be like /phone/3425.php?GID=28, but thу component variables will be set correctly: IBLOCK_CODE = phone, ELEMENT_ID = 3425 and SECTION_ID = 28.
  • $arComponentVariables - used to specify variables that the component can accept in an HTTP request and can have aliases. Each element of the array is the variable name.

The predefined input parameter SEF_MODE can be either Y or N. If $arParams["SEF_MODE"] is Y, the component functions in the human friendly mode, otherwise - not.

The predefined input parameter SEF_FOLDER is effective if only the component is in the human friendly mode. In this case, it contains the component working directory. The path can be virtual (i.e. it may not exist). For example, the above component resides in /fld/n.php and functions in the human friendly mode. Let SEF_FOLDER be /company/news/. In this case, the component will be available at /company/news/index.php, /company/news/25.php etc.

The following Methods are used to determine the correct page to display and to restore the real component variables from aliases.

  • CComponentEngine::MakeComponentUrlTemplates
    array
CComponentEngine::MakeComponentUrlTemplates($arDefaultUrlTemplates404,
                                            $arParams["SEF_URL_TEMPLATES"]);
    The method unions the default path template array and the path templates passed in parameters, into a single array. Path templates in $arParams["SEF_URL_TEMPLATES"] override default path templates.
  • CComponentEngine::MakeComponentVariableAliases
    array
CComponentEngine::MakeComponentVariableAliases($arDefaultVariableAliases404,
                                               $arParams["VARIABLE_ALIASES"]);
    The method unions the default variable alias array and the aliases passed in parameters, into a single array. If an alias exists in both arrays, the alias from $arParams["VARIABLE_ALIASES"] takes precedence.
  • CComponentEngine::ParseComponentPath
    string
CComponentEngine::ParseComponentPath($arParams["SEF_FOLDER"],
                                     $arUrlTemplates, $arVariables);
    The method takes the value of $arParams["SEF_FOLDER"] and an array of path templates returned by MakeComponentUrlTemplates and determines the template that corresponds to the specified address. The method returns the ID if the template was found, or an empty string otherwise. Additionally, $arVariables contains an array of original variables restored form the peth template. For example, consider the following array:
    $arUrlTemplates = array(
    "list" => "index.php",
    "element" => "#IBLOCK_ID#/#ELEMENT_ID#.php?SID=#SECTION_ID#"
);
    If SEF_FOLDER is /company/news/, and the requested URL is /company/news/15/7653.php?SID=28, ParseComponentPath will return "element" (the code of a corresponding template), and $arVariables will contain:
    $arVariables = array(
    "IBLOCK_ID" => 15,
    "ELEMENT_ID" => 7653
)
  • CComponentEngine::InitComponentVariables
    CComponentEngine::InitComponentVariables($componentPage,
                                         $arComponentVariables,
                                         $arVariableAliases,
                                         $arVariables);
    Parameters:
    • $componentPage - the ID of the template returned by ParseComponentPath (to which the requested URL corresponds);
    • $arComponentVariables - an array of variables that the component can accept in an HTTP request an that can have aliases;
    • $arVariableAliases - an array of aliases returned by MakeComponentVariableAliases.

    Restores parameters from $_REQUEST with respect to their possible aliases and returns them in $arVariables. For example, if $arVariableAliases in the code above contains:

    "element" => array(
    "SECTION_ID" => "SID",
)
    InitComponentVariables will return the following array in $arVariables:
    $arVariables = array(
    "IBLOCK_ID" => 15,
    "ELEMENT_ID" => 7653,
    "SECTION_ID" => 28
)
    Here, InitComponentVariables initialized the SECTION_ID element. Other elements were initialized by ParseComponentPath in the example above. If the component is not in the human friendly mode, pass false to InitComponentVariables in the first parameter.

In the human friendly mode, the component takes the path template ID and the HTTP request parameters, and determines the page to be displayed. Then, it passes the page name in the following call:

$this->IncludeComponentTemplate($componentPage);

On its pages, the compound component activates simple components and passes required parameters to them. For example, the "element" page of the sample component template (/templates/.default/list.php) can be he following:

<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>
<?$APPLICATION->IncludeComponent(
   "bitrix:news.detail",
   "",
   Array(
      "IBLOCK_ID" => $arParams["IBLOCK_ID"],
      "ELEMENT_ID" => $arResult["VARIABLES"]["ELEMENT_ID"],
      "SECTION_ID" => $arResult["VARIABLES"]["SECTION_ID"],
      "CACHE_TIME" => $arParams["CACHE_TIME"],
   ),
   $component
);?>

The last parameter ($component) is an object containing the current component. This gives the component a chance to be notified that it is connected from within a compound component, and use the compound component resources etc.

© 2001-2007 Bitrix Bitrix Site Manager


Display templates

There are two kinds of component templates: system and user.

System templates are shipped with the component and reside in the templates subfolder of the component folder.

User templates can be customized according to requirements of a given site. User templates must be stored in site template folders (/bitrix/templates/site template/).

Component templates are identified by their names. The default template has a name of .default. If the name is omitted, the default template is used. Other templates may bear arbitrary names, e.g. table.

Component templates can be files or folders. If a template does not require localization, styles or other resources, it can be stored in a single file. Otherwise, templates should be stored in a folder.

Each component template is an indivisible unit. If a system component template is to be customized, the whole component template must be copied to a site template folder.

For example: the component bitrix:catalog.section.element has a template table located in templates folder of the component folder (/bitrix/components/bitrix/catalog.section.element/templates/). If you customize the template, you will have to copy the table folder to /bitrix/templates/шаблон_сайта/components/bitrix/catalog.section.element/ and then chage it as required.

© 2001-2007 Bitrix Bitrix Site Manager


Simple component template

A simple component template can contain the following files and folders.

  • Subfolder lang contains subfolders with text messages. Subfolder names are the abbreviations of languages in which the text messages are stored. A good practice is to save a text message file under the same name as a corresponding file of the component, and store it in the same folder hierarchy. For example, the file with English messages for /index.php is to be saved in /lang/en/index.php.

    The lang folder is optional if the component does not use language-dependent messages.
  • The file result_modifier.php is included immediately before the inclusion of component template. This file takes the component results as an array $arResult, and the component input array $arParams. This allows to change the contents of $arResult as required. Consider a system component that does everything you need but does not return some important field. A straightforward solution is to develop a custom component. But this approach is time and resource consuming, and the component will not be updated via the Update system. Instead, you can create создать a file result_modifier.php in the component template and add the missing field to $arResult.

    The file result_modifier.php is optional.
  • The file style.css which defines styles required by a given template. Can be used if the component needs custom non-standard styles. style.css is included automatically if it exists. This file is optional.
  • The file script.js contains scripts required by the template; included via <script src=".../script.js" type="text/javascript"></script>. Included automatically if it exists. This file is optional.
  • .description.php contains the template name and description for use in the visual editor. This file is optional.
  • .parameters.php contains the description of input parameters for use in the visual editor. This file is optional.
  • The file template.ext is the main file; it contains the template code. The extension ext depends on the templating language in which the template is written. php is the default extension. This file is required.
  • Any other files and folders with resources required by the component.
© 2001-2007 Bitrix Bitrix Site Manager


Compound component template

A compound component template can contain the following files and folders.

  • Subfolder lang contains subfolders with text messages. Subfolder names are the abbreviations of languages in which the text messages are stored. A good practice is to save a text message file under the same name as a corresponding file of the component, and store it in the same folder hierarchy. For example, the file with English messages for /section.php is to be saved in /lang/en/section.php.

    The lang folder is optional if the component does not use language-dependent messages.
  • The file result_modifier.php is included immediately before the inclusion of component template. This file takes the component results as an array $arResult, and the component input array $arParams. This allows to change the contents of $arResult as required.
  • The file style.css which defines styles required by a given template. Can be used if the component needs custom non-standard styles. style.css is included automatically if it exists. This file is optional.
  • The file script.js contains scripts required by the template;
  included via <script src=".../script.js"
  type="text/javascript"></script>. Included automatically if it
  exists. This file is optional.
  • .description.php contains the template name and description for use in the visual editor. This file is optional.
  • .parameters.php contains the description of input parameters for use in the visual editor. This file is optional.
  • Files name.ext which are templates of the compound component pages. extension ext depends on the templating language in which the template is written. php is the default extension. Each page must have a corresponding file name.ext.
  • Templates of simple components that are members of the compound one. These templates should reside in folders /namespace/simple component name/ relative to the component folder.
  • Any other files and folders with resources required by the component.

Simple components that belong to compound components are activated in page teampltes of a compound component.

© 2001-2007 Bitrix Bitrix Site Manager


Result modifier: result_modifier.php

If the template folder contains the file result_modifier.php, this file is called before the template is included. This file allows to modify the component output.

In result_modifier.php you can add the required information to $arResult. This allows to avoid component customization.

Or, in result_modifier.php you can reformat the component output in $arResult for easier use in a template.

© 2001-2007 Bitrix Bitrix Site Manager


Component template look-up

To search for an appropriate component template, the system user the following search order.

  1. In /bitrix/templates/current site template/components/. First, the system checks the subfolder /пространство_имен_компонента/название_компонента/ for a file or folder with the template name. If not found, the system searches for file template_name.ext, enumerating all installed templating engines on ext.
  2. If not found, the folder /bitrix/templates/.default/components/ is searched using the same algorithm as in step 1.
  3. If not found, the system searches all system templates.

If the template name is not specified, the .default template is used.

If the required template is specified as a folder name, the system searches for file template.ext for simple components, and page_name.ext - for compound components. The default ext is "php"; if no file with this extension is found, the system enumerates all installed templating engines on ext.

For example: the component bitrix:catalog.list is to be displayed using the table template. Assume that the Smarty template engine is available on the server (*.tpl). First the system will check /bitrix/templates/current site template/components/bitrix/catalog.list/ for fiel or folder named table. If no such found, the system will search the specified folder for files table.php or table.tpl. If nothing appeared to be found again, the system will check folders /bitrix/templates/.default/components/bitrix/catalog.list/ and /bitrix/components/bitrix/catalog.list/templates/.

If the component folder is found, the system will first search for template.php, and, if template.php was not found, template.tpl. If the template is specified as «table/template.php», the file matches.

if a simple component is called as a part of a compound component, a template of a simple component is first looked up in the compound component folder, and then, if not found, in own templates.

© 2001-2007 Bitrix Bitrix Site Manager


Custom template engines

Components can function with any template engine that can be plugged in PHP. To define a new template engine, create or edit the global variable $arCustomTemplateEngines in /bitrix/php_interface/init.php. This variable contains an associated array having the following format:

"template engine ID" => array(
    "templateExt" => array("ext1"[, "ext2"...]),
    "function" => "engine control function"
    )

Here:

  • "template engine ID" - an arbitrary unique name;
  • "extN" - file extension associated with the engine;
  • "engine control function" - the name of the function that will be called if a component template extension is extN. You can create the function in this file (/bitrix/php_interface/init.php).

For example, if you want to use Smarty on your site, add the following lines to /bitrix/php_interface/init.php:

global $arCustomTemplateEngines;
$arCustomTemplateEngines = array(
    "smarty" => array(
        "templateExt" => array("tpl"),
        "function" => "SmartyEngine"
    ),
);

This will cause templates with extension tpl to be run using the SmartyEngine function, which will run Smarty.

Template engine control function

function
EngineControlFunction($templateFile,
                      $arResult,
                      $arParams,
                      $arLangMessages,
                      $templateFolder,
                      $parentTemplateFolder,
                      $template)
Here:
  • $templateFile – path to the template relative to the site root;
  • $arResult – a component result output array;
  • $arParams – a component input array;
  • $arLangMessages – language-dependent messages (array);
  • $templateFolder – path to the template folder relative to the site root (can be empty if the template does not occupy a separate folder);
  • $parentTemplateFolder - path to the template folder of a parent compound component, relative to the site root (can be empty if a simple component is plugged alone);
  • $template – template object.

The engine control function depends on the engine.

Example: adding Smarty engine

Add the following lines to /bitrix/php_interface/init.php:

global $arCustomTemplateEngines;
$arCustomTemplateEngines = array(
    "smarty" => array(
        "templateExt" => array("tpl"),
        "function" => "SmartyEngine"
    )
);

function SmartyEngine($templateFile,
                      $arResult,
                      $arParams,
                      $arLangMessages,
                      $templateFolder,
                      $parentTemplateFolder,
                      $template)
{
    if (!defined("SMARTY_DIR"))
        define("SMARTY_DIR", "<absolute path to Smarty>/libs/");

    require_once('<absolute path to Smarty>/libs/Smarty.class.php');

    $smarty = new Smarty;

    $smarty->compile_dir = "<absolute path to Smarty>/templates_c/";
    $smarty->config_dir = "<absolute path to Smarty>/configs/";
    $smarty->template_dir = "<absolute path to Smarty>/templates/";
    $smarty->cache_dir = "<absolute path to Smarty>/cache/";

    $smarty->compile_check = true;
    $smarty->debugging = false;

    $smarty->assign("arResult", $arResult);
    $smarty->assign("arParams", $arParams);
    $smarty->assign("MESS", $arLangMessages);
    $smarty->assign("templateFolder", $templateFolder);
    $smarty->assign("parentTemplateFolder", $parentTemplateFolder);

    $smarty->display($_SERVER["DOCUMENT_ROOT"].$templateFile);
}

Replace "<absolute path to Smarty>" with the absolute path to the Smarty installation folder. You will find more information on installation and using Smarty in its help section.

The array $arCustomTemplateEngines registers Smarty. The function SmartyEngine initializes its parameters according to Smarty requirements. Then, variables with component's output, input parameters, language messages etc. are passed to Smarty. Finally, Smarty is run and the output is displayed.

This simple example emphasizes on template engine connection. For real site, it can be modified according to requirements, you can use Smarty's filters etc. For example, to avoid creating Smarty instance every time a template is activated, you can use the following code:

global $smarty;
$smarty = null;

function SmartyEngine($templateFile,
                      $arResult,
                      $arParams,
                      $arLangMessages,
                      $templateFolder,
                      $parentTemplateFolder,
                      $template)
{
    if (!defined("SMARTY_DIR"))
        define("SMARTY_DIR", "<absolute path to Smarty>/libs/");

    global $smarty;
    if (!isset($smarty) || !is_object($smarty))
    {
        require_once('<absolute path to Smarty>/libs/Smarty.class.php');

        $smarty = new Smarty;

        $smarty->compile_dir = "<absolute path to Smarty>/templates_c/";
        $smarty->config_dir = "<absolute path to Smarty>/configs/";
        $smarty->template_dir = "<absolute path to Smarty>/templates/";
        $smarty->cache_dir = "<absolute path to Smarty>/cache/";

        $smarty->compile_check = true;
        $smarty->debugging = false;
    }
    else
    {
        $smarty->clear_all_assign();
    }

    $smarty->assign("arResult", $arResult);
    $smarty->assign("arParams", $arParams);
    $smarty->assign("MESS", $arLangMessages);
    $smarty->assign("templateFolder", $templateFolder);
    $smarty->assign("parentTemplateFolder", $parentTemplateFolder);

    $smarty->display($_SERVER["DOCUMENT_ROOT"].$templateFile);
}

Example: plugging in a XML/XSLT engine

global $arCustomTemplateEngines;
$arCustomTemplateEngines = array(
    "xslt" => array(
        "templateExt" => array("xsl"),
        "function" => "XSLTEngine"
    ),
);

function CreateXMLFromArray($xDoc, $xNode, $ar)
{
    foreach($ar as $key=>$val)
    {
        if(!is_string($key) || strlen($key)<=0)
            $key = "value";

        $xElement = $xDoc->createElement($key);
        if(is_array($val))
        {
            CreateXMLFromArray($xDoc, $xElement, $val);
        }
        else
        {
            $xElement->appendChild($xDoc->createTextNode(iconv(SITE_CHARSET, "utf-8", $val)));
        }
        $xNode->appendChild($xElement);
    }
    return $xNode;
}

function XSLTEngine($templateFile,
                    $arResult,
                    $arParams,
                    $arLangMessages,
                    $templateFolder,
                    $parentTemplateFolder,
                    $template)
{
    $arResult["PARAMS"] = array(
        "templateFolder" => $templateFolder,
        "parentTemplateFolder" => $parentTemplateFolder,
        "arParams" => $arParams,
        "arLangMessages" => $arLangMessages
    );

    $xDoc = new DOMDocument("1.0", SITE_CHARSET);
    $xRoot = $xDoc->createElement('result');
    CreateXMLFromArray($xDoc, $xRoot, $arResult);
    $xDoc->appendChild($xRoot);

    $xXsl = new DOMDocument();
    $xXsl->load($_SERVER["DOCUMENT_ROOT"].$templateFile);

    $xProc = new XSLTProcessor;
    $xProc->importStyleSheet($xXsl);

    echo $xProc->transformToXML($xDoc);
}
© 2001-2007 Bitrix Bitrix Site Manager


Human friendly URL's

Compound components is capable of generating search engine friendly URL's.

Each compound component has an input parameter SEF_MODE, which can be Y or N.

If SEF_MODE is N, the component handles physical links and passes all parameters via an HTTP request. For example:

/fld/cat.php?IBLOCK_ID=12&SECTION_ID=371

If SEF_MODE is Y, the component generates and handles links using templates. For example, the following link is valid:

/catalog/section/371.php?IBLOCK_ID=12

even if the component resides in /fld/cat.php.

If SEF_MODE is Y, another parameter SEF_FOLDER must be passed to the component. This parameter contains path to the folder in which the component runs. This path can be the same as the physical path, or it can be different. For example: a component «bitrix:catalog» activated in /fld/cat.php can have the parameters SEF_MODE = Y and SEF_FOLDER=/catalog/. In this case, the component will respond to requests containing /catalog/.... By default, the editor should provide the current physical path to a file being edited.

A compound component that functions in SEF mode must be provided with a set of default path templates. For example, the following array can be defined for the compound component «bitrix:catalog»:

$arDefaultUrlTemplatesSEF = array(
    "list" => "index.php",
    "section" => "section.php?IBLOCK_ID=#IBLOCK_ID#&SECTION_ID=#SECTION_ID#",
    "element" => "element.php?ELEMENT_ID=#ELEMENT_ID#"
);

These path templates can be redefined using the input parameter SEF_URL_TEMPLATES, which contains an array of all path templates or their portions.

When saving a page containing SEF component, the editor creates or updates a urlrewrite record. For example, when saving /fld/cat.php containing the «bitrix:catalog» component set to work in SEF mode with SEF_FOLDER=/catalog/, the urlrewrite system creates or updates a record similar to:

array(
    "CONDITION" => "#^/catalog/#",
    "ID" => "bitrix:catalog",
    "PATH" => "/fld/cat.php"
),

Here, CONDITION contains a value of SEF_FOLDER enclosed in «#^» and «#»; ID contains the component name, and PATH contains physical path to the file being saved. If a record with the specified PATH and ID already exists, it is updated; otherwise, a new record is created.

At run time, when a non-existing page is requested, urlrewrite searches for an appropriate record by CONDITION and passes control to a page specified in PATH.

The component running on a page to which PATH points finds the requested page and restores variables from the path.

Attention!

The mandatory requirement for the component path template array is the uniqueness of each path template (without parameters and variables). This requirement must be verified each time a page is saved in the visual editor. For example, the following path templates:

"section" => "section/#SECTION_ID#.php?IBLOCK_ID=#IBLOCK_ID#",
"element" => "element/#ELEMENT_ID#.php"
are valid, but this array:

"section" => "#SECTION_ID#.php?IBLOCK_ID=#IBLOCK_ID#",
"element" => "#ELEMENT_ID#.php"
is invalid.
© 2001-2007 Bitrix Bitrix Site Manager


Input parameter aliases

Each component has a set of variables in which it takes ID's or other attributes of requested information. For example, the component bitrix:catalog.section has variables IBLOCK_ID and SECTION_ID, in which it takes ID's of a catalog and a product group, respectively.

All components that belong to a compound component must have a uniform set of variables. For example, the compound component bitrix:catalog and its simple components (bitrix:catalog.list, bitrix:catalog.section etc.) can handle variables IBLOCK_ID, SECTION_ID, ELEMENT_ID etc.

If, when adding a component to a page, you want to redefine its variables, you have to provide the VARIABLE_ALIASES parameter.

In SEF mode, this parameter has the following format:

"VARIABLE_ALIASES" => array(
    "list" => array(),
    "section" => array(
        "IBLOCK_ID" => "BID",
        "SECTION_ID" => "ID"
    ),
    "element" => array(
        "SECTION_ID" => "SID",
        "ELEMENT_ID" => "ID"
    ),
)

Here, array keys are the same as keys of the path template array. An individual set of definitions can exist for each path.

In non-SEF mode, this parameter has the following format:

"VARIABLE_ALIASES" => array(
    "IBLOCK_ID" => "BID",
    "SECTION_ID" => "GID",
    "ELEMENT_ID" => "ID",
)

Example 1

Let us make the component bitrix:catalog that resides in /fld/cat.php work with the following paths:

/catalog/index.php (for a list of catalogs)
/catalog/section/код_группы.php?ID=код_каталога (for product group)
/catalog/product/код_товара.php?ID=код_группы (for product details)

The following parameters have to be specified in the input parameters:

"SEF_MODE" => "Y",
"SEF_FOLDER" => "/catalog/",
"SEF_URL_TEMPLATES" => array(
    "list" => "index.php",
    "section" => "section/#SECTION_ID#.php?ID=#IBLOCK_ID#",
    "element" => "element/#ELEMENT_ID#.php?ID=#SECTION_ID#"
),
"VARIABLE_ALIASES" => array(
    "list" => array(),
    "section" => array(
        "IBLOCK_ID" => "ID"
    ),
    "element" => array(
        "SECTION_ID" => "ID",
    ),
)

Example 2

Make the component bitrix:catalog that resides in /fld/cat.php work with the following paths:

/fld/cat.php (для списка каталогов)
/fld/cat.php?BID=код_каталога&SID=код_группы (для группы товаров)
/fld/cat.php?ID=код_товара&SID=код_группы (для детальной информации о товаре)

The following parameters have to be specified in the input parameters:

"SEF_MODE" => "N",
"VARIABLE_ALIASES" => array(
    "IBLOCK_ID" => "BID",
    "SECTION_ID" => "SID",
    "ELEMENT_ID" => "ID",
)
© 2001-2007 Bitrix Bitrix Site Manager


HTTP POST requests

If your site handles error pages using the ErrorDocument option (ErrorDocument 404 /404.php), sending an HTTP POST request to an error page will lose request parameters. Therefore, such requests have to be processed using scripts that exist physically.

One of the methods to handle SEF URL's using Components 2.0 allows using the ErrorDocument option. Components 2.0 offer a unified solution that will eliminate the need to care about how SEF is done: via ErrorDocument or mod_rewrite.

When creating forms in component templates that send data using POST, set the action attribute to POST_FORM_ACTION_URI:

<form method="post" action="<?=POST_FORM_ACTION_URI?>">
    * * *
</form>

In this case, a POST request will be sent to an existing script when using ErrorDocument, or to the current address in other cases. The most convenient thing is that no matter how a component is called: via POST or GET request. All the required variables will be set properly.

© 2001-2007 Bitrix Bitrix Site Manager


Creating a Control Panel section

This chapter describes how to create a developer defined section in Control Panel. As an example, we shall create a custom subsection in the Subscription section.

  • Creating a list of elements: step-by-step demonstration of creating a Control Panel page containing a list of elements;
  • Creating an editing page - step-by-step demonstration of creating a Control Panel page containing an element editing form.

Also, we shall study the creation of custom tab handlers for element editing form, and customization of the module Control Panel menu.

© 2001-2008 Bitrix Bitrix Site Manager


Managing module menus in Control Panel

This section describes how to manage the Control Panel menus.

Main structure

For each module, the menu parameters are specified in the file: /bitrix/module_catalogue/admin/menu.php. This file should create the module menu description array. API allows to create a tree menu of an arbitrary nesting level. The tree nodes and branches can be created dynamically.

The menu.php file returns an associated array of the following structure:

Key | Description
parent_menu Menu section identifier. This key is meaningful only for the upper level of the module menu tree. Can be one of the following values.
  • global_menu_content - the Content section;
  • global_menu_services - the Services section;
  • global_menu_store - the Store section;
  • global_menu_statistics - the Web Analytics section;
  • global_menu_settings - the Settings section.
sort | The relative weight of a menu item (for sorting).
url | A menu item link. When a visitor opens this URL, the corresponding menu item will be highlighted.
more_url | A list of additional URL that will cause the corresponding menu item to be highlighted.
text | A menu item link text.
title | A menu item tooltip text.
icon | The CSS class of the menu item icon.
page_icon | The CSS class of the menu item icon that is displayed on the index page (larger image).
module_id | The module identifier to which the menu belongs.
dynamic | Specifies whether the branch starting with the current item is to be created dynamically.
items_id | The menu node identifier. Used for dynamically created branches.
items | A list of child menu items in the form of an array. Each element is an associated array of similar structure.

Example

The menu.php file for the Web Form module (simple static menu).

<?
IncludeModuleLangFile(__FILE__); // in menu.php, language files can be used as well

if($APPLICATION->GetGroupRight("form")>"D") // check the Web Form module access level
{
  // build the upper menu item
  $aMenu = array(
    "parent_menu" => "global_menu_services", // put it into the Service section
    "sort"        => 100,                    // the menu item weight
    "url"         => "form_list.php?lang=".LANGUAGE_ID,  // the menu item link
    "text"        => GetMessage("FORM_MENU_MAIN"),       // the menu item text
    "title"       => GetMessage("FORM_MENU_MAIN_TITLE"), // the tooltip text
    "icon"        => "form_menu_icon", // the small icon
    "page_icon"   => "form_page_icon", // the large icon
    "items_id"    => "menu_webforms",  // the node identifier
    "items"       => array(),          // other menu levels will be built below.
  );

  // now obtain the list of web forms and
  // add corresponding menu items for each of them
  require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
  $z = CForm::GetMenuList(array("LID"=>LANGUAGE_ID));
  while ($zr=$z->GetNext())
  {
    if (strlen($zr["MENU"]) > 0)
    {
      // array of each item is built similarly
      $aMenu["items"][] =  array(
        "text" => $zr["MENU"],
        "url"  => "form_result_list.php?lang=".LANGUAGE_ID."&WEB_FORM_ID=".$zr["ID"],
        "icon" => "form_menu_icon",
        "page_icon" => "form_page_icon",
        "more_url"  => array(
            "form_view.php?WEB_FORM_ID=".$zr["ID"],
            "form_result_list.php?WEB_FORM_ID=".$zr["ID"],
            "form_result_edit.php?WEB_FORM_ID=".$zr["ID"],
            "form_result_print.php?WEB_FORM_ID=".$zr["ID"],
            "form_result_view.php?WEB_FORM_ID=".$zr["ID"]
            ),
        "title" => GetMessage("FORM_RESULTS_ALT")
       );
    }
  }

  // if more more items are required,
  // add elements to $aMenu["items"]
  // ............

  // return the obtained list
  return $aMenu;
}
// return false if access is denied
return false;
?>

Dynamic creation of menu nodes and branches

As it has been already mentioned, th system allows to build menus with dynamically created nodes and branches. For this, the following steps are required:

  1. set "dynamic" to true for nodes requiring dynamic items;
  2. specify the "items_id" parameter and the module ID for nodes requiring dynamic items;
  3. check the "expanded" state when creating child items of a dynamic node.

The last step implies calling CAdminMenu::IsSectionActive(). Since the menu building script runs in the context of the CAdminMenu class instance, it is sufficient to assert $this->IsSectionActive() specifying the value of the "items_id" parameter of a required branch.

The below is an example of the same Web Form module menu whose list of forms is created dynamically.

<?
// in menu.php, language files can be used as well
IncludeModuleLangFile(__FILE__);

// check the Web Form module access level
if($APPLICATION->GetGroupRight("form")>"D")
{
  // leave the upper menu item untouched
  $aMenu = array(
    "parent_menu" => "global_menu_services", // put it into the Service section
    "sort"        => 100,                    // the menu item weight
    "url"         => "form_list.php?lang=".LANGUAGE_ID,  // the menu item link
    "text"        => GetMessage("FORM_MENU_MAIN"),       // the menu item text
    "title"       => GetMessage("FORM_MENU_MAIN_TITLE"), // the tooltip text
    "icon"        => "form_menu_icon", // the small icon
    "page_icon"   => "form_page_icon", // the large icon
    "items_id"    => "menu_webforms",  // the node identifier
    "items"       => array(),          // build the other menu levels below.
  );

  // build the menu items that will be loaded dynamically
  $arFormsList = array();
  if (
    // compatibility check
    method_exists($this, "IsSectionActive")
    &&
    // if a menu section "menu_webforms_list" is active
    $this->IsSectionActive("menu_webforms_list")
    ||
    // you can also add your own conditions.
    // For example, display this node on all pages
    // where the FORM_MENU_OPEN constant is set to 1
    defined('FORM_MENU_OPEN') && FORM_MENU_OPEN == 1)
  {

    // now perform the same operation but store elements in a separate array
    require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
    $z = CForm::GetMenuList(array("LID"=>LANGUAGE_ID));
    while ($zr=$z->GetNext())
    {
      if (strlen($zr["MENU"]) > 0)
      {
        // array of each item is built similarly
        $arFormsList[] =  array(
          "text" => $zr["MENU"],
          "url"  => "form_result_list.php?lang=".LANGUAGE_ID."&WEB_FORM_ID=".$zr["ID"],
          "icon" => "form_menu_icon",
          "page_icon" => "form_page_icon",
          "more_url"  => array(
              "form_view.php?WEB_FORM_ID=".$zr["ID"],
              "form_result_list.php?WEB_FORM_ID=".$zr["ID"],
              "form_result_edit.php?WEB_FORM_ID=".$zr["ID"],
              "form_result_print.php?WEB_FORM_ID=".$zr["ID"],
              "form_result_view.php?WEB_FORM_ID=".$zr["ID"]
              ),
          "title" => GetMessage("FORM_RESULTS_ALT")
         );
      }
    }
  }

  // now build the root of the dynamic menu branch.
  // pay attention to the highlighted parameters.

  $aMenu["items"][] = array(
    "text" => GetMessage("FORM_RESULTS_ALL"),
    "url" => "form_result_list.php?lang=".LANGUAGE_ID,
    "title" => GetMessage("FORM_RESULTS_ALL_ALT"),

    "dynamic" => true,                  // !!!!!!!!!!!!!!!!!!!!!!!!!
    "module_id" => "form",              // !!!!!!!!!!!!!!!!!!!!!!!!!
    "items_id" => "menu_webforms_list", // !!!!!!!!!!!!!!!!!!!!!!!!!
    "items" => $arFormsList,            // !!!!!!!!!!!!!!!!!!!!!!!!!

  );

  // if you want to add more items,
  // add elements to $aMenu["items"]
  // ............

  // return the obtained list
  return $aMenu;
}
// return false if access is denied
return false;
?>
© 2001-2008 Bitrix Bitrix Site Manager


Creating a custom list of elements

You can view a working example of a Control Panel page with a custom list here: Example: creating a custom list of elements.

Basic principles

Generally, a Control Panel page displaying a list of elements requires the implementation of the following functions:

  • protection against unauthorized access;
  • obtaining a paginated list of elements;
  • ability to sort the list by any column;
  • ability to perform group and single actions on list elements;
  • perform the required actions on list elements.

The Control Panel page creation API allows to perform these functions independently. For example, a list can be built in such a way that it can be updated and navigated using AJAX without having to update the whole page.

Let us see how a Control Panel page with a list of elements can be created. Use the Subscription/Newsletter module page as example.

Prolog

Before we start the page output, we have to perform some preliminary steps. Create a file /bitrix/modules/subscribe/rubric_admin.php and add the following code to it:

<?
// include all necessary files:
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");
// the first common prologue

// initialise the module

require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/include.php");

// a module proloque
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/prolog.php");

// include a language file
IncludeModuleLangFile(__FILE__);

// obtain the current user module access level to the
$POST_RIGHT = $APPLICATION->GetGroupRight("subscribe");
// if access is denied, direct the visitor to the authorization form
if ($POST_RIGHT == "D")
    $APPLICATION->AuthForm(GetMessage("ACCESS_DENIED"));
?>

<?
// prepare all the data here
?>
<?
// the second common prologue
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");
?>
<?
// display the page here
?>
<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin.php");?>

Now we have the page body indicated on the figure above.

Now create a language file, for example: /bitrix/modules/subscribe/lang/ru/rubric_admin.php for French. In this file, create all language messages as the array elements: $MESS['message_identifier'] = "message_text";.

Since the /bitrix/modules/ catalog is not accessible via HTTP as has been set by the BSM installation, create a file /bitrix/admin/rubric_admin.php:

<?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/admin/rubric_admin.php");
?>

Now this file is available at: http://mysite.ru/bitrix/admin/rubric_admin.php.

Page functions

As shown on the figure above, all page functions can be conditionally divided into several components.

  • Processing and preparing data
    • create instances required for class operation;
    • process actions on list elements;
    • configure and process filter of element list;
    • select list elements from database and prepare them for display;
    • specify table parameters (including sorting).
  • Data display
    • configure and display a Control Panel menu;
    • display filter;
    • display list.

For this, we need instances of the following classes.

Class | Description
CAdminList | The main class used with the Control Panel element lists.
CAdminResult | The CDBResult class extension used with element lists in the Control Panel scripts.
CAdminSorting | Used for list sorting.
CAdminFilter | Used for list filtering.
Data handling

First, create instances of the CAdminList and CAdminSorting classes:

$sTableID = "tbl_rubric"; // table ID
$oSort = new CAdminSorting($sTableID, "ID", "desc"); // object to sort
$lAdmin = new CAdminList($sTableID, $oSort); // main object of the list
Result filter

In the example below, the result filter includes of the following parameters:

  • search by the mail list ID;
  • by the active mail list active state flag;
  • by the completion status.

The preparatory actions can be as follows:

// move filter validation to a separate function
function CheckFilter()
{
    global $FilterArr, $lAdmin;
    foreach ($FilterArr as $f) global $$f;

    /*
    check values of $find_name variables and if an error occurs,
    call $lAdmin->AddFilterError("error_text").
    */

    // return false on error

    return count($lAdmin->arFilterErrors) == 0;
}

// describe filter elements
$FilterArr = Array(

    "find_id",

    "find_lid",

    "find_active",

    "find_visible",

    "find_auto",

    );

// initialise the filter
$lAdmin->InitFilter($FilterArr);

// if all filter values are correct, process the filter
if (CheckFilter())
{

    // create a filter array for CRubric::GetList()

    // using the filter values
    $arFilter = Array(

            "ID"        => $find_id,
            "LID"       => $find_lid,
            "ACTIVE"    => $find_active,
            "VISIBLE"   => $find_visible,
            "AUTO"      => $find_auto,
    );
}
Handling actions on elements

The following actions are possible with elements:

  • editing elements on the list page;
  • group and single actions with elements.

To verify that an action was performed on a list element, you can call CAdminList::EditAction or CAdminList::GroupAction. Don't forget to check permissions in both cases (here, check the write access permission for the Subscription module - $POST_RIGHT=="W").

Example:

// save modified elements
if($lAdmin->EditAction() && $POST_RIGHT=="W")
{
    // check the list of passed elements
    foreach($FIELDS as $ID=>$arFields)
    {
        if(!$lAdmin->IsUpdated($ID))
            continue;

        // save changes for each element
        $DB->StartTransaction();
        $ID = IntVal($ID);
        $cData = new CRubric;
        if(($rsData = $cData->GetByID($ID)) && ($arData = $rsData->Fetch()))
        {
            foreach($arFields as $key=>$value)
                $arData[$key]=$value;
            if(!$cData->Update($ID, $arData))
            {
                $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".$cData->LAST_ERROR, $ID);
                $DB->Rollback();
            }
        }
        else
        {
            $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".GetMessage("rub_no_rubric"), $ID);
            $DB->Rollback();
        }
        $DB->Commit();
    }
}

// process single and group actions
if(($arID = $lAdmin->GroupAction()) && $POST_RIGHT=="W")
{
    // if "For all elements" is selected
    if($_REQUEST['action_target']=='selected')
    {
        $cData = new CRubric;
        $rsData = $cData->GetList(array($by=>$order), $arFilter);
        while($arRes = $rsData->Fetch())
            $arID[] = $arRes['ID'];
    }

    // walk the list of elements
    foreach($arID as $ID)
    {
        if(strlen($ID)<=0)
            continue;
           $ID = IntVal($ID);

        // perform the required action for each element
        switch($_REQUEST['action'])
        {
        // delete
        case "delete":
            @set_time_limit(0);
            $DB->StartTransaction();
            if(!CRubric::Delete($ID))
            {
                $DB->Rollback();
                $lAdmin->AddGroupError(GetMessage("rub_del_err"), $ID);
            }
            $DB->Commit();
            break;

        // activate or deactivate
        case "activate":
        case "deactivate":
            $cData = new CRubric;
            if(($rsData = $cData->GetByID($ID)) && ($arFields = $rsData->Fetch()))
            {
                $arFields["ACTIVE"]=($_REQUEST['action']=="activate"?"Y":"N");
                if(!$cData->Update($ID, $arFields))
                    $lAdmin->AddGroupError(GetMessage("rub_save_error").$cData->LAST_ERROR, $ID);
            }
            else
                $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".GetMessage("rub_no_rubric"), $ID);
            break;
        }

    }
}
Selection of elements

The process of selection of elements is similar to that in a component or page except that an instance of the CAdminResult class needs to be created from the selection.

// select the list of mail lists
$cData = new CRubric;
$rsData = $cData->GetList(array($by=>$order), $arFilter);

// transform the list into an instance of the CAdminResult class
$rsData = new CAdminResult($rsData, $sTableID);

// initialise pagewise navigation similar to CDBResult.
$rsData->NavStart();

// emit the navigation code to $lAdmin
$lAdmin->NavText($rsData->GetNavPrint(GetMessage("rub_nav")));
Prepare elements for output

In order to build a table of elements, we have to create an array of table headers; and then send the list of elements to $lAdmin.The first action is performed by calling CAdminList::AddHeaders passing an array of table columns to it. Each column is described by an array, containing the following keys:

Key | Description
id | The column identifier.
content | The column header.
sort | The value of the GET request parameter for sorting.
default | Specifies if a column is displayed in the list by default (true|false).

Example:

$lAdmin->AddHeaders(array(
  array(  "id"    =>"ID",
    "content"  =>"ID",
    "sort"     =>"id",
    "default"  =>true,
  ),
  array(  "id"    =>"NAME",
    "content"  =>GetMessage("rub_name"),
    "sort"     =>"name",
    "default"  =>true,
  ),
  array(  "id"    =>"LID",
    "content"  =>GetMessage("rub_site"),
    "sort"     =>"lid",
    "default"  =>true,
  ),
  array(  "id"    =>"SORT",
    "content"  =>GetMessage("rub_sort"),
    "sort"     =>"sort",
    "align"    =>"right",
    "default"  =>true,
  ),
  array(  "id"    =>"ACTIVE",
    "content"  =>GetMessage("rub_act"),
    "sort"     =>"act",
    "default"  =>true,
  ),
  array(  "id"    =>"VISIBLE",
    "content"  =>GetMessage("rub_visible"),
    "sort"     =>"visible",
    "default"  =>true,
  ),
  array(  "id"    =>"AUTO",
    "content"  =>GetMessage("rub_auto"),
    "sort"     =>"auto",
    "default"  =>true,
  ),
  array(  "id"    =>"LAST_EXECUTED",
    "content"  =>GetMessage("rub_last_exec"),
    "sort"     =>"last_executed",
    "default"  =>true,
  ),
));

The list of elements is passed to the main object in the following way:

  1. Call CAdminList::AddRow(). This method returns a reference to an empty instance of CAdminListRow.
  2. Create the fields using the following methods of CAdminListRow:
    • AddField - the cell value is displayed as specified when reading and editing the list;
    • AddViewField - specifies the field format for viewing;
    • AddEditField - specifies the field format for editing;
    • AddCheckField - the value is rendered and edited as a checkbox;
    • AddSelectField - the value is edited as a drop down list;
    • AddInputField - the value is edited in a text area field;
    • AddCalendarField - the value is edited as a date input field.
  3. Create the context menu for the row (CAdminListRow::AddActions)

You can combine different methods when creating a row field.

The element context menu is specified as an array whose elements are associated arrays with the following keys:

Key | Description
ICON | The CSS class name with an action button.
DISABLED | Specifies whether the menu item is disabled or not (true|false).
DEFAULT | Specifies whether the menu item is a default action (true|false). Double clicking the row activates the default action.
TEXT | The menu item title.
TITLE | The menu item tooltip.
ACTION | The action to be performed performed when the menu item is activated (Javascript).
SEPARATOR | Inserts a separator {true|false}. If true, all other keys will be ignored.

Example:

while($arRes = $rsData->NavNext(true, "f_")):

  // create a row. the result is a CAdminListRow class instance
  $row =& $lAdmin->AddRow($f_ID, $arRes);

  // now configure the value display format
  // for viewing and editing

  // the NAME parameter will be edited as a text and displayed as a link
  $row->AddInputField("NAME", array("size"=>20));
  $row->AddViewField("NAME", '<a href="rubric_edit.php?ID='.$f_ID.'&lang='.LANG.'">'.$f_NAME.'</a>');

  // the LID parameter will be edited as a drop down list of languages
  $row->AddEditField("LID", CLang::SelectBox("LID", $f_LID));

  // the SORT parameter will be edited as a text
  $row->AddInputField("SORT", array("size"=>20));

  // the ACTIVE and VISIBLE flags will be edited as checkboxes
  $row->AddCheckField("ACTIVE");
  $row->AddCheckField("VISIBLE");

  // the AUTO parameter will be displayed as "Yes" or "No" in bold when edited
  $row->AddViewField("AUTO", $f_AUTO=="Y"?GetMessage("POST_U_YES"):GetMessage("POST_U_NO"));
  $row->AddEditField("AUTO", "<b>".($f_AUTO=="Y"?GetMessage("POST_U_YES"):GetMessage("POST_U_NO"))."</b>");

  // create the context menu
  $arActions = Array();

  // element editing
  $arActions[] = array(
    "ICON"=>"edit",
    "DEFAULT"=>true,
    "TEXT"=>GetMessage("rub_edit"),
    "ACTION"=>$lAdmin->ActionRedirect("rubric_edit.php?ID=".$f_ID)
  );

  // element deletion
  if ($POST_RIGHT>="W")
    $arActions[] = array(
      "ICON"=>"delete",
      "TEXT"=>GetMessage("rub_del"),
      "ACTION"=>"if(confirm('".GetMessage('rub_del_conf')."')) ".$lAdmin->ActionDoGroup($f_ID, "delete")
    );

  // insert a separator
  $arActions[] = array("SEPARATOR"=>true);

  // check the automated mail list template
  if (strlen($f_TEMPLATE)>0 && $f_AUTO=="Y")
    $arActions[] = array(
      "ICON"=>"",
      "TEXT"=>GetMessage("rub_check"),
      "ACTION"=>$lAdmin->ActionRedirect("template_test.php?ID=".$f_ID)
    );

  // if the last item is separator, remove it.
  if(is_set($arActions[count($arActions)-1], "SEPARATOR"))
    unset($arActions[count($arActions)-1]);

  // apply the context menu to the row
  $row->AddActions($arActions);

endwhile;

Now we have to add a table footer and assign group actions to elements to complete the table preparation.

The table resume is formed as an array whose elements are associated arrays with the following keys:

"title" - parameter name;
"value" - parameter value.

Additionally, the associated array may contain an entry "counter" set to true, which makes the element a table row selection counter. The value of "counter" will change dynamically whenever a user selects or deselects table rows.

A footer can be attached by calling CAdminList::AddFooter.

A list of possible group actions is specified as an array of elements in the format:

"action_identifier" => "action_name"

It can be attached to the table by calling CAdminList::AddGroupActionTable. Processing group actions is discussed above.

Example:

// table footer
$lAdmin->AddFooter(
  array(
          // element count
    array("title"=>GetMessage("MAIN_ADMIN_LIST_SELECTED"),
          "value"=>$rsData->SelectedRowsCount()),
          // selection counter
    array("counter"=>true,
          "title"=>GetMessage("MAIN_ADMIN_LIST_CHECKED"), "value"=>"0"),
  )
);

// group actions
$lAdmin->AddGroupActionTable(Array(
  // delete selected elements
  "delete"=>GetMessage("MAIN_ADMIN_LIST_DELETE"),
  // activate selected elements
  "activate"=>GetMessage("MAIN_ADMIN_LIST_ACTIVATE"),
  // deactivate selected elements
  "deactivate"=>GetMessage("MAIN_ADMIN_LIST_DEACTIVATE"),
  ));
Configuring Control Panel parameters

If required, you can assign the Control Panel menu which is displayed above the table (for users having the editing permissions). The menu is created as an array whose elements are associated arrays with the following keys:

Key | Description
TEXT | The menu item text.
TITLE | The menu item tooltip.
LINK | The button link.
LINK_PARAM | Additional link parameters (will be added to the <A> tag).
ICON | The button CSS class.
HTML | Specifies the menu item HTML code.
SEPARATOR | Specifies that an item is a separator (true|false).
NEWBAR | Starts a new block of menu items (true|false).
MENU | Creates a drop down menu. The value is specified similarly to the table row context menu.

The context menu is attached by calling CAdminList::AddAdminContextMenu.

Example:

// build a menu consisting of only one item - "Add newsletter"
$aContext = array(
  array(
    "TEXT"=>GetMessage("POST_ADD"),
    "LINK"=>"rubric_edit.php?lang=".LANG,
    "TITLE"=>GetMessage("POST_ADD_TITLE"),
    "ICON"=>"btn_new",
  ),
);

// and attach it to the list
$lAdmin->AddAdminContextMenu($aContext);
Final steps

Now the list preparation is completed. Call CAdminList::CheckListMode to enable alternative rendering methods (AJAX, export to Excel):

// alternative display
$lAdmin->CheckListMode();

Finally, set the page title immediately before output.

// set the page title
$APPLICATION->SetTitle(GetMessage("rub_title"));
Data output

As the figure shows, the page preparation and the main output must be separated by including the system file prolog_admin_after.php:

// remember to separate data preparation from presentation
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");

As it has been mentioned above, data output can be split into two parts:

  • filter output;
  • list output.
Rendering the filter

To render the filter, we need to create a CAdminFilter class instance, pass the list of fields to it, and then build the filter form.

Example:

// create a filter object
$oFilter = new CAdminFilter(
  $sTableID."_filter",
  array(
    "ID",
    GetMessage("rub_f_site"),
    GetMessage("rub_f_active"),
    GetMessage("rub_f_public"),
    GetMessage("rub_f_auto"),
  )
);
?>
<form name="find_form" method="get" action="<?echo $APPLICATION->GetCurPage();?>">
<?$oFilter->Begin();?>
<tr>
  <td><?="ID"?>:</td>
  <td>
    <input type="text" name="find_id" size="47" value="<?echo htmlspecialchars($find_id)?>">
  </td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_site").":"?></td>
  <td><input type="text" name="find_lid" size="47" value="<?echo htmlspecialchars($find_lid)?>"></td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_active")?>:</td>
  <td>
    <?
    $arr = array(
      "reference" => array(
        GetMessage("POST_YES"),
        GetMessage("POST_NO"),
      ),
      "reference_id" => array(
        "Y",
        "N",
      )
    );
    echo SelectBoxFromArray("find_active", $arr, $find_active, GetMessage("POST_ALL"), "");
    ?>
  </td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_public")?>:</td>
  <td><?echo SelectBoxFromArray("find_visible", $arr, $find_visible, GetMessage("POST_ALL"), "");?></td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_auto")?>:</td>
  <td><?echo SelectBoxFromArray("find_auto", $arr, $find_auto, GetMessage("POST_ALL"), "");?></td>
</tr>
<?
$oFilter->Buttons(array("table_id"=>$sTableID,"url"=>$APPLICATION->GetCurPage(),"form"=>"find_form"));
$oFilter->End();
?>
</form>
Rendering the table

Having prepared all the required data, we can now render the report table just with one call:

// output the table of element list
$lAdmin->DisplayList();

Here you can find the complete example of an administration page with the list.

© 2001-2008 Bitrix Bitrix Site Manager


Example: creating a custom list of elements

A detailed description of creating a Control Panel report page can be found here.

Example

<?
// include all necessary files:
 // the first common prologue
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");
 // initialise the module
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/include.php");
// the module prologue
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/prolog.php");

// include a language file
IncludeModuleLangFile(__FILE__);

// obtain the current user access level for the module
$POST_RIGHT = $APPLICATION->GetGroupRight("subscribe");
// if access if denied, direct the user to the autorisation form
if ($POST_RIGHT == "D")
    $APPLICATION->AuthForm(GetMessage("ACCESS_DENIED"));

$sTableID = "tbl_rubric"; // the table ID
$oSort = new CAdminSorting($sTableID, "ID", "desc"); // the object to be sorted
$lAdmin = new CAdminList($sTableID, $oSort); // the main list object

// ******************************************************************** //
//                           FILTER                                     //
// ******************************************************************** //

// *********************** CheckFilter ******************************** //
// move filter validation to a separate function
function CheckFilter()
{
  global $FilterArr, $lAdmin;
  foreach ($FilterArr as $f) global $$f;

  // In this case, no check is required.
  // In a common case, the value of $find_name is be checked
  // and if an error occurs, it should be passed to a handler
  // using $lAdmin->AddFilterError('error_text').

  // return false if an error occurs;
  return count($lAdmin->arFilterErrors)==0;
}
// *********************** /CheckFilter ******************************* //

// describe filter elements
$FilterArr = Array(
  "find",
  "find_type",
  "find_id",
  "find_lid",
  "find_active",
  "find_visible",
  "find_auto",
  );

// initialise the filter
$lAdmin->InitFilter($FilterArr);

// if all filter values are correct, process it
if (CheckFilter())
{
  // create a filter array to invoke CRubric::GetList()
  $arFilter = Array(
    "ID"    => ($find!="" && $find_type == "id"? $find:$find_id),
    "LID"    => $find_lid,
    "ACTIVE"  => $find_active,
    "VISIBLE"  => $find_visible,
    "AUTO"    => $find_auto,
  );
}

// ******************************************************************** //
//                HANDLE LIST ELEMENTS ACTIONS
// ******************************************************************** //

// save edited elements
if($lAdmin->EditAction() && $POST_RIGHT=="W")
{
  // walk the list of elements
  foreach($FIELDS as $ID=>$arFields)
  {
    if(!$lAdmin->IsUpdated($ID))
      continue;

    // save changes of each element
    $DB->StartTransaction();
    $ID = IntVal($ID);
    $cData = new CRubric;
    if(($rsData = $cData->GetByID($ID)) && ($arData = $rsData->Fetch()))
    {
      foreach($arFields as $key=>$value)
        $arData[$key]=$value;
      if(!$cData->Update($ID, $arData))
      {
        $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".$cData->LAST_ERROR, $ID);
        $DB->Rollback();
      }
    }
    else
    {
      $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".GetMessage("rub_no_rubric"), $ID);
      $DB->Rollback();
    }
    $DB->Commit();
  }
}

// handle single and group actions
if(($arID = $lAdmin->GroupAction()) && $POST_RIGHT=="W")
{
  // if "For all elements" is checked
  if($_REQUEST['action_target']=='selected')
  {
    $cData = new CRubric;
    $rsData = $cData->GetList(array($by=>$order), $arFilter);
    while($arRes = $rsData->Fetch())
      $arID[] = $arRes['ID'];
  }

  // walk the list of elements
  foreach($arID as $ID)
  {
    if(strlen($ID)<=0)
      continue;
       $ID = IntVal($ID);

    // perform the required action for each element
    switch($_REQUEST['action'])
    {
    // delete
    case "delete":
      @set_time_limit(0);
      $DB->StartTransaction();
      if(!CRubric::Delete($ID))
      {
        $DB->Rollback();
        $lAdmin->AddGroupError(GetMessage("rub_del_err"), $ID);
      }
      $DB->Commit();
      break;

    // activate/deactivate
    case "activate":
    case "deactivate":
      $cData = new CRubric;
      if(($rsData = $cData->GetByID($ID)) && ($arFields = $rsData->Fetch()))
      {
        $arFields["ACTIVE"]=($_REQUEST['action']=="activate"?"Y":"N");
        if(!$cData->Update($ID, $arFields))
          $lAdmin->AddGroupError(GetMessage("rub_save_error").$cData->LAST_ERROR, $ID);
      }
      else
        $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".GetMessage("rub_no_rubric"), $ID);
      break;
    }
  }
}

// ******************************************************************** //
//                EXTRACT LIST ELEMENTS
// ******************************************************************** //

// get the list of mail lists
$cData = new CRubric;
$rsData = $cData->GetList(array($by=>$order), $arFilter);

// create an instance of CAdminResult from the list
$rsData = new CAdminResult($rsData, $sTableID);

// initialise pagewise navigation similar to CDBResult.
$rsData->NavStart();

// print the page switcher to $lAdmin
$lAdmin->NavText($rsData->GetNavPrint(GetMessage("rub_nav")));

// ******************************************************************** //
//                PREPARE LIST FOR OUTPUT
// ******************************************************************** //

$lAdmin->AddHeaders(array(
  array(  "id"    =>"ID",
    "content"  =>"ID",
    "sort"    =>"id",
    "align"    =>"right",
    "default"  =>true,
  ),
  array(  "id"    =>"NAME",
    "content"  =>GetMessage("rub_name"),
    "sort"    =>"name",
    "default"  =>true,
  ),
  array(  "id"    =>"LID",
    "content"  =>GetMessage("rub_site"),
    "sort"    =>"lid",
    "default"  =>true,
  ),
  array(  "id"    =>"SORT",
    "content"  =>GetMessage("rub_sort"),
    "sort"    =>"sort",
    "align"    =>"right",
    "default"  =>true,
  ),
  array(  "id"    =>"ACTIVE",
    "content"  =>GetMessage("rub_act"),
    "sort"    =>"act",
    "default"  =>true,
  ),
  array(  "id"    =>"VISIBLE",
    "content"  =>GetMessage("rub_visible"),
    "sort"    =>"visible",
    "default"  =>true,
  ),
  array(  "id"    =>"AUTO",
    "content"  =>GetMessage("rub_auto"),
    "sort"    =>"auto",
    "default"  =>true,
  ),
  array(  "id"    =>"LAST_EXECUTED",
    "content"  =>GetMessage("rub_last_exec"),
    "sort"    =>"last_executed",
    "default"  =>true,
  ),
));

while($arRes = $rsData->NavNext(true, "f_")):

  // create a row. the result is an instance of CAdminListRow
  $row =& $lAdmin->AddRow($f_ID, $arRes);

  // next, configure the value display format for viewing and editing

  // the NAME parameter is edited as text and displayed as link
  $row->AddInputField("NAME", array("size"=>20));
  $row->AddViewField("NAME", '<a href="rubric_edit.php?ID='.$f_ID.'&lang='.LANG.'">'.$f_NAME.'</a>');

  // the LID parameter is edited as a drop down list
  $row->AddEditField("LID", CLang::SelectBox("LID", $f_LID));

  // the SORT parameter is edited as text
  $row->AddInputField("SORT", array("size"=>20));

  // the ACTIVE and VISIBLE flags are edited as checkboxes
  $row->AddCheckField("ACTIVE");
  $row->AddCheckField("VISIBLE");

  // the AUTO parameter is displayed as Yes or No text in bold in editing mode
  $row->AddViewField("AUTO", $f_AUTO=="Y"?GetMessage("POST_U_YES"):GetMessage("POST_U_NO"));
  $row->AddEditField("AUTO", "<b>".($f_AUTO=="Y"?GetMessage("POST_U_YES"):GetMessage("POST_U_NO"))."</b>");

  // build the context menu
  $arActions = Array();

  // edit the element
  $arActions[] = array(
    "ICON"=>"edit",
    "DEFAULT"=>true,
    "TEXT"=>GetMessage("rub_edit"),
    "ACTION"=>$lAdmin->ActionRedirect("rubric_edit.php?ID=".$f_ID)
  );

  // delete the element
  if ($POST_RIGHT>="W")
    $arActions[] = array(
      "ICON"=>"delete",
      "TEXT"=>GetMessage("rub_del"),
      "ACTION"=>"if(confirm('".GetMessage('rub_del_conf')."')) ".$lAdmin->ActionDoGroup($f_ID, "delete")
    );

  // insert a separator
  $arActions[] = array("SEPARATOR"=>true);

  // check the automated mail lists
  if (strlen($f_TEMPLATE)>0 && $f_AUTO=="Y")
    $arActions[] = array(
      "ICON"=>"",
      "TEXT"=>GetMessage("rub_check"),
      "ACTION"=>$lAdmin->ActionRedirect("template_test.php?ID=".$f_ID)
    );

  // if the separator comes last, remove it
  if(is_set($arActions[count($arActions)-1], "SEPARATOR"))
    unset($arActions[count($arActions)-1]);

  // apply the context menu to the row
  $row->AddActions($arActions);

endwhile;

// the table footer
$lAdmin->AddFooter(
  array(
    array("title"=>GetMessage("MAIN_ADMIN_LIST_SELECTED"),
          "value"=>$rsData->SelectedRowsCount()), // number of elements
    array("counter"=>true,
          "title"=>GetMessage("MAIN_ADMIN_LIST_CHECKED"),
          "value"=>"0"), // counter of selected elements
  )
);

// group actions
$lAdmin->AddGroupActionTable(Array(
  "delete"=>GetMessage("MAIN_ADMIN_LIST_DELETE"), // delete selected elements
  "activate"=>GetMessage("MAIN_ADMIN_LIST_ACTIVATE"), // activate selected elements
  "deactivate"=>GetMessage("MAIN_ADMIN_LIST_DEACTIVATE"), // deactivate selected elements
  ));

// ******************************************************************** //
//                CONTROL PANEL MENU

// ******************************************************************** //

// create a menu item containing only one item: Create Newsletter
$aContext = array(
  array(
    "TEXT"=>GetMessage("POST_ADD"),
    "LINK"=>"rubric_edit.php?lang=".LANG,
    "TITLE"=>GetMessage("POST_ADD_TITLE"),
    "ICON"=>"btn_new",
  ),
);

// and attach it to the list
$lAdmin->AddAdminContextMenu($aContext);

// ******************************************************************** //
//                OUTPUT
// ******************************************************************** //

// enable export
$lAdmin->CheckListMode();

// specify page title
$APPLICATION->SetTitle(GetMessage("rub_title"));

// remember to separate data preparation from display
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");

// ******************************************************************** //
//                FILTER OUTPUT
// ******************************************************************** //

// create a filter object
$oFilter = new CAdminFilter(
  $sTableID."_filter",
  array(
    "ID",
    GetMessage("rub_f_site"),
    GetMessage("rub_f_active"),
    GetMessage("rub_f_public"),
    GetMessage("rub_f_auto"),
  )
);
?>
<form name="find_form" method="get" action="<?echo $APPLICATION->GetCurPage();?>">
<?$oFilter->Begin();?>
<tr>
  <td><b><?=GetMessage("rub_f_find")?>:</b></td>
  <td>
    <input type="text" size="25" name="find" value="<?echo htmlspecialchars($find)?>" title="<?=GetMessage("rub_f_find_title")?>">
    <?
    $arr = array(
      "reference" => array(
        "ID",
      ),
      "reference_id" => array(
        "id",
      )
    );
    echo SelectBoxFromArray("find_type", $arr, $find_type, "", "");
    ?>
  </td>
</tr>
<tr>
  <td><?="ID"?>:</td>
  <td>
    <input type="text" name="find_id" size="47" value="<?echo htmlspecialchars($find_id)?>">
  </td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_site").":"?></td>
  <td><input type="text" name="find_lid" size="47" value="<?echo htmlspecialchars($find_lid)?>"></td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_active")?>:</td>
  <td>
    <?
    $arr = array(
      "reference" => array(
        GetMessage("POST_YES"),
        GetMessage("POST_NO"),
      ),
      "reference_id" => array(
        "Y",
        "N",
      )
    );
    echo SelectBoxFromArray("find_active", $arr, $find_active, GetMessage("POST_ALL"), "");
    ?>
  </td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_public")?>:</td>
  <td><?echo SelectBoxFromArray("find_visible", $arr, $find_visible, GetMessage("POST_ALL"), "");?></td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_auto")?>:</td>
  <td><?echo SelectBoxFromArray("find_auto", $arr, $find_auto, GetMessage("POST_ALL"), "");?></td>
</tr>
<?
$oFilter->Buttons(array("table_id"=>$sTableID,"url"=>$APPLICATION->GetCurPage(),"form"=>"find_form"));
$oFilter->End();
?>
</form>

<?
// display the table
$lAdmin->DisplayList();
?>

<?
// close the table
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin.php");
?>
© 2001-2008 Bitrix Bitrix Site Manager


Example: creating a custom editing form

You can view a working example of a custom Control Panel editing page in Example: creating a custom editing page.

Basic principles

The following functions are required to implement a Control Panel editing page:

  • protection against unauthorized access;
  • obtaining and preparing the form data;
  • display the editing form in the format that would give a user a better usability experience;
  • process data modifications and analyse errors.

API features designed for building the Control Panel pages allow to isolate the implementation of these functions. To give a user a better usability experience, forms should be split into pages with dynamic navigation using tabs.

Let us see how to create an editing form in the administration interface. We shall use the Newsletter module page as an example.

The beginning

First, create a file bitrix/modules/subscribe/rubric_edit.php as follows:

<?
// include all necessary files

// the first common prologue
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");

// initialise the module
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/include.php");

// the module proloque
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/prolog.php");

// include a language file
IncludeModuleLangFile(__FILE__);

// obtain the current user access level for the module
$POST_RIGHT = $APPLICATION->GetGroupRight("subscribe");

// if access is denied, direct the visitor to the authorization form
if ($POST_RIGHT == "D")
$APPLICATION->AuthForm(GetMessage("ACCESS_DENIED"));?>
<?
// prepare all data here
?>
<?
// the second common prologue
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");
?>
<?
// display page here
?>
<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin.php");?>

This is the page body indicated on the figure.

Now create a French language file, for example: /bitrix/modules/subscribe/lang/ru/rubric_edit.php. In this file, create all language messages as the array elements: $MESS['message_identifier'] = "message_text";.

Since the /bitrix/modules/ catalog is not accessible via HTTP as has been set by the BSM installation, create a file /bitrix/admin/rubric_edit.php:

<?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/admin/rubric_edit.php");
?>

Now this file is available here: http://mysite.ru/bitrix/admin/rubric_edit.php.

Page functions

As the figure illustrates, all page functions can be relatively divided into the following steps:

  • Processing and preparing data
    • Process and save changes;
    • Select and prepare data for the form;
    • Configuring the tabbed interface and the Control Panel menu parameters.
  • Data output
    • Configure and display the Control Panel menu;
    • Display error messages, if any;
    • Display the tabbed editing form.

For this, we need instances of the following classes.

Class | Description
CAdminTabControl | Displays the form split into pages with dynamic tabs.
CAdminMessage | Used with administration messages.
CAdminContextMenu | Used with the Control Panel action toolbars.
Handling and preparing data
Configuring the tabbed interface

A Control Panel form can be split into tabbed pages. To define the tab layout, you have to create an array whose elements are associated arrays with the following keys.

Key | Description
DIV | The unique tab ID.
TAB | The tab text.
TITLE | Describes the page to which the tab is linked.
ICON | The CSS class of an icon to be displayed near the page title.
ONSELECT | JavaScript function to be executed when a user clicks the tab.

Now, we have to create a CAdminTabControl class instance passing this structure to the class constructor.

$aTabs = array(
  array("DIV" => "edit1",
        "TAB" => GetMessage("rub_tab_rubric"),
        "ICON"=>"main_user_edit",
        "TITLE"=>GetMessage("rub_tab_rubric_title")),
  array("DIV" => "edit2",
        "TAB" => GetMessage("rub_tab_generation"),
        "ICON"=>"main_user_edit",
        "TITLE"=>GetMessage("rub_tab_generation_title")),
);

$tabControl = new CAdminTabControl("tabControl", $aTabs);
Handling and saving changes

First, define variables for later use:

// the identifier of a record to be edited
$ID = intval($ID);

// error message
$message = null;

// this flag indicates that the data was obtained via the form rather than database
$bVarsFromForm = false;

The form dirty state can be determined using the following parameters:

  • The page is called using POST.
  • The input parameters include the Save or Apply button identifiers.

If one of these conditions are true and security checks are passed, we can save the data that has been passed to the script:

if(
    $REQUEST_METHOD == "POST" // check the page call method
    &&
    ($save!="" || $apply!="") // check Save and Apply buttons
    &&
    $POST_RIGHT=="W"          // check the access permission for the module
    &&
    check_bitrix_sessid()     // check the session identifier
)
{
  $rubric = new CRubric;

  // process the form data
  $arFields = Array(
    "ACTIVE"         => ($ACTIVE <> "Y" ? "N" : "Y"),
    "NAME"           => $NAME,
    "SORT"           => $SORT,
    "DESCRIPTION"    => $DESCRIPTION,
    "LID"            => $LID,
    "AUTO"           => ($AUTO <> "Y" ? "N" : "Y"),
    "DAYS_OF_MONTH"  => $DAYS_OF_MONTH,
    "DAYS_OF_WEEK"   => (is_array($DAYS_OF_WEEK) ? implode(",", $DAYS_OF_WEEK) : ""),
    "TIMES_OF_DAY"   => $TIMES_OF_DAY,
    "TEMPLATE"       => $TEMPLATE,
    "VISIBLE"        => ($VISIBLE <> "Y" ? "N" : "Y"),
    "FROM_FIELD"     => $FROM_FIELD,
    "LAST_EXECUTED"  => $LAST_EXECUTED
  );

  // save the data
  if($ID > 0)
  {
    $res = $rubric->Update($ID, $arFields);
  }
  else
  {
    $ID = $rubric->Add($arFields);
    $res = ($ID > 0);
  }

  if($res)
  {
    // if saved ok, direct to a new page
    // (to prevent repeated form posts by clicking "Refresh" in a browser)
    if ($apply != "")
      // if Apply is clicked, navigate back to the form.
      LocalRedirect("/bitrix/admin/rubric_edit.php?ID=".$ID."&mess=ok&lang=".LANG."&".$tabControl->ActiveTabParam());
    else
      // if Save is clicked, open the list of elements.
      LocalRedirect("/bitrix/admin/rubric_admin.php?lang=".LANG);
  }
  else
  {
    // if an error occurred,
    // obtain the error message and modify the above variables
    if($e = $APPLICATION->GetException())
      $message = new CAdminMessage(GetMessage("rub_save_error"), $e);
    $bVarsFromForm = true;
  }
}
Selecting and preparing form data

First, define the default values. All data received form the database will be saved in the str_ variables.

$str_SORT          = 100;
$str_ACTIVE        = "Y";
$str_AUTO          = "N";
$str_DAYS_OF_MONTH = "";
$str_DAYS_OF_WEEK  = "";
$str_TIMES_OF_DAY  = "";
$str_VISIBLE       = "Y";
$str_LAST_EXECUTED = ConvertTimeStamp(false, "FULL");
$str_FROM_FIELD    = COption::GetOptionString("subscribe", "default_from");

Extract data:

if($ID>0)
{
  $rubric = CRubric::GetByID($ID);
  if(!$rubric->ExtractFields("str_"))
    $ID=0;
}

Prepare the data and specify the page title:

// if the data came from the form, initialise it
if($bVarsFromForm)
  $DB->InitTableVarsForEdit("b_list_rubric", "", "str_");

$APPLICATION->SetTitle(($ID>0? GetMessage("rub_title_edit").$ID : GetMessage("rub_title_add")));
Configuring the Control Panel menu parameters

If required, you can assign the Control Panel menu which is displayed above the table (for users having the editing permissions). The menu is created as an array whose elements are associated arrays with the following keys:

Key | Description
TEXT | The menu item text.
TITLE | The text of the menu item toolbar.
LINK | The button link.
LINK_PARAM | Additional link parameters (will be added to the <A> tag).
ICON | The button CSS class.
HTML | Specifies the menu item HTML code.
SEPARATOR | Specifies that an item is a separator (true|false).
NEWBAR | Starts a new block of menu items (true|false).
MENU | Creates a drop down menu. The value is specified similarly to the table row context menu.

Example:

$aMenu = array(
  array(
    "TEXT"  => GetMessage("rub_list"),
    "TITLE" => GetMessage("rub_list_title"),
    "LINK"  => "rubric_admin.php?lang=".LANG,
    "ICON"  => "btn_list",
  )
);

if($ID>0)
{
  $aMenu[] = array("SEPARATOR"=>"Y");

  $aMenu[] = array(
    "TEXT"  => GetMessage("rub_add"),
    "TITLE" => GetMessage("rubric_mnu_add"),
    "LINK"  => "rubric_edit.php?lang=".LANG,
    "ICON"  => "btn_new",
  );
  $aMenu[] = array(
    "TEXT"  => GetMessage("rub_delete"),
    "TITLE" => GetMessage("rubric_mnu_del"),
    "LINK"  => "javascript:if(confirm('".GetMessage("rubric_mnu_del_conf")."')) ".
           "window.location='rubric_admin.php?ID=".$ID.
               "&action=delete&lang=".LANG."&".bitrix_sessid_get()."';",
    "ICON"  => "btn_delete",
  );
  $aMenu[] = array("SEPARATOR"=>"Y");
  $aMenu[] = array(
    "TEXT"  => GetMessage("rub_check"),
    "TITLE" => GetMessage("rubric_mnu_check"),
    "LINK"  => "template_test.php?lang=".LANG."&ID=".$ID
  );
}

The resulting structure is passed to the CAdminContextMenu constructor.

Data output

As the figure shows, the page preparation and the main output must be separated by including the system file prolog_admin_after.php:

// don't forget to separate data preparation from presentation
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");

First, display the prepared administration menu.

// create an instance of the Control Panel menu class
$context = new CAdminContextMenu($aMenu);

// emit the menu
$context->Show();

Display error or success messages, if any.

if($_REQUEST["mess"] == "ok" && $ID>0)
  CAdminMessage::ShowMessage(array("MESSAGE"=>GetMessage("rub_saved"), "TYPE"=>"OK"));

if($message)
  echo $message->Show();
elseif($rubric->LAST_ERROR!="")
  CAdminMessage::ShowMessage($rubric->LAST_ERROR);

Now print the form. Use CAdminTabControl::Begin to initialise the tab engine and display the tab bar. CAdminTabControl::BeginNextTab is used to end a current tab and start a new tab. CAdminTabControl::End closes all tabs.

<form method="POST" Action="<?echo $APPLICATION->GetCurPage()?>" ENCTYPE="multipart/form-data" name="post_form">
<?// check the session identifier ?>
<?echo bitrix_sessid_post();?>
<input type="hidden" name="lang" value="<?=LANG?>">
<?if($ID>0 && !$bCopy):?>
  <input type="hidden" name="ID" value="<?=$ID?>">
<?endif;?>
<?
// display tab titles
$tabControl->Begin();
?>
<?
//********************
// the first tab - an editing form of mail list parameters
//********************
$tabControl->BeginNextTab();
?>
  <tr>
    <td width="40%"><?echo GetMessage("rub_act")?></td>
    <td width="60%"><input type="checkbox" name="ACTIVE" value="Y"
      <?if($str_ACTIVE == "Y") echo " checked"?> /></td>
  </tr>

  <!--  HTML code of the table rows -->

  <tr>
    <td><?echo GetMessage("rub_auto")?></td>
    <td><input type="checkbox" name="AUTO" value="Y"
        <?if ($str_AUTO == "Y") echo " checked"?>
              OnClick="if(this.checked) tabControl.EnableTab('edit2');
          else
              tabControl.DisableTab('edit2');" /></td>
  </tr>
<?
//********************
// the second tab - automated mail list parameters
//********************
$tabControl->BeginNextTab();
?>
  <tr class="heading">
    <td colspan="2"><?echo GetMessage("rub_schedule")?></td>
  </tr>
  <tr>
    <td width="40%"><span class="required">*</span><?echo GetMessage("rub_last_executed"). " (".FORMAT_DATETIME."):"?></td>
    <td width="60%"><?echo CalendarDate("LAST_EXECUTED", $str_LAST_EXECUTED, "post_form", "20")?></td>
  </tr>

  <!--  HTML code of the table rows -->

  <tr>
    <td><span class="required">*</span><?echo GetMessage("rub_post_fields_from")?></td>
    <td><input type="text" name="FROM_FIELD" value="<?echo $str_FROM_FIELD;?>" size="30" maxlength="255" /></td>
  </tr>
<?
// close the form: display save and apply controls
$tabControl->Buttons(
  array(
    "disabled"=>($POST_RIGHT<"W"),
    "back_url"=>"rubric_admin.php?lang=".LANG,
  )
);
?>
<?
// complete the tabs
$tabControl->End();
?>

As the figure shows, a connection can be established between the form fields and the error messages, which will display messages about the fields whose values are incorrect.

<?
// additional errors messages displayed besides the field where an error occured
$tabControl->ShowWarnings("post_form", $message);
?>

You can also control the tab behaviour via JavaScript. Consider the following example of disabling a tab:

<script language="JavaScript">
<!--
  if(document.post_form.AUTO.checked)
    tabControl.EnableTab('edit2');
  else
    tabControl.DisableTab('edit2');
//-->
</script>

Display the following notification after the table:

<?echo BeginNote();?>
<span class="required">*</span><?echo GetMessage("REQUIRED_FIELDS")?>
<?echo EndNote();?>

<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin.php");?>

Here you can find the complete example of an administration page with the list.

© 2001-2008 Bitrix Bitrix Site Manager


Example: creating a custom editing page

A detailed description of creating a Control Panel editing page can be found here.

Example

<?
// include all the required files
// common prologue
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");

// initialise the module
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/include.php");

// the module prologue
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/subscribe/prolog.php");

// include a language file
IncludeModuleLangFile(__FILE__);

// get the current user permissions for the module
$POST_RIGHT = $APPLICATION->GetGroupRight("subscribe");
// no permission - open the authorisation form
if ($POST_RIGHT == "D")
  $APPLICATION->AuthForm(GetMessage("ACCESS_DENIED"));

// create the tab array
$aTabs = array(
  array("DIV" => "edit1", "TAB" => GetMessage("rub_tab_rubric"), "ICON"=>"main_user_edit", "TITLE"=>GetMessage("rub_tab_rubric_title")),
  array("DIV" => "edit2", "TAB" => GetMessage("rub_tab_generation"), "ICON"=>"main_user_edit", "TITLE"=>GetMessage("rub_tab_generation_title")),
);
$tabControl = new CAdminTabControl("tabControl", $aTabs);

$ID = intval($ID);		// the ID of a record to edit
$message = null;		// error message
// this flag indicates that the data has been received fron a form
// rather than database
$bVarsFromForm = false;

// ******************************************************************** //
//                    PROCESS USER EDITINGS                             //
// ******************************************************************** //

if(
    $REQUEST_METHOD == "POST" // check the page call method
    &&
    ($save!="" || $apply!="") // check Save and Apply buttons
    &&
    $POST_RIGHT=="W"          // check the access permission for the module
    &&
    check_bitrix_sessid()     // check the session identifier
)
{
  $rubric = new CRubric;

  // process the form data
  $arFields = Array(
    "ACTIVE"  => ($ACTIVE <> "Y"? "N":"Y"),
    "NAME"    => $NAME,
    "SORT"    => $SORT,
    "DESCRIPTION"  => $DESCRIPTION,
    "LID"    => $LID,
    "AUTO"    =>($AUTO <> "Y"? "N":"Y"),
    "DAYS_OF_MONTH"  => $DAYS_OF_MONTH,
    "DAYS_OF_WEEK"  => (is_array($DAYS_OF_WEEK)?implode(",", $DAYS_OF_WEEK):""),
    "TIMES_OF_DAY"  => $TIMES_OF_DAY,
    "TEMPLATE"  => $TEMPLATE,
    "VISIBLE"  => ($VISIBLE <> "Y"? "N":"Y"),
    "FROM_FIELD"  => $FROM_FIELD,
    "LAST_EXECUTED"  => $LAST_EXECUTED
  );

  // save the data
  if($ID > 0)
  {
    $res = $rubric->Update($ID, $arFields);
  }
  else
  {
    $ID = $rubric->Add($arFields);
    $res = ($ID > 0);
  }

  if($res)
  {
    // if saved ok, direct to a new page
    // (to prevent repeated form posts by clicking "Refresh" in a browser)
    if ($apply != "")
      // if Apply is clicked, navigate back to the form.
      LocalRedirect("/bitrix/admin/rubric_edit.php?ID=".$ID."&mess=ok&lang=".LANG."&".$tabControl->ActiveTabParam());
    else
      // if Save is clicked, open the list of elements.
      LocalRedirect("/bitrix/admin/rubric_admin.php?lang=".LANG);
  }
  else
  {
    // if an error occurred,
    // obtain the error message and modify the above variables
    if($e = $APPLICATION->GetException())
      $message = new CAdminMessage(GetMessage("rub_save_error"), $e);
    $bVarsFromForm = true;
  }
}

// ******************************************************************** //
//                EXTRACT AND PREPARE THE FORM DATA                     //
// ******************************************************************** //

// default values
$str_SORT          = 100;
$str_ACTIVE        = "Y";
$str_AUTO          = "N";
$str_DAYS_OF_MONTH = "";
$str_DAYS_OF_WEEK  = "";
$str_TIMES_OF_DAY  = "";
$str_VISIBLE       = "Y";
$str_LAST_EXECUTED = ConvertTimeStamp(false, "FULL");
$str_FROM_FIELD    = COption::GetOptionString("subscribe", "default_from");

// extract data
if($ID>0)
{
  $rubric = CRubric::GetByID($ID);
  if(!$rubric->ExtractFields("str_"))
    $ID=0;
}

// some more preparation please...
if($ID>0 && !$message)
  $DAYS_OF_WEEK = explode(",", $str_DAYS_OF_WEEK);
if(!is_array($DAYS_OF_WEEK))
  $DAYS_OF_WEEK = array();

// if the data came from the form, initialise it
if($bVarsFromForm)
  $DB->InitTableVarsForEdit("b_list_rubric", "", "str_");

// ******************************************************************** //
//                    PRINT THE FORM                                    //
// ******************************************************************** //

// set the page title
$APPLICATION->SetTitle(($ID>0? GetMessage("rub_title_edit").$ID : GetMessage("rub_title_add")));

// separate preparation from actual output
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");

// Contro Panel Menu
$aMenu = array(
  array(
    "TEXT"=>GetMessage("rub_list"),
    "TITLE"=>GetMessage("rub_list_title"),
    "LINK"=>"rubric_admin.php?lang=".LANG,
    "ICON"=>"btn_list",
  )
);

if($ID>0)
{
  $aMenu[] = array("SEPARATOR"=>"Y");
  $aMenu[] = array(
    "TEXT"=>GetMessage("rub_add"),
    "TITLE"=>GetMessage("rubric_mnu_add"),
    "LINK"=>"rubric_edit.php?lang=".LANG,
    "ICON"=>"btn_new",
  );
  $aMenu[] = array(
    "TEXT"=>GetMessage("rub_delete"),
    "TITLE"=>GetMessage("rubric_mnu_del"),
    "LINK"=>"javascript:if(confirm('".GetMessage("rubric_mnu_del_conf")."'))window.location='rubric_admin.php?ID=".$ID."&action=delete&lang=".LANG."&".bitrix_sessid_get()."';",
    "ICON"=>"btn_delete",
  );
  $aMenu[] = array("SEPARATOR"=>"Y");
  $aMenu[] = array(
    "TEXT"=>GetMessage("rub_check"),
    "TITLE"=>GetMessage("rubric_mnu_check"),
    "LINK"=>"template_test.php?lang=".LANG."&ID=".$ID
  );
}

// create an instance of Control Panel menu
$context = new CAdminContextMenu($aMenu);

// show the menu
$context->Show();
?>

<?
// print error or success messages, if any
if($_REQUEST["mess"] == "ok" && $ID>0)
  CAdminMessage::ShowMessage(array("MESSAGE"=>GetMessage("rub_saved"), "TYPE"=>"OK"));

if($message)
  echo $message->Show();
elseif($rubric->LAST_ERROR!="")
  CAdminMessage::ShowMessage($rubric->LAST_ERROR);
?>

<?
// display the form
?>
<form method="POST" Action="<?echo $APPLICATION->GetCurPage()?>" ENCTYPE="multipart/form-data" name="post_form">
<?// check session ID ?>
<?echo bitrix_sessid_post();?>
<?
// display the tab bar
$tabControl->Begin();
?>
<?
//********************
// tab 1: mail list parameters editing form
//********************
$tabControl->BeginNextTab();
?>
  <tr>
    <td width="40%"><?echo GetMessage("rub_act")?></td>
    <td width="60%"><input type="checkbox" name="ACTIVE" value="Y"<?if($str_ACTIVE == "Y") echo " checked"?>></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_visible")?></td>
    <td><input type="checkbox" name="VISIBLE" value="Y"<?if($str_VISIBLE == "Y") echo " checked"?>></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_site")?></td>
    <td><?echo CLang::SelectBox("LID", $str_LID);?></td>
  </tr>
  <tr>
    <td><span class="required">*</span><?echo GetMessage("rub_name")?></td>
    <td><input type="text" name="NAME" value="<?echo $str_NAME;?>" size="30" maxlength="100"></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_sort")?></td>
    <td><input type="text" name="SORT" value="<?echo $str_SORT;?>" size="30"></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_desc")?></td>
    <td><textarea class="typearea" name="DESCRIPTION" cols="45" rows="5" wrap="VIRTUAL"><?echo $str_DESCRIPTION; ?></textarea></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_auto")?></td>
    <td><input type="checkbox" name="AUTO" value="Y"<?if($str_AUTO == "Y") echo " checked"?> OnClick="if(this.checked) tabControl.EnableTab('edit2'); else tabControl.DisableTab('edit2');"></td>
  </tr>
<?
//********************
// tab 2: parameters of automated mail lists
//********************
$tabControl->BeginNextTab();
?>
  <tr class="heading">
    <td colspan="2"><?echo GetMessage("rub_schedule")?></td>
  </tr>
  <tr>
    <td width="40%"><span class="required">*</span><?echo GetMessage("rub_last_executed"). " (".FORMAT_DATETIME."):"?></td>
    <td width="60%"><?echo CalendarDate("LAST_EXECUTED", $str_LAST_EXECUTED, "post_form", "20")?></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_dom")?></td>
    <td><input class="typeinput" type="text" name="DAYS_OF_MONTH" value="<?echo $str_DAYS_OF_MONTH;?>" size="30" maxlength="100"></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_dow")?></td>
    <td>
    <table cellspacing=1 cellpadding=0 border=0 class="internal">
    <?  $arDoW = array(
        "1"  => GetMessage("rubric_mon"),
        "2"  => GetMessage("rubric_tue"),
        "3"  => GetMessage("rubric_wed"),
        "4"  => GetMessage("rubric_thu"),
        "5"  => GetMessage("rubric_fri"),
        "6"  => GetMessage("rubric_sat"),
        "7"  => GetMessage("rubric_sun")
      );
    ?>
      <tr class="heading"><?foreach($arDoW as $strVal=>$strDoW):?>
        <td><?=$strDoW?></td>
        <?endforeach;?>
      </tr>
      <tr>
      <?foreach($arDoW as $strVal=>$strDoW):?>
        <td><input type="checkbox" name="DAYS_OF_WEEK[]" value="<?=$strVal?>"<?if(array_search($strVal, $DAYS_OF_WEEK) !== false) echo " checked"?>></td>
      <?endforeach;?>
      </tr>
    </table>
    </td>
  </tr>
  <tr>
    <td><span class="required">*</span><?echo GetMessage("rub_tod")?></td>
    <td><input type="text" name="TIMES_OF_DAY" value="<?echo $str_TIMES_OF_DAY;?>" size="30" maxlength="255"></td>
  </tr>
  <tr class="heading">
    <td colspan="2"><?echo GetMessage("rub_template")?></td>
  </tr>
<?
$arTemplates=CPostingTemplate::GetList();
if(count($arTemplates)>0):
?>
  <tr>
    <td><span class="required">*</span><?echo GetMessage("rub_templates")?></td>
    <td><table>
<?
  $i=0;
  foreach($arTemplates as $strTemplate):
    $arTemplate = CPostingTemplate::GetByID($strTemplate);
?>
    <tr>
      <td valign="top"><input type="radio" id="TEMPLATE<?=$i?>" name="TEMPLATE" value="<?=$arTemplate["PATH"]?>"<?if($str_TEMPLATE==$arTemplate["PATH"]) echo "checked"?>></td>
      <td>
        <label for="TEMPLATE<?=$i?>" title="<?=$arTemplate["DESCRIPTION"]?>"><?=(strlen($arTemplate["NAME"])>0?$arTemplate["NAME"]:GetMessage("rub_no_name"))?></label><br>
        <?if(IsModuleInstalled("fileman")):?>
          <a title="<?=GetMessage("rub_manage")?>" href="/bitrix/admin/fileman_admin.php?path=<?=urlencode("/".$arTemplate["PATH"])?>"><?=$arTemplate["PATH"]?></a>
        <?else:?>
          <?=$arTemplate["PATH"]?>
        <?endif?>
      </td>
    <?$i++?>
    </tr>
  <?endforeach;?>
    </table></td>
  </tr>
<?else:?>
  <tr>
    <td colspan="2"><?=GetMessage("rub_no_templates")?></td>
  </tr>
<?endif?>
  <tr class="heading">
    <td colspan="2"><?echo GetMessage("rub_post_fields")?></td>
  </tr>
  <tr>
    <td><span class="required">*</span><?echo GetMessage("rub_post_fields_from")?></td>
    <td><input type="text" name="FROM_FIELD" value="<?echo $str_FROM_FIELD;?>" size="30" maxlength="255"></td>
  </tr>
<?
// close the form and display save and apply changes
$tabControl->Buttons(
  array(
    "disabled"=>($POST_RIGHT<"W"),
    "back_url"=>"rubric_admin.php?lang=".LANG,

  )
);
?>
<input type="hidden" name="lang" value="<?=LANG?>">
<?if($ID>0 && !$bCopy):?>
  <input type="hidden" name="ID" value="<?=$ID?>">
<?endif;?>
<?
// close tabs
$tabControl->End();
?>

<?
// additional error notification: display an icon near the invalid field
$tabControl->ShowWarnings("post_form", $message);
?>

<?
// we can disable the tab if required
?>
<script language="JavaScript">
<!--
  if(document.post_form.AUTO.checked)
    tabControl.EnableTab('edit2');
  else
    tabControl.DisableTab('edit2');
//-->
</script>

<?
// print the small help text
echo BeginNote();?
>
<span class="required">*</span><?echo GetMessage("REQUIRED_FIELDS")?>
<?echo EndNote();?>

<?
// close the page
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin.php");
?>
© 2001-2008 Bitrix Bitrix Site Manager


Creating custom tabs in the forms

This topic describes how you can create custom tabs in Control Panel.

To create custom tabs, you will have to:

  1. implement tab handlers as a class or functions;
  2. Register the tab event by calling AddeventHandler or RegisterModuleDependencies.

The class must implement the following methods:

  • The OnInit() method - returns an array with names or callback arrays of other methods. The array must contain the following keys:
    • TABSET - the tab set ID;
    • GetTabs - a callback array of a tab description method;
    • ShowTab - a callback array of a method returning the HTML code of a form page by the tab identifier;
    • Action - a callback array of a method that will process data received from the from;
    • Check - a callback array of a method that will check data received from the from.
  • All the methods returned by OnInit.
  • Any other methods used in the class or functions.

Example of a class implementing custom tabs

<?
class CCustomOETabs
{
    function OnInit()
    {
        return array(
        "TABSET" => "YYY",
        "GetTabs" => array("CCustomOETabs", "GetTabs"),
        "ShowTab" => array("CCustomOETabs", "ShowTab"),
        "Action" => array("CCustomOETabs", "Action"),
        "Check" => array("CCustomOETabs", "Check"),
        );
    }

    function Action($arArgs)
    {
        // Data is stored. Perfom actions here.
        // Return true on success, or false otherwise.
        // In case of error, also call $GLOBALS["APPLICATION"]-> ThrowException("ERROR!!!");
    }

    function Check($arArgs)
    {
        // Data has not been stored yet. Perform various checks here.
        // Return true if data can be saved, or false otherwise.
        // If false, also call $GLOBALS["APPLICATION"]-> ThrowException("ERROR!!!");
    }

    function GetTabs($arArgs)
    {
        // SORT - specifies the insertion position (in terms of standard tabs).
      // If not specified, inserts after the last tab.
        $arTabs = array(
        array("DIV" => "edit1", "TAB" => "Custom tab 1", "ICON" => "sale", "TITLE" => "Custom tab 1", "SORT" => 1),
        );
        return $arTabs;
    }

    function ShowTab($divName, $arArgs, $bVarsFromForm)
    {
        if ($divName == "edit1")
        {
        ?>
        <tr>
        <td width="40%">Custom field 1:</td>
        <td width="60%"><input type="text" name="custom_field_1"></td>
        </tr>
        <?
        }
    }
}

All methods (except ShowTab) receive an array of arguments specified using in the CAdminTabEngine class constructor or the CAdminTabEngine::SetArgs method. The format of an array returned by GetTabs is described here.

© 2001-2008 Bitrix Bitrix Site Manager


CAdminContextMenu

CAdminContextMenu describes a menu displayed on Control Panel pages.

Methods

Method | Description
CAdminContextMenu | The class constructor.
Show | Displays a menu display.

Example of using menus

See the administration page creation manual.
© 2001-2008 Bitrix Bitrix Site Manager


CAdminContextMenu

CAdminContextMenu::CAdminContextMenu

object
CAdminContextMenu(
    array $arMenu
)

This class allows to create a Control Panel menu normally displayed above the main table (only for users who has permission for editing). Menu configuration is passed in a constructor parameter - an array whose elements are associated arrays containing the following keys:

Key | Description
TEXT | The menu item text.
TITLE | The text of a menu item tooltip.
LINK | The button link.
LINK_PARAM | Additional parameters of the link (<A>) tag.
ICON | The CSS class of an action icon .
HTML | Explicitly sets the HTML code of a menu item.
SEPARATOR | Specifies a separator (true/false).
NEWBAR | Starts a new block of menu items (true/false).
MENU | The key creates a drop-down submenu. The value is specified similarly to the table row context menu.

Example

// Let's build a menu containing only item: add maillist
$aContext = array(
  array(
    "TEXT"=>GetMessage("POST_ADD"),
    "LINK"=>"rubric_edit.php?lang=".LANG,
    "TITLE"=>GetMessage("POST_ADD_TITLE"),
    "ICON"=>"btn_new",
  ),
);

// and attach it to the list
$oMenu = new CAdminContextMenu($aContext);
$oMenu->Show();
© 2001-2008 Bitrix Bitrix Site Manager


Show

CAdminContextMenu::Show

void
CAdminContextMenu::Show(
)

The method Show displays the created menu.

Example

// Build a menu containing only item: add maillist
$aContext = array(
  array(
    "TEXT"=>GetMessage("POST_ADD"),
    "LINK"=>"rubric_edit.php?lang=".LANG,
    "TITLE"=>GetMessage("POST_ADD_TITLE"),
    "ICON"=>"btn_new",
  ),
);

// and attach it to the list
$oMenu = new CAdminContextMenu($aContext);
$oMenu->Show();
© 2001-2008 Bitrix Bitrix Site Manager


CAdminException

The CAdminException class extends the functionality of the CApplicationException class for use in Control Panel.

This class was introduced to facilitate processing of complex error messages.

Methods

Method | Description
CAdminException | The class constructor.
GetMessages | Receives a list of error messages.
AddMessage | Adds error messages to the list.
© 2001-2008 Bitrix Bitrix Site Manager


CAdminException

CAdminException::CAdminException

object
CAdminException(
  array $arMessages[,
  string $id = false]
)

The class constructor.

Receives an array of messages as the first argument where each message is an associated array in the following format: array("id"=>"Error_identifier", "text" => "Error_text").

The second parameter ($id) is similar to the CApplicationException parameter $id.

© 2001-2008 Bitrix Bitrix Site Manager


AddMessage

CAdminException::AddMessage

void
CAdminException::AddMessage(
  array $arMessage
)

The method AddMessage adds a message to the list of errors registered in the class instance.

The messages are specified in the format: array("id"=>"Error identifier", "text" => "Error text").

© 2001-2008 Bitrix Bitrix Site Manager


GetMessages

CAdminException::GetMessages

array
CAdminException::GetMessages(
)

The method GetMessages returns an array of errors passed to the class constructor.

© 2001-2008 Bitrix Bitrix Site Manager


CAdminFilter

The CAdminFilter class is used with the result filter in Control Panel pages.

Methods

Method | Description
CAdminFilter | The class constructor.
Begin | Displays the filter title.
Buttons | Displays the filter buttons.
End | Ends the filter display.

Example

The following example shows how to set up a filter.

// Move the filter check to a separate function
function CheckFilter()
{
    global $FilterArr, $lAdmin;
    foreach ($FilterArr as $f) global $$f;

    /* check values of $find_[name] variables and,
       if an error occurs, call $lAdmin->AddFilterError("error_text"). */

    return count($lAdmin->arFilterErrors) == 0; // if there are errors, return false
}

// describe the filter elements
$FilterArr = Array(
    "find_id",
    "find_lid",
    "find_active",
    "find_visible",
    "find_auto",
    );

// initialise the filter
$lAdmin->InitFilter($FilterArr);

// if all filter values are correct, process it
if (CheckFilter())
{
    // create a filter array for extracting
    // CRubric::GetList() according to filter values
    $arFilter = Array(
        "ID"        => $find_id,
        "LID"        => $find_lid,
        "ACTIVE"    => $find_active,
        "VISIBLE"    => $find_visible,
        "AUTO"        => $find_auto,
    );
}

// then, pass the received array to CRubric::GetList()

To display the filter, you have to create a CAdminFilter class instance passing the list of fields to it, and then build the filter form "manually".

// create a filter object
$oFilter = new CAdminFilter(
  $sTableID."_filter",
  array(
    "ID",
    GetMessage("rub_f_site"),
    GetMessage("rub_f_active"),
    GetMessage("rub_f_public"),
    GetMessage("rub_f_auto"),
  )
);
?>
<form name="find_form" method="get" action="<?echo $APPLICATION->GetCurPage();?>">
<?$oFilter->Begin();?>
<tr>
  <td><?="ID"?>:</td>
  <td>
    <input type="text" name="find_id" size="47" value="<?echo htmlspecialchars($find_id)?>">
  </td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_site").":"?></td>
  <td><input type="text" name="find_lid" size="47" value="<?echo htmlspecialchars($find_lid)?>"></td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_active")?>:</td>
  <td>
    <?
    $arr = array(
      "reference" => array(
        GetMessage("POST_YES"),
        GetMessage("POST_NO"),
      ),
      "reference_id" => array(
        "Y",
        "N",
      )
    );
    echo SelectBoxFromArray("find_active", $arr, $find_active, GetMessage("POST_ALL"), "");
    ?>
  </td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_public")?>:</td>
  <td><?echo SelectBoxFromArray("find_visible", $arr, $find_visible, GetMessage("POST_ALL"), "");?></td>
</tr>
<tr>
  <td><?=GetMessage("rub_f_auto")?>:</td>
  <td><?echo SelectBoxFromArray("find_auto", $arr, $find_auto, GetMessage("POST_ALL"), "");?></td>
</tr>
<?
$oFilter->Buttons(array("table_id"=>$sTableID,"url"=>$APPLICATION->GetCurPage(),"form"=>"find_form"));
$oFilter->End();
?>
</form>
© 2001-2008 Bitrix Bitrix Site Manager


CAdminFilter

CAdminFilter::CAdminFilter

object
CAdminFilter(
    string $ID[,
    array $arPopup = false]
)

The filter class constructor.

Parameters

Parameter | Description
ID | A filter identifier that is unique within the page scope.
arPopup | An array of filter field names.
© 2001-2008 Bitrix Bitrix Site Manager


Begin

CAdminFilter::Begin

void
CAdminFilter::Begin(
)

The method Begin displays the title of a filter form in Control Panel pages.

© 2001-2008 Bitrix Bitrix Site Manager


Buttons

CAdminFilter::Buttons

void
CAdminFilter::Buttons(
  mixed $arParams = false
)

The method Buttons shows the filter command buttons.

Parameters

Parameter Description
arParams Optional array of parameters. The following keys are possible:
  • url - path to the filter processor page (by default - the current page);
  • table_id - the list table ID.
  • report - the key is used with pages that contain reports. False by default.
© 2001-2008 Bitrix Bitrix Site Manager


End

CAdminFilter::End

void
CAdminFilter::End(
)

The End method closes the previously started filter form.

© 2001-2008 Bitrix Bitrix Site Manager


CAdminList

The CAdminList class is used to render a report table on Control Panel pages and perform service actions.

Methods

Method | Description
CAdminList | The class constructor.
AddHeaders | Creates table columns.
AddAdminContextMenu | Creates items for a Control Panel page context menu adds them to a menu.
IsUpdated | Returns true is any of the table rows have been changed when editing the table rows.
EditAction | Returns true if table rows have been edited and changes need to be saved.
GroupAction | Returns true if any group action have been performed on the table rows and changes are to be saved.
ActionRedirect | Returns a string which is a JavaScript call required to redirect a user to the specified page.
ActionAjaxReload | Returns a string which is a JavaScript call required for dynamic list update using the specified URL.
ActionDoGroup | Returns a string which is a JavaScript call required to update a list dynamically using the specified URL.
ActionPost | Returns a string which is a JavaScript call that redirects a user to a specified page using the POST method dispatching a form that contains a list of changes.
CheckListMode | Examines the required table rendering mode.
InitFilter | Initialises the filter.
AddRow | Adds a new row to the table.
AddFooter | Adds a footer to the report table.
Display | Displays the prepared report table.
AddGroupActionTable | Creates a menu of available group actions that can be performed on the list elements.
DisplayList | Displays the prepared report table.
AddUpdateError | Registers errors that occur when saving changes of the table rows.
AddGroupError | Registers errors that occur when processing group actions performed on the table rows.
AddFilterError | Registers errors that occur when performing group actions on the table rows.

Examples

You can find the detailed example of a report page here.

© 2001-2008 Bitrix Bitrix Site Manager


CAdminList

CAdminList::CAdminList

object
CAdminList(
    string $ID[,
    mixed $oSort = false]
)

The class constructor.

Parameters

Parameter | Description
ID | A table list identifier unique within the page.
oSort | The CAdminSorting class instance. Optional.
© 2001-2008 Bitrix Bitrix Site Manager


ActionAjaxReload

CAdminList::ActionAjaxReload

string
CAdminList::ActionAjaxReload(
  string $url
)

ActionAjaxReload returns a string which is a JavaScript call required for dynamic list update using the specified URL. A link to the update script is specified in the $url parameter. The update script can use the CAdminList::CheckListMode method to check the action type.

Example

The following code builds a context menu for a group of files in the Site Explorer.

$defaultEdit = COption::GetOptionString("fileman", "default_edit", "text");

if($FILE_ACCESS > "U")
{
  $arDDMenu = array();

  $isB = false;
  $dbRes = CGroup::GetDropDownList();
  while ($arRes = $dbRes->Fetch())
  {
    if($show_perms_for == $arRes["REFERENCE_ID"])
      $isB = true;

    $arDDMenu[] = array(
      "TEXT" => $arRes["REFERENCE"],
      "ACTION" => $lAdmin->ActionAjaxReload("fileman_admin.php?".$addUrl."&site=".UrlEncode($site)."&path=".UrlEncode($path)."&show_perms_for=".$arRes["REFERENCE_ID"]).';return false;',
      "ICON" =>  ($show_perms_for == $arRes["REFERENCE_ID"] ? "checked" : "" ),
    );
  }

  $arDDMenu[] = array(
    "TEXT" => GetMessage("FILEMAN_ADM_CUR_USER"),
    "ACTION" => $lAdmin->ActionAjaxReload("fileman_admin.php?".$addUrl."&site=".UrlEncode($site)."&path=".UrlEncode($path)."&show_perms_for=0").';return false;',
    "ICON" =>  (!$isB ? "checked" : "" ),
  );

  $aContext = array(
    array(
      "TEXT" => GetMessage("FILEMAN_ADMIN_NEW_FOLDER"),
      "ICON" => "btn_new_folder",
      "LINK" => "fileman_newfolder.php?".$addUrl."&site=".$site."&path=".UrlEncode($path)."",
      "TITLE" => GetMessage("FILEMAN_ADMIN_NEW_FOLDER")
    ),
    array(
      "TEXT" => GetMessage("FILEMAN_ADMIN_NEW_FILE"),
      "ICON" => "btn_new_file",
      "LINK" =>
        ($defaultEdit == 'html'?
          "fileman_html_edit.php?".$addUrl."&site=".$site."&path=".UrlEncode($path)."&new=y"
        :
          (
          $defaultEdit == 'php' && $USER->IsAdmin()?
            "fileman_file_edit.php?".$addUrl."&site=".$site."&full_src=Y&path=".UrlEncode($path)."&new=y"
          :
            "fileman_file_edit.php?".$addUrl."&site=".$site."&path=".UrlEncode($path)."&new=y"
          )
        ),
      "TITLE" => GetMessage("FILEMAN_ADMIN_NEW_FILE")
    ),
    array(
      "TEXT" => GetMessage("FILEMAN_ADMIN_FILE_UPLOAD"),
      "ICON" => "btn_upload",
      "LINK" => "fileman_file_upload.php?".$addUrl."&site=".$site."&path=".UrlEncode($path)."",
      "TITLE" => GetMessage("FILEMAN_ADMIN_FILE_UPLOAD")
    ),
    array(
      "TEXT" => GetMessage("FILEMAN_ADMIN_MENU_ADD"),
      "ICON" => "btn_new_menu",
      "LINK" => "fileman_menu_edit.php?".$addUrl."&site=".$site."&path=".UrlEncode($path)."&new=y",
      "TITLE" => GetMessage("FILEMAN_ADMIN_MENU_ADD")
    ),
    array(
      "NEWBAR" => True
    ),
    array(
      "TEXT" => GetMessage("FILEMAN_ADMIN_FOLDER_PROP"),
      "LINK" => "fileman_folder.php?".$addUrl."&site=".$site."&path=".UrlEncode($path)."",
      "ICON" => "btn_folder_prop",
      "TITLE" => GetMessage("FILEMAN_ADMIN_FOLDER_PROP")
    ),
    array(
      "TEXT" => GetMessage('FILEMAN_SHOW_PRM_FOR'),
      "TITLE" => GetMessage('FILEMAN_SHOW_PRM_FOR'),
      "MENU" => $arDDMenu
    ),
    array(
      "NEWBAR" => True
    ),
  );
}
© 2001-2008 Bitrix Bitrix Site Manager


ActionDoGroup

CAdminList::ActionDoGroup

string
CAdminList::ActionDoGroup(
  string $ID,
  string $action_id[,
  string $add_params='']
)

ActionDoGroup returns a string which is a JavaScript call required to update a list dynamically using the specified URL. The update script can use the CAdminList::CheckListMode method to check the action type.

Parameters

Parameter | Description
ID | The list ID.
action_id | The ID of the required action.
add_params | The string containing additional parameters for the GET query.

Example

  // create a row; the result is the CAdminListRow class instance
  $row =& $lAdmin->AddRow($f_ID, $arRes);

  // build the context menu
  $arActions = Array();

  // delete the element
  if ($POST_RIGHT>="W")
    $arActions[] = array(
      "ICON"=>"delete",
      "TEXT"=>GetMessage("rub_del"),
      "ACTION"=>"if(confirm('".GetMessage('rub_del_conf')."')) ".$lAdmin->ActionDoGroup($f_ID, "delete")
    );

  // attach the context menu to the row
  $row->AddActions($arActions);
© 2001-2008 Bitrix Bitrix Site Manager


ActionPost

CAdminList::ActionPost

string
CAdminList::ActionPost(
  string $url
)

The method ActionPost returns a string which is a JavaScript call that redirects a user to a specified page using the POST method dispatching a form that contains a list of changes. The link to the page is defined in the $url parameter. The method can be used to create links for the Control Panel menu or a list element context menu.

Example

// create a row; the result is the CAdminListRow class instance
  $row =& $lAdmin->AddRow($f_ID, $arRes);

// build the context menu
  $arActions = Array();

  if ($Elem["PERMISSION"] > "R")
  {
    $arActions[] = array("SEPARATOR" => true);
    $arActions[] = array(
      "ICON" => "rename",
      "TEXT" => GetMessage("FILEMAN_RENAME_SAVE"),
      "ACTION" => 'setCheckbox(\''.$f_NAME.'\'); if('.$lAdmin->table_id.'.IsActionEnabled(\'edit\')){document.forms[\'form_'.$lAdmin->table_id.'\'].elements[\'action_button\'].value=\'edit\'; '.$lAdmin->ActionPost().'}'
    );
  }

  // attach the context menu to the row
  $row->AddActions($arActions);
© 2001-2008 Bitrix Bitrix Site Manager


ActionRedirect

CAdminList::ActionRedirect

string
CAdminList::ActionRedirect(
  string $url
)

The method ActionRedirect returns a string which is a JavaScript call required to redirect a user to the specified page. The link to the page is defined in the $url parameter. The method can be used to create links for the Control Panel menu or a list element context menu.

Example

while($arRes = $rsData->NavNext(true, "f_")):

  // create a row; the result is the CAdminListRow class instance
  $row =& $lAdmin->AddRow($f_ID, $arRes);

  // then add fields in the appropriate format

  // the NAME parameter is edited as text and displayed as a link
  $row->AddInputField("NAME", array("size"=>20));
  $row->AddViewField("NAME", '<a href="rubric_edit.php?ID='.$f_ID.'&lang='.LANG.'">'.$f_NAME.'</a>');

  // the LID parameter is edited as a drop-down list of languages
  $row->AddEditField("LID", CLang::SelectBox("LID", $f_LID));

  // the SORT parameter is edited as text
  $row->AddInputField("SORT", array("size"=>20));

  // the ACTIVE and VISIBLE flags are edited as checkboxes
  $row->AddCheckField("ACTIVE");
  $row->AddCheckField("VISIBLE");

  // the AUTO parameter is displayed as Yes or NO in bold in the editing mode
  $row->AddViewField("AUTO", $f_AUTO=="Y"?GetMessage("POST_U_YES"):GetMessage("POST_U_NO"));
  $row->AddEditField("AUTO", "<b>".($f_AUTO=="Y"?GetMessage("POST_U_YES"):GetMessage("POST_U_NO"))."</b>");

  // build the context menu
  $arActions = Array();

  // element editing
  $arActions[] = array(
    "ICON"=>"edit",
    "DEFAULT"=>true,
    "TEXT"=>GetMessage("rub_edit"),
    "ACTION"=>$lAdmin->ActionRedirect("rubric_edit.php?ID=".$f_ID)
  );

  // element deletion
  if ($POST_RIGHT>="W")
    $arActions[] = array(
      "ICON"=>"delete",
      "TEXT"=>GetMessage("rub_del"),
      "ACTION"=>"if(confirm('".GetMessage('rub_del_conf')."')) ".$lAdmin->ActionDoGroup($f_ID, "delete")
    );

  // insert the separator
  $arActions[] = array("SEPARATOR"=>true);

  // check the automated mail list template
  if (strlen($f_TEMPLATE)>0 && $f_AUTO=="Y")
    $arActions[] = array(
      "ICON"=>"",
      "TEXT"=>GetMessage("rub_check"),
      "ACTION"=>$lAdmin->ActionRedirect("template_test.php?ID=".$f_ID)
    );

  // if the separator comes last, delete it
  if(is_set($arActions[count($arActions)-1], "SEPARATOR"))
    unset($arActions[count($arActions)-1]);

  // attach the context menu to the row
  $row->AddActions($arActions);

endwhile;
© 2001-2008 Bitrix Bitrix Site Manager


AddAdminContextMenu

CAdminList::AddAdminContextMenu

void
CAdminList::AddAdminContextMenu([
  array $aMenu = array(),
  bool $bShowExcel = true,
  bool $bShowSettings = true
])

The AddAdminContextMenu method creates items for a Control Panel page context menu adds them to a menu.

Parameters

Parameter | Description
aMenu | A menu descriptor array. See also: CAdminContextMenu.
bShowExcel | If true, specifies to add the MS Excel export button to the context menu. Optional parameter; true by default. The button is added to the end of the menu.
bShowSettings | If true, adds the list customization button to the menu. Optional; true by default. The button will be added to the end of the menu.
© 2001-2008 Bitrix Bitrix Site Manager


AddFilterError

CAdminList::AddFilterError

void
CAdminList::AddFilterError(
  string $strError
)

The AddFilterError method registers errors that occur when performing group actions on the table rows.

Parameters

Parameter | Description
strError | The error text.
© 2001-2008 Bitrix Bitrix Site Manager


AddFooter

CAdminList::AddFooter

void
CAdminList::AddFooter(
  array $arFooter
)

The method AddFooter adds a footer to the report table.

The table footer data is passed in an array whose elements are associated arrays. In each array, the title keys specify the parameter names, and the value keys specify the parameter value.

The associated arrays may contain the counter keys set to true. In this case, the footer element is a counter of selected elements. The counter value will change dynamically.

Example

// table footer
$lAdmin->AddFooter(
  array(
    array("title"=>GetMessage("MAIN_ADMIN_LIST_SELECTED"),
          // number of elements
          "value"=>$rsData->SelectedRowsCount()),
    array("counter"=>true,
          "title"=>GetMessage("MAIN_ADMIN_LIST_CHECKED"),
          // counter of selected elements
          "value"=>"0"),
  )
);
© 2001-2008 Bitrix Bitrix Site Manager


AddGroupActionTable

CAdminList::AddGroupActionTable

void
CAdminList::AddGroupActionTable(
  array $arActions[,
  array $arParams = array()]
)

The AddGroupActionTable method creates a menu of available group actions that can be performed on the list elements. The actions are passes as an array: "action_identifier"=>"action_name".

Parameters

Actions

The actions $arActions can be specified in two ways. The first simple method requires an associated array containing the following pairs: action_identifier => "menu_item_name. In this case, a menu item is a link to the current page with an additional GET parameter: &action=action_identifier which is to be processed when saving changes.

The second method implies that each element of $arActions represents an associated array containing the following keys.

Key | Description
action | Javascript code to be executed whenever a menu item is selected.
type Specifies the action link appearance. Can be one of the following values:
  • button - action will be displayed as a button;
  • html - a text link as specified in the value parameter.
If the parameters is any other value or not defined, the action will be displayed as an drop-down list item.
value | Specifies the action title (menu_item_name for the simple mode).

You can combine the both methods in the same $arActions.

arParams

Action parameters are defined in an associated array with the following keys:

  • disable_action_target - defines the availability of the apply to all checkbox;
  • select_onchange - javascript to be be executed whenever a drop-down list action is selected.

Example (the simple method)

$lAdmin->AddGroupActionTable(Array(
  "delete"    => GetMessage("MAIN_ADMIN_LIST_DELETE"),
  "activate"  => GetMessage("MAIN_ADMIN_LIST_ACTIVATE"),
  "deactivate"=> GetMessage("MAIN_ADMIN_LIST_DEACTIVATE"),
));

Example (the extended method)

// show the form with buttons
$lAdmin->AddGroupActionTable(
  array(
    "delete" => GetMessage("MAIN_ADMIN_LIST_DELETE"),
    "access" => array(
      "action" => "setAccess('".str_replace("'", "\'", $site)."', '".
                             str_replace("'", "\'", $path)."')",
      "value" => "access",
      "name" => GetMessage('FILEMAN_ADMIN_ACCESS_CMD')
    ),
    "copy" => GetMessage("FILEMAN_ADM_COPY"),
    "move" => GetMessage("FILEMAN_ADM_MOVE"),
    "copy2" => array(
      "type" => "html",
      "value" => " ".GetMessage("FILEMAN_ADMIN_IN")." "
    ),
    "copy1" => array(
      "type" => "html",
      "value" => $strHTML
    ),
  ),
  array("select_onchange"=>"this.form.copy_to_button.disabled=this.form.copy_to.disabled=!(this[this.selectedIndex].value == 'copy' || this[this.selectedIndex].value == 'move')")
);
© 2001-2008 Bitrix Bitrix Site Manager


AddGroupError

CAdminList::AddGroupError

void
CAdminList::AddGroupError(
  string $strError[,
  mixed $ID = false]
)

The AddGroupError method registers errors that occur when processing group actions performed on the table rows.

Parameters

Parameter | Description
strError | The error text.
ID | The ID of a row that contains an error.
© 2001-2008 Bitrix Bitrix Site Manager


AddHeaders

CAdminList::AddHeaders

void
CAdminList::AddHeaders(
  array $aHeaders
)

The method AddHeaders creates table columns. Each column is described in an array containing the following keys:

Key | Description
id | The column identifier.
content | The column title.
sort | The value of the GET query parameter. Used for sorting.
default | Specifies whether the column is by default displayed in the list (true|false).

Example:

$lAdmin->AddHeaders(array(
  array(  "id"    =>"ID",
    "content"  =>"ID",
    "sort"     =>"id",
    "default"  =>true,
  ),
  array(  "id"    =>"NAME",
    "content"  =>GetMessage("rub_name"),
    "sort"     =>"name",
    "default"  =>true,
  ),
  array(  "id"    =>"LID",
    "content"  =>GetMessage("rub_site"),
    "sort"     =>"lid",
    "default"  =>true,
  ),
  array(  "id"    =>"SORT",
    "content"  =>GetMessage("rub_sort"),
    "sort"     =>"sort",
    "align"    =>"right",
    "default"  =>true,
  ),
  array(  "id"    =>"ACTIVE",
    "content"  =>GetMessage("rub_act"),
    "sort"     =>"act",
    "default"  =>true,
  ),
  array(  "id"    =>"VISIBLE",
    "content"  =>GetMessage("rub_visible"),
    "sort"     =>"visible",
    "default"  =>true,
  ),
  array(  "id"    =>"AUTO",
    "content"  =>GetMessage("rub_auto"),
    "sort"     =>"auto",
    "default"  =>true,
  ),
  array(  "id"    =>"LAST_EXECUTED",
    "content"  =>GetMessage("rub_last_exec"),
    "sort"     =>"last_executed",
    "default"  =>true,
  ),
));
© 2001-2008 Bitrix Bitrix Site Manager


AddUpdateError

CAdminList::AddUpdateError

void
CAdminList::AddUpdateError(
  string $strError[,
  mixed $ID = false]
)

The AddUpdateError method registers errors that occur when saving changes.

Parameters

Parameter | Description
strError | The error text.
ID | The identifier of the row containing the error.
© 2001-2008 Bitrix Bitrix Site Manager


AddUpdateError

CAdminList::AddUpdateError

void
CAdminList::AddUpdateError(
  string $strError[,
  mixed $ID = false]
)

The method AddUpdateError registers errors that occur when saving changes of the table rows.

Parameters:

Parameter | Description
strError | The error text.
ID | The identifier of the row containing the error.
© 2001-2008 Bitrix Bitrix Site Manager


CheckListMode

CAdminList::CheckListMode

void
CAdminList::CheckListMode(
)

The CheckListMode method examines the required table rendering mode. If the list is to be displayed using AJAX or as an Excel spreadsheet, the script is interrupted and the method renders the table internally.

© 2001-2008 Bitrix Bitrix Site Manager


Display

CAdminList::Display

void
CAdminList::Display(
)

The method Display displays the prepared report table.
© 2001-2008 Bitrix Bitrix Site Manager


DisplayList

CAdminList::DisplayList

void
CAdminList::DisplayList(
)

The method DisplayList displays the prepared report table.

Unlike the Display method, DisplayList adds all the required gadgets (buttons, AJAX rendering etc.) and functions.
© 2001-2008 Bitrix Bitrix Site Manager


EditAction

CAdminList::EditAction

bool
CAdminList::EditAction(
)

The EditAction method returns true if table rows have been edited and changes need to be saved.

Example

// save modified elements
if($lAdmin->EditAction() && $POST_RIGHT=="W")
{
    // walk the list of passed elements
    foreach($FIELDS as $ID=>$arFields)
    {
        // if the elements are not changed - do nothing
        if(!$lAdmin->EditAction($ID))
            continue;

        // save changes of each element
        $DB->StartTransaction();
        $ID = IntVal($ID);
        $cData = new CRubric;
        if(($rsData = $cData->GetByID($ID)) && ($arData = $rsData->Fetch()))
        {
            foreach($arFields as $key=>$value)
                $arData[$key]=$value;
            if(!$cData->Update($ID, $arData))
            {
                $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".$cData->LAST_ERROR, $ID);
                $DB->Rollback();
            }
        }
        else
        {
            $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".GetMessage("rub_no_rubric"), $ID);
            $DB->Rollback();
        }
        $DB->Commit();
    }
}
© 2001-2008 Bitrix Bitrix Site Manager


GroupAction

CAdminList::GroupAction

bool
CAdminList::GroupAction(
)

The GroupAction method returns true if any group action have been performed on the table rows and changes are to be saved.

Example

// process single and group actions
if(($arID = $lAdmin->GroupAction()) && $POST_RIGHT=="W")
{
    // if "apply to all" is selected
    if($_REQUEST['action_target']=='selected')
    {
        $cData = new CRubric;
        $rsData = $cData->GetList(array($by=>$order), $arFilter);
        while($arRes = $rsData->Fetch())
            $arID[] = $arRes['ID'];
    }

    // walk the list of elements
    foreach($arID as $ID)
    {
        if(strlen($ID)<=0)
            continue;
           $ID = IntVal($ID);

        // perform the required action on each element
        switch($_REQUEST['action'])
        {
        // remove
        case "delete":
            @set_time_limit(0);
            $DB->StartTransaction();
            if(!CRubric::Delete($ID))
            {
                $DB->Rollback();
                $lAdmin->AddGroupError(GetMessage("rub_del_err"), $ID);
            }
            $DB->Commit();
            break;

        // activate/deactivate
        case "activate":
        case "deactivate":
            $cData = new CRubric;
            if(($rsData = $cData->GetByID($ID)) && ($arFields = $rsData->Fetch()))
            {
                $arFields["ACTIVE"]=($_REQUEST['action']=="activate"?"Y":"N");
                if(!$cData->Update($ID, $arFields))
                    $lAdmin->AddGroupError(GetMessage("rub_save_error").$cData->LAST_ERROR, $ID);
            }
            else
                $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".GetMessage("rub_no_rubric"), $ID);
            break;
        }

    }
}
© 2001-2008 Bitrix Bitrix Site Manager


InitFilter

CAdminList::InitFilter

void
CAdminList::InitFilter(
  array $arFilterFields
)

The InitFilter method initialises the filter. Here you will find the detailed description of how an administration page with filter is to be created.
© 2001-2008 Bitrix Bitrix Site Manager


IsUpdated

CAdminList::IsUpdated

bool
CAdminList::IsUpdated(
  string $ID
)

The IsUpdated method returns true is any of the table rows have been changed when editing the table rows. The parameter is the table ID

Example

// save modified elements
if($lAdmin->EditAction() && $POST_RIGHT=="W")
{
    // walk the list of elements
    foreach($FIELDS as $ID=>$arFields)
    {
        // unchanged? do nothing
        if(!$lAdmin->IsUpdated($ID))
            continue;

        // otherwise, save changes
        $DB->StartTransaction();
        $ID = IntVal($ID);
        $cData = new CRubric;
        if(($rsData = $cData->GetByID($ID)) && ($arData = $rsData->Fetch()))
        {
            foreach($arFields as $key=>$value)
                $arData[$key]=$value;
            if(!$cData->Update($ID, $arData))
            {
                $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".
                                       $cData->LAST_ERROR, $ID);
                $DB->Rollback();
            }
        }
        else
        {
            $lAdmin->AddGroupError(GetMessage("rub_save_error")." ".
                                   GetMessage("rub_no_rubric"), $ID);
            $DB->Rollback();
        }
        $DB->Commit();
    }
}
© 2001-2008 Bitrix Bitrix Site Manager


CAdminListRow

The CAdminListRow class is used to manage rows of the report tables on the Control Panel pages. To create a CAdminListRow instance, call CAdminList::AddRow which returns a reference to CAdminListRow.

Methods

The class methods allow to configure the format of the row cells format for view and edit modes.

Method | Description
AddField | Adds a generic editing mode field.
AddCheckField | Adds a checkbox field.
AddSelectField | Adds a drop-down list field.
AddInputField | Adds a generic text input field.
AddCalendarField | Adds a date editing field.
AddViewField | Adds a field to a report table cell. Unlike other methods, the field will be displayed in the view mode.
AddEditField | Adds a text edit field.
AddActions | Configures a context menu for table row.

You can add as many fields as required to the same cell.

Example

You can find a detailed example of creating a report table here.

© 2001-2008 Bitrix Bitrix Site Manager


AddActions

CAdminListRow::AddActions

void
CAdminListRow::AddActions(
  array $arActions
)

The AddActions method configures a context menu for table row. The menu parameters are specified as an array whose elements are associated arrays with the following keys.

Key | Description
ICON | The name of the CSS class for the action icon.
DISABLED | Specifies that the menu item is disabled (true|false).
DEFAULT | Specifies that the menu item performs a default action (true|false) when activated.
TEXT | The menu item name.
TITLE | The menu item tooltip text.
ACTION | The action to be performed upon the menu item activation (Javascript).
SEPARATOR | Inserts a separator {true|false}. If true, other keys are ignored.

Example:

// build a context menu
$arActions = Array();

// element editing
$arActions[] = array(
"ICON"=>"edit",
"DEFAULT"=>true,
"TEXT"=>GetMessage("rub_edit"),
"ACTION"=>$lAdmin->ActionRedirect("rubric_edit.php?ID=".$f_ID)
);

// element deletion
if ($POST_RIGHT>="W")
$arActions[] = array(
  "ICON"=>"delete",
  "TEXT"=>GetMessage("rub_del"),
  "ACTION"=>"if(confirm('".GetMessage('rub_del_conf')."')) ".
            $lAdmin->ActionDoGroup($f_ID, "delete")
);

// insert a separator
$arActions[] = array("SEPARATOR"=>true);

// check the template for automatically generated mail lists
if (strlen($f_TEMPLATE)>0 && $f_AUTO=="Y")
$arActions[] = array(
  "ICON"=>"",
  "TEXT"=>GetMessage("rub_check"),
  "ACTION"=>$lAdmin->ActionRedirect("template_test.php?ID=".$f_ID)
);

// if separator comes last, remove it.
if(is_set($arActions[count($arActions)-1], "SEPARATOR"))
unset($arActions[count($arActions)-1]);

// attach context menu to the row
$row->AddActions($arActions);
© 2001-2008 Bitrix Bitrix Site Manager


AddCalendarField

CAdminListRow::AddCalendarField

void
CAdminListRow::AddCalendarField(
  string $ID[,
  array $arAttributes = array()]
)

The AddCalendarField method adds a date editing field. The field is active in the editing mode only.

Parameters

Parameter | Description
ID | The cell identifier.
arAttributes | An array of additional INPUT tag attributes in the format: "attribute" => "value".

Example:

$row->AddCalendarField(
    "DATE",
    array(
        "size" => "15"
    )
);
© 2001-2008 Bitrix Bitrix Site Manager


AddCheckField

CAdminListRow::AddCheckField

void
CAdminListRow::AddCheckField(
  string $ID
)

The AddCheckField method adds a checkbox field. The checkbox is checked is the cell value is "Y". The field is active in the editing mode only.

Parameters

Parameter | Description
ID | The cell identifier.

Example:

// the ACTIVE and VISIBLE flags are edited as checkboxes
$row->AddCheckField("ACTIVE");
$row->AddCheckField("VISIBLE");
© 2001-2008 Bitrix Bitrix Site Manager


AddEditField

CAdminListRow::AddEditField

void
CAdminListRow::AddEditField(
  string $ID,
  string $HTML
)

The AddEditField method adds a text edit field. The field is active in the editing mode only.

Parameters

Parameter | Description
ID | The cell identifier.
HTML | The HTML code to be rendered in a table cell.

Example:

// the AUTO parameter is displayed as "Yes" or "No", bold in the editing mode
$row->AddViewField("AUTO", $f_AUTO == "Y" ? GetMessage("POST_U_YES") :
                                            GetMessage("POST_U_NO"));
$row->AddEditField("AUTO", "<b>".($f_AUTO == "Y" ? GetMessage("POST_U_YES") :
                                                   GetMessage("POST_U_NO"))."</b>");
© 2001-2008 Bitrix Bitrix Site Manager


AddField

CAdminListRow::AddField

void
CAdminListRow::AddField(
  string $ID,
  string $HTML[,
  bool $edit = false]
)

The AddField method adds a generic editing mode field. The field is active in the editing mode only.

Parameters

Parameter | Description
ID | The cell identifier.
HTML | The HTML code to be rendered in the cell in the editing mode.
edit | Specifies that the cell value can be edited. Optional. False by default (cannot be edited).

Example:

$row->AddField(
    "ID",
    '<a href="/bitrix/admin/blog_blog_edit.php?ID='.$f_ID.'&lang='.LANGUAGE_ID.
    '" title="'.GetMessage("BLB_UPDATE_ALT").'">'
    .$f_ID
    .'</a>'
);
© 2001-2008 Bitrix Bitrix Site Manager


AddInputField

CAdminListRow::AddInputField

void
CAdminListRow::AddInputField(
  string $ID[,
  array $arAttributes = array()]
)

The AddInputField method adds a generic text input field. The field is active in the editing mode only.

Parameters

Parameter | Description
ID | The cell identifier.
arAttributes | An array of additional INPUT tag attributes in the format: "attribute" => "value".

Example:

// the NAME parameter is edited as a text and displayed as a link
$row->AddInputField("NAME", array("size"=>20));
$row->AddViewField("NAME", '<a href="rubric_edit.php?ID='.$f_ID.
                           '&lang='.LANG.'">'.$f_NAME.'</a>');
© 2001-2008 Bitrix Bitrix Site Manager


AddSelectField

CAdminListRow::AddSelectField

void
CAdminListRow::AddSelectField(
  string $ID,
  array $arValues[,
  array $arAttributes = array()]
)

The AddSelectField method adds a drop-down list field. The field is active in the editing mode only.

Parameters

Parameter | Description
ID | The cell identifier.
arValues | An array of drop-down list items in the format of "value" => "name".
arAttributes | An array of additional SELECT tag attributes in the format: "attribute" => "value".

Example

$arStatusList = array(
    "Draft" => GetMessage("STATUS_DRAFT"),
    "Published" => GetMessage("STATUS_PUBLISHED"),
);

$row->AddSelectField(
    "STATUS",
    $arStatusList
);
© 2001-2008 Bitrix Bitrix Site Manager


AddViewField

CAdminListRow::AddViewField

void
CAdminListRow::AddViewField(
  string $ID,
  string $HTML
)

The AddViewField method adds a field to a report table cell. The field is active in the view mode only.

Parameters

Parameter | Description
ID | The cell identifier.
HTML | The HTML code to be rendered in a table cell.

Example:

// the NAME parameter is edited as text and displayed as a link
$row->AddInputField("NAME", array("size"=>20));
$row->AddViewField("NAME", '<a href="rubric_edit.php?ID='.$f_ID.
                           '&lang='.LANG.'">'.$f_NAME.'</a>');
© 2001-2008 Bitrix Bitrix Site Manager


CAdminMessage

The CAdminMessage class is used to manage messages used on the Control Panel pages.

Methods

Method | Description
CAdminMessage | The class constructor.
Show | Displays a message.
GetMessages | Receives a message list.

The following methods do not require creating a class instance.

Method | Description
ShowNote | Displays a note.
ShowMessage | Displays a message.
© 2001-2008 Bitrix Bitrix Site Manager


CAdminMessage

CAdminMessage::CAdminMessage

object
CAdminMessage(
 array $arMessage[,
 mixed $exception = false]
)

The CAdminMessage class constructor.

Parameters

Parameter | Description
arMessage An array with the following keys:
  • MESSAGE - the message text;
  • TYPE - the message type ("ERROR" - error message; "OK" - notification);
  • DETAILS - the detailed description;
  • HTML - if true, the error message is HTML and should be rendered as is.
exception | The CApplicationException class instance which provides the error description in case it is not specified in arMessage.

Example:

if($strError)
{
  $aMsg = array();
  $arrErr = explode("<br />",$strError);
  reset($arrErr);
  while (list(,$err)=each($arrErr)) $aMsg[]['text']=$err;

  $e = new CAdminException($aMsg);
  $GLOBALS["APPLICATION"]->ThrowException($e);
  $message = new CAdminMessage(GetMessage("FORM_ERROR_SAVE"), $e);
  echo $message->Show();
}
© 2001-2008 Bitrix Bitrix Site Manager


GetMessages

CAdminMessage::GetMessages

array
CAdminMessage::GetMessages(
)

The GetMessages method obtains an array of messages.

This method can be used to get the messages when a CAdminMessage object is created by passing a CAdminException class instance to the constructor.

© 2001-2008 Bitrix Bitrix Site Manager


Show

CAdminMessage::Show

string
CAdminMessage::Show(
)

The Show method displays a message.

Example:

if($ex = $APPLICATION->GetException())
{
  $message = new CAdminMessage(GetMessage("FORM_ERROR_SAVE"), $ex);
  echo $message->Show();
}
© 2001-2008 Bitrix Bitrix Site Manager


ShowMessage

CAdminMessage::ShowMessage

string
CAdminMessage::ShowMessage(
 string $message
)

The ShowMessage method displays a specified error message.

Example:

if (strlen(strError) > 0)
{
  echo CAdminMessage::ShowMessage($strError);
}
© 2001-2008 Bitrix Bitrix Site Manager


ShowNote

CAdminMessage::ShowNote

string
CAdminMessage::ShowNote(
  string $message
)

The ShowNote method displays a notification.

Example:

echo CAdminMessage::ShowNote('Do not click Back or Refresh in your browser!');
© 2001-2008 Bitrix Bitrix Site Manager


CAdminResult

CAdminResult inherits from CDBResult and overloads some methods so that it can be used with the Control Panel scripts.

© 2001-2008 Bitrix Bitrix Site Manager


CAdminSorting

The CAdminSorting class is used to handle the sorting modes in the report table on the Control Panel pages.

Methods

Method | Description
CAdminSorting | The class constructor.

Example

You can find a detailed example of using the sorting modes in Creating a custom list of elements.

© 2001-2008 Bitrix Bitrix Site Manager


CAdminSorting

CAdminSorting::CAdminSorting

object
CAdminSorting(
   string $table_id[,
   mixed $by_initial = false,
   mixed $order_initial = false,
   string $by_name = "by",
   string $order_name = "order"]
)

This class can sort the rows in a table on a Control Panel page by clicking any column. You can configure the column sorting using CAdminList::AddHeaders.

Parameters

Parameter | Description
table_id | The table identifier.
by_inital | The column identifier by which the default sorting is performed.
order_inital | The default sort order ({'asc'|'desc'}).
by_name | The name of a "GET" variable that will contain the identifier of a sorting column. Optional parameter. 'by' is the default value.
order_name | The name of a "GET" variable that will contain the sort order. Optional parameter. The default name is 'order'.

The initialised class instance is passed to the CAdminList class constructor. Further preparation is accomplished automatically and does not require other actions on your side.

Example

$sTableID = "tbl_rubric"; // the table ID
$oSort = new CAdminSorting($sTableID, "ID", "desc"); // sorting object
$lAdmin = new CAdminList($sTableID, $oSort); // the main list object
© 2001-2008 Bitrix Bitrix Site Manager


CAdminTabControl

CAdminTabControl is used with multi-page tabbed forms.

Methods

Method | Description
CAdminTabControl | The class constructor.
AddTabs | Adds custom tabs.
Begin | Displays tabs and starts an initial page.
BeginNextTab | Completes a previous tab if any and starts a new one.
EndTab | Completes a previously started tab.
Buttons | Adds form submit buttons.
End | Completes tab display.
ActiveTabParam | The method returns a name and a value of "GET" variable containing a tab name that will be activated after the page is loaded.
ShowWarnings | Shows form processing errors by highlighting form fields whose values are invalid.

Example

You can find the detailed example of creating a tabbed form here.

© 2001-2008 Bitrix Bitrix Site Manager


CAdminTabControl

CAdminTabControl::CAdminTabControl

object
CAdminTabControl(
   string $NAME,
   array $aTabs[,
   bool $bCanExpand = true]
)

Constructs a class that implements tabbed forms.

Parameters

Parameter | Description
NAME | A unique page identifier.
aTabs | An array describing the tabs. The array format is described below.
bCanExpand | Specifies that all pages can be expanded to fit in a single view. Optional parameter. The default value is true.

The tabs configuration is passed as an array whose elements are associated arrays with the following keys.

Key | Description
DIV | A unique tab identifier.
TAB | The tab text.
TITLE | The description of a tab page.
ICON | The CSS class of an image (icon) displayed near the page description.
ONSELECT | The JavaScript script that will be executed when the tab is activated.

Example

$aTabs = array(
  array("DIV" => "edit1",
        "TAB" => GetMessage("rub_tab_rubric"),
        "ICON"=>"main_user_edit",
        "TITLE"=>GetMessage("rub_tab_rubric_title")),

  array("DIV" => "edit2",
        "TAB" => GetMessage("rub_tab_generation"),
        "ICON"=>"main_user_edit",
        "TITLE"=>GetMessage("rub_tab_generation_title")),
);

$tabControl = new CAdminTabControl("tabControl", $aTabs);
© 2001-2008 Bitrix Bitrix Site Manager


ActiveTabParam

CAdminTabControl::ActiveTabParam

string
CAdminTabControl::ActiveTabParam(
)

The ActiveTabParam method returns the name and the value of a "GET" variable containing the name of a tab that will be activated after the page is loaded.

Example

The following example redirects a user after processing the form data.

if (strlen($strError)<=0)
{
  // if Save has been clicked, direct to the list
  if (strlen($save)>0)
    LocalRedirect("form_field_list.php?WEB_FORM_ID=".$WEB_FORM_ID.
                  "&additional=". $additional."&lang=".LANGUAGE_ID);
  // if Apply has been clicked, direct back to the form with the last open tab.
  else
    LocalRedirect("form_field_edit_simple.php?".$tabControl->ActiveTabParam().
                  "&ID=".$ID."&WEB_FORM_ID=".$WEB_FORM_ID."&additional=".
                  $additional."&lang=".LANGUAGE_ID);
}
© 2001-2008 Bitrix Bitrix Site Manager


AddTabs

CAdminTabControl::AddTabs

void
CAdminTabControl::AddTabs(
  CAdminTabEngine &$customTabber
)

The method AddTabs adds tabbed pages to a form taking a reference to a CAdminTabEngine class instance as a parameter. See also: creation of custom tabbed forms.

Example

$customTabber = new CAdminTabEngine("OnAdminIBlockElementEdit", array("ID" => $ID));

// ..........................

$tabControl = new CAdminTabControl("tabControl", $aTabs);
$customTabber->SetErrorState($bVarsFromForm);
$tabControl->AddTabs($customTabber);
© 2001-2008 Bitrix Bitrix Site Manager


Begin

CAdminTabControl::Begin

void
CAdminTabControl::Begin(
)

The Begin method displays the tab bar and starts an initial property page.

Example

<?
$aTabs = array(
  array("DIV" => "edit1",
        "TAB" => GetMessage("rub_tab_rubric"),
        "ICON"=>"main_user_edit",
        "TITLE"=>GetMessage("rub_tab_rubric_title")),
  array("DIV" => "edit2",
        "TAB" => GetMessage("rub_tab_generation"),
        "ICON"=>"main_user_edit",
        "TITLE"=>GetMessage("rub_tab_generation_title")),
);
$tabControl = new CAdminTabControl("tabControl", $aTabs);
?>
<?
// display tab titles
$tabControl->Begin();
?>
© 2001-2008 Bitrix Bitrix Site Manager


BeginNextTab

CAdminTabControl::BeginNextTab

void
CAdminTabControl::BeginNextTab(
)

The method BeginNextTab completes a previously started tab (if any has been started) and starts a new page.

Example

<?
// display tab titles
$tabControl->Begin();
?>
<?
//********************
// the first tab is a mail list editing form
//********************
$tabControl->BeginNextTab();
?>
  <tr>
    <td width="40%"><?echo GetMessage("rub_act")?></td>
    <td width="60%"><input type="checkbox"
                           name="ACTIVE"
                           value="Y"<?if($str_ACTIVE == "Y") echo " checked"?>></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_visible")?></td>
    <td><input type="checkbox"
               name="VISIBLE"
               value="Y"<?if($str_VISIBLE == "Y") echo " checked"?>></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_site")?></td>
    <td><?echo CLang::SelectBox("LID", $str_LID);?></td>
  </tr>
  <tr>
    <td><span class="required">*</span><?echo GetMessage("rub_name")?></td>
    <td><input type="text"
               name="NAME"
               value="<?echo $str_NAME;?>" size="30" maxlength="100"></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_sort")?></td>
    <td><input type="text"
               name="SORT" value="<?echo $str_SORT;?>" size="30"></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_desc")?></td>
    <td><textarea class="typearea"
                  name="DESCRIPTION" cols="45" rows="5"
                  wrap="VIRTUAL"><?echo $str_DESCRIPTION; ?></textarea></td>
  </tr>
  <tr>
    <td><?echo GetMessage("rub_auto")?></td>
    <td><input type="checkbox"
               name="AUTO"
               value="Y"<?if($str_AUTO == "Y") echo " checked"?>
               OnClick="if (this.checked)
                            tabControl.EnableTab('edit2');
                        else tabControl.DisableTab('edit2');"></td>
  </tr>
<?
//********************
// second tab
//********************
$tabControl->BeginNextTab();
?>
© 2001-2008 Bitrix Bitrix Site Manager


Buttons

CAdminTabControl::Buttons

void
CAdminTabControl::Buttons([
 mixed $arParams = false
])

The Buttons method displays a standard form submit buttons and closes started tabs if any has been started.

Parameters

Parameter Description
arParams An array of additional parameters. Can contain the following keys:
  • disabled - if true, form submit buttons will be disabled.
  • back_url - the return page URL. If a visitor clicks Cancel, the system will opens this URL.
If the parameter value is not specified (or the value is false), the method will close all tabs not adding the standard form submit buttons. In this case, you can create them manually.

Example

<?
// close the form - display the save buttons
$tabControl->Buttons(
  array(
    "disabled" => ($POST_RIGHT < "W"),
    "back_url" => $_REQUEST["back_url"],
  )
);
?>

<?
// close the form not adding the buttons
$tabControl->Buttons();
?>
<input class="mybutton" type="submit" name="save" value="Click me!!!! ;-)" title="My save button" />&nbsp;
<input class="mybutton" type="button" name="foo" value="Click me too!" onClick="alert('Hello, world!')" />
<?
$tabControl->End();
?>
© 2001-2008 Bitrix Bitrix Site Manager


End

CAdminTabControl::End

void
CAdminTabControl::End(
)

The End method closes the tabbed form output. If any tabs were previously started, they are closed.

Example

<?
// close the form - display the save buttons
$tabControl->Buttons(
  array(
    "disabled"=>($POST_RIGHT<"W"),
    "back_url"=>"rubric_admin.php?lang=".LANG,
  )
);
?>
<?
// complete the tab interface
$tabControl->End();
?>
© 2001-2008 Bitrix Bitrix Site Manager


EndTab

CAdminTabControl::EndTab

void
CAdminTabControl::EndTab(
)

The EndTab method closes the current tab page. The method is called automatically in BeginNextTab, Buttons and End.

© 2001-2008 Bitrix Bitrix Site Manager


ShowWarnings

CAdminTabControl::ShowWarnings

void
CAdminTabControl::ShowWarnings(
    string $FORM,
    CAdminException $messages[,
    mixed $arFields = false]
)

The ShowWarnings method highlights fields whose values was considered invalid during form processing.

Parameters

Parameter | Description
FORM | The value of the NAME attribute of the FORM tag.
messages | A CAdminException class instance containing error messages.
arFields | An associated array in the format: "invalid_parameter_id" => "form_field_name". Optional parameter. By default, the system searches fields whose names match the invalid parameter ID.

Example

if($e = $APPLICATION->GetException())
  $message = new CAdminMessage(GetMessage("currency_error"), $e);

if($message)
  echo $message->Show();

<form method="post" action="<?$APPLICATION->GetCurPage()?>" name="form1">

<!-- form -->

</form>

<?$tabControl->ShowWarnings("form1", $message);?>
© 2001-2008 Bitrix Bitrix Site Manager


CAdminTabEngine

CAdminTabEngine is a class used to create and manage custom tabs. You can find more information about the creation of custom tab forms here.

Methods

Method | Description
CAdminTabEngine | The class constructor.
SetErrorState | Sets the value of the "Data obtained from a form on error" flag.
SetArgs | Sets additional parameters that will be passed to the custom tab handlers.
Check | Calls the custom tab handlers to validate the form data.
Action | Calls the tab handlers to process the form data.
GetTabs | Obtains the tab configuration information by calling the custom tab handlers.
ShowTab | Calls custom tab handlers to obtain the HTML code of their pages.

Example

You can find the detailed example of creating custom tabs here.

© 2001-2008 Bitrix Bitrix Site Manager


CAdminTabEngine

CAdminTabEngine::CAdminTabEngine

object
CAdminTabEngine(
   string $EVENT_NAME[,
   array $aArgs = array()]
)

The class constructor allows to create custom tabs in multi-page forms.

Parameters

Parameter | Description
EVENT_NAME | The name of an event for which custom tabs have been configured.
aArgs | An array of additional arguments passed to the tab handlers.

Example

$customTabber = new CAdminTabEngine("OnAdminSaleOrderEdit", array("ID" => $ID));
$tabControl = new CAdminTabControl("tabControl", $aTabs);
$customTabber->SetErrorState($bVarsFromForm);
$tabControl->AddTabs($customTabber);
© 2001-2008 Bitrix Bitrix Site Manager


Action

CAdminTabEngine::Action

bool
CAdminTabEngine::Action(
)

The Action method calls the tab handlers to process the form data. The system always calls all of the handlers even if one of the them fails.

Example

if (!$customTabber->Action())
{
  if ($ex = $APPLICATION->GetException())
    $errorMessage .= $ex->GetString();
  else
    $errorMessage .= "Error. ";
}
© 2001-2008 Bitrix Bitrix Site Manager


Check

CAdminTabEngine::Check

bool
CAdminTabEngine::Check(
)

The Check method calls the custom tab handlers to validate the form data. If an error occurs in one of the handlers, the other handlers are called anyway.

Example

if (!$customTabber->Check())
{
  if ($ex = $APPLICATION->GetException())
    $errorMessage .= $ex->GetString();
  else
    $errorMessage .= "Error. ";
}
© 2001-2008 Bitrix Bitrix Site Manager


GetTabs

CAdminTabEngine::GetTabs

array
CAdminTabEngine::GetTabs(
)

The GetTabs method obtains the tab configuration information by calling the custom tab handlers. It calls CAdminTabControl::AddTabs automatically.

© 2001-2008 Bitrix Bitrix Site Manager


SetArgs

CAdminTabEngine::SetArgs

void
CAdminTabEngine::SetArgs([
  array $arArgs = array()
])

The SetArgs method sets additional parameters that will be passed to the custom tab handlers. This method sets the same parameters as the second parameter of the class constructor.

© 2001-2008 Bitrix Bitrix Site Manager


SetErrorState

CAdminTabEngine::SetErrorState

void
CAdminTabEngine::SetErrorState([
  bool $bVarsFromForm = false
])

The method SetErrorState is used to set the state of the "Data obtained from a form on error" flag. The value is passed to the custom tab handlers.

Example

$customTabber = new CAdminTabEngine("OnAdminSaleOrderEdit", array("ID" => $ID));
$tabControl = new CAdminTabControl("tabControl", $aTabs);
$customTabber->SetErrorState($bVarsFromForm);
$tabControl->AddTabs($customTabber);
© 2001-2008 Bitrix Bitrix Site Manager


ShowTab

CAdminTabEngine::ShowTab

void
CAdminTabEngine::ShowTab(
  string $tabName
)

The ShowTab method calls custom tab handlers to obtain the HTML code of their pages. Accepts a tab identifier as a parameter. The method is called automatically in CAdminTabControl::BeginNextTab.
© 2001-2008 Bitrix Bitrix Site Manager


Classes

The system kernel is built on functions, events and the following classes.

Class | Description
CMain | Represents a page.
CDatabase | Used to work with the database.
CDBResult | Represents the result of a database query.
CAgent | Class to handle agent functions.
CEvent | Class to handle mail events.
CEventMessage | Class to deal with mail templates.
CEventType | Class to handle mail event types.
CFile | Used to handle files and images.
CUser | Class to deal with the user-specific information.
CGroup | Class to deal with the user groups.
CSite | Used to manage sites.
CLanguage | Class to handle languages of the system.
CMainPage | Class for use with index page.
CMenu | Class to handle menu.
CModule | Class to handle modules.
COption | Class to handle module parameters stored in the database.
CPageOption | Class to handle page parameters.
CPageCache | Used to cache the HTML result of the script execution.
CPHPCache | Used to cache PHP variables and HTML results of script execution.
© 2001-2005 Bitrix Bitrix Site Manager


CAgent

CAgent is the class to handle agent functions.

Class methods

AddAgent | Registers a new agent function.
CheckAgents | Executes the agent function.
Delete | Takes the ID of an agent function and removes it from the agent registrar table.
RemoveAgent | Removes the specified agent function from the agent registrar table.
RemoveModuleAgents | Removes all the agent functions of the specified module from the agents registrar table.

See Also

  • Agents


AddAgent

CAgent::AddAgent

The method AddAgent registers a new agent function.

mixed
CAgent::AddAgent(
 string name,
 string module = "",
 string period = "N",
 int interval = 86400,
 string datecheck = "",
 string active = "Y",
 string next_exec = "",
 int sort = 100
)

Parameters

Parameter | Description
name | PHP string to launch agent function.
module | The module ID. Required to include the module files. Optional. Empty by default.
period If "Y", the time of the next run of agent (next_exec) is calculated as follows:
next_exec = next_exec + interval
At the next run, if the amount of time elapsed is more than the interval value, the agent will be run as many times as it was to with respect to the amount of time it failed to run. Then, when next_exec will achieve or exceed the current time it will be further run according to the interval value. Usually this rule applies to agents which are to be run the required number of times with no fail.

If "N", the time of the next run of agent (next_exec) is calculated as follows:
next_exec = time of the last run + interval
After the first run the agent will be further run according to the interval value. Optional, "N" by default.
interval Interval (in seconds) at which the agent is to be run.
Optional. 86400 (24 hours) by default.
datecheck The time of the first check for the agent pending state, in the format of the current language.
Optional. The current time by default.
active Specifies whether the agent is active or not (Y|N).
Optional. "Y" (active) by default.
next_exec The time of the first run of the agent in the format of the current language.
Optional. The current time by default.
sort The sort weight allows to define the priority of run of this agent in respect to the other agents.
Optional. 100 by default.

Return Values

Returns the ID of the added agent on success, or false otherwise.

See Also

  • Agents
  • CAgent::RemoveAgent
  • CAgent::RemoveModuleAgents
  • Structure of files

Example

<?
// add agent of the Statistics module
CAgent::AddAgent(
    "CStatistic::CleanUpStatistics_2();", // function name
    "statistic",                          // module ID
    "N",                                  // the agent is not critical to number of runs
    86400,                                // interval of run is 24 hours
    "07.04.2005 20:03:26",                // time of the first check of the run
    "Y",                                  // the agent is active
    "07.04.2005 20:03:26",                // time of the first run
    30);
?>
<?
// add agent of the Techsupport module
CAgent::AddAgent(
    "CTicket::AutoClose();",  // function name
    "support",                // module ID
    "N",                      // the agent is not critical to number of runs
    86400,                    // interval of run is 24 hours
    "",                       // time of the first check of the run is current
    "Y",                      // the agent is active
    "",                       // time of the first run is current
    30);
?>
<?
// add an arbitrary agent not belonging to any of modules
CAgent::AddAgent("My_Agent_Function();");
?>

<?
// file /bitrix/php_interface/init.php

function My_Agent_Function()
{
   // perform any actions
   return "My_Agent_Function();";
}
?>
<?
// add an arbitrary agent of the module
// with the ID my_module

CAgent::AddAgent(
   "CMyModule::Agent007(1)",
   "my_module",
   "Y",
    86400);
?>

<?
// this agent will be run 7 times once per 24 hours,
// after that it will be removed from the agent table.

Class CMyModule
{
   function Agent007($cnt=1)
   {
      echo "Hello!";
      if($cnt>=7)
         return "";
      return "CMyModule::Agent007(".($cnt+1).")";
   }
}
?>


CheckAgents

CAgent::CheckAgents

CAgent::CheckAgents()

The method CheckAgents executes the agent function for which the time to be run has come. The function is automatically called at the start of every page and needs not to be called manually.

Parameters

No parameters.

See Also

  • Agents


CAgent::Delete

CAgent::Delete(
 int id
)

The method Delete deletes an agent function from the agent registrar table by its ID.

Parameters

Parameter | Description
id | The ID of an agent to be deleted.

See Also

  • Agents
  • CAgent::RemoveAgent
  • CAgent::RemoveModuleAgents

Example

<?
if (CAgent::Delete(34)) echo "Agent #34 has been successfully deleted.";
?>


RemoveAgent

CAgent::RemoveAgent

CAgent::RemoveAgent(
 string name,
 string module=""
)

Removes the agent function from the agent registrar table.

Parameters

Parameter | Description
name | The agent function.
module | Module ID. Optional. The kernel module is used by default ("main").

See Also

  • Agents
  • CAgent::RemoveModuleAgents
  • CAgent::Delete

Example

<?
CAgent::RemoveAgent("CCatalog::PreGenerateXML(\"google\");", "catalog");
if ($bNeedAgent)
{
    CAgent::AddAgent("CCatalog::PreGenerateXML(\"google\");", "catalog", "N", 24*60*60, "", "Y");
}
?>


RemoveModuleAgents

CAgent::RemoveModuleAgents

CAgent::RemoveModuleAgents(
 string module
)

Removes all the agent functions of the specified module from the agents registrar table.

Parameters

Parameter | Description
module | The module ID.

See Also

  • Agents
  • CAgent::RemoveAgent
  • CAgent::Delete

Example

<?
CAgent::RemoveModuleAgents("statistic");
?>


CApplicationException

CApplicationException is the class to handle exceptions.

Methods

Method | Description
CApplicationException | Raises an exception.
GetString | Returns the exception description.

See Also

  • CMain::ThrowException


CApplicationException

CApplicationException(
 string msg,
 mixed id = false
)

Creates an instance of the CApplicationException class with the text msg and the code id.

Parameters

Parameter | Description
msg | Error description.
id | The error ID.

Remarks

To raise exceptions it is recommended to call $APPLICATION->ThrowException directly. This constructor is mainly intended as the template for the custom exception classes inherited from CApplicationException.

See Also

  • CMain::ThrowException

Example

<?
$exception = new CApplicationException("File is not found", BX_E_FILE_NOT_FOUND);
$APPLICATION->ThrowException($exception);
?>


GetString

CApplicationException::GetString

string
CApplicationException::GetString()

The method GetString returns the exception description.

Parameters

No parameters.

See Also

  • CApplicationException
  • CMain::ThrowException

Example

<?
$DB->StartTransaction();
if(!$langs->Delete($del_id))
{
  $DB->Rollback();
  if($ex = $APPLICATION->GetException())
    $strError = $ex->GetString();
}
else
  $DB->Commit();
?>


CBitrixComponent

The CBitrixComponent class works as a component wrapper. For each component instance, a separate instance of CBitrixComponent is created, which exists until the component instance is destroyed. Inside the component, methods of this class can be accessed via the alias $this.

© 2001-2007 Bitrix Bitrix Site Manager


AbortResultCache

CBitrixComponent::AbortResultCache

void
AbortResultCache();

This helper method is used by components for internal caching.

It is used if the data fetching procedure figured it out that it is not necessary to cache data.

For example, if there is no news with the required ID, caching should be stopped and a warning message is to be displayed. If caching is not interrupted, malicious persons can increase cache size up to a maximum possible value, thereby calling the page with arbitrary ID's.

Example

// Check and initialize input parameters
if ($arParams["ID"] <= 0)
    $arParams["ID"] = 10;

// If there is no valid cache (data is to be queried and
// a valid cache is to be created)
if ($this->StartResultCache())
{
    // Query data and fill in $arResult
    $arResult = array(
        "ID" => rand(1, 100)
    );

    for ($i = 0; $i < 5; $i++)
        $arResult["FIELDS"][] = rand(1, 100);

    // If any condition is true,
       // do not cache data
    if ($arParams["ID"] < 10)
        $this->AbortResultCache();

    // Include the display template
    $this->IncludeComponentTemplate();
}

// Set the page heading using the delay function
$APPLICATION->SetTitle($arResult["ID"]);

See Also

  • CBitrixComponent::StartResultCache
  • CBitrixComponent::ClearResultCache
    • © 2001-2007 Bitrix Bitrix Site Manager


AddIncludeAreaIcon

CBitrixComponent::AddIncludeAreaIcon

void
AddIncludeAreaIcon(
 array arIcon
);

The method adds a new button to component buttons that are displayed in the component area in the site editing mode.

Parameters

Parameter Description
arIcon An array describing the button in the format:
array(
    'URL'   => "javascript:alert('Button');",
    'SRC'   => $this->GetPath().'/images/znak.gif',
    'TITLE' => "Button"
)

Example

$this->AddIncludeAreaIcon(
    array(
        'URL'   => "javascript:alert('It's a new button for ".$this->GetName()."');",
        'SRC'   => $this->GetPath().'/images/znak.gif',
        'TITLE' => "It's a new button"
    )
);

See Also

  • CBitrixComponent::AddIncludeAreaIcons
    • © 2001-2007 Bitrix Bitrix Site Manager


AddIncludeAreaIcons

CBitrixComponent::AddIncludeAreaIcons

void
AddIncludeAreaIcons(
 array arIcons
);

The method adds an array of new buttons to component buttons that are displayed in the component area in the site editing mode. Calling AddIncludeAreaIcons dismisses all previous calls to AddIncludeAreaIcons and AddIncludeAreaIcon.

Parameters

Parameter Description
arIcons An array containing arrays that describe the button. Each of arrays describing the button has the following format:
array(
    'URL'   => "javascript:alert('It's a new button');",
    'SRC'   => $this->GetPath().'/images/znak.gif',
    'TITLE' => "It's a new button"
)

Example

$this->AddIncludeAreaIcons(
    array(
        array(
            'URL' => "javascript:alert('It's a new button for ".$this->GetName()."');",
            'SRC' => $this->GetPath().'/images/znak.gif',
            'TITLE' => "It's a new button"
        ),
        array(
            'URL' => "javascript:alert('It's another button for ".$this->GetName()."');",
            'SRC' => $this->GetPath().'/images/znak1.gif',
            'TITLE' => "It's another button"
        ),
    )
);

See Also

  • CBitrixComponent::AddIncludeAreaIcon
    • © 2001-2007 Bitrix Bitrix Site Manager


ClearResultCache

CBitrixComponent::ClearResultCache

bool
ClearResultCache(
 string additionalCacheID [,
 string cachePath]]
);

The internal caching helper method.

Used if the cache has to be cleared due to any external event. For example, when certain information is modified.

Parameters

Parameter | Description
additionalCacheID | The cache depends on the current site (SITE_ID), component name, file path and input parameters $arParams. If the cache is to depend on any other parameters, they must be specified here as a string. By default, the parameter is false, i.e. cache only depends on the current site SITE_ID, component name, path to the file and input parameters $arParams.
cachePath | Path to the cache file relative to the cache folder. By defult - "/".SITE_ID.<path to the component relative to bitrix/components>.

See Also

  • CBitrixComponent::StartResultCache
  • CBitrixComponent::AbortResultCache
    • © 2001-2007 Bitrix Bitrix Site Manager


GetName

CBitrixComponent::GetName

string
GetName();

The method returns the component name.

Example

$name = $this->GetName();
© 2001-2007 Bitrix Bitrix Site Manager


GetParent

CBitrixComponent::GetParent

object &
GetParent();

The method returns a reference to the parent compound component object.

Example

$parent = & $this->GetParent();
$parentName = $parent->GetName();
© 2001-2007 Bitrix Bitrix Site Manager


GetPath

CBitrixComponent::GetPath

string
GetPath();

The method returns the path to the component folder relative to the site root.

Example

$path = $this->GetPath();
© 2001-2007 Bitrix Bitrix Site Manager


GetRelativePath

CBitrixComponent::GetRelativePath

string
GetRelativePath();

The method returns the path to the component folder relative to the /bitrix/components folder.

Example

$relativePath = $this->GetRelativePath();
© 2001-2007 Bitrix Bitrix Site Manager


GetTemplate

CBitrixComponent::GetTemplate

object &
GetTemplate();

The method returns a reference to the component template object. The component template is valid only after calling IncludeComponentTemplate or InitComponentTemplate. Before calling these methods, a reference to null is returned.

Example

$template = & $this->GetTemplate();
$tamplateFile = $template->GetFile();
© 2001-2007 Bitrix Bitrix Site Manager


GetTemplateCachedData

CBitrixComponent::GetTemplateCachedData

mixed
GetTemplateCachedData();

The GetTemplateCachedData method is called if the standard caching mechanism is not used, but calls to IncludeComponentTemplate are cached. This method returns data that are to be saved in cache, and then restored from cache and returned to the template using SetTemplateCachedData.

Example

// Check and initialize input parameters
if ($arParams["ID"] <= 0)
   $arParams["ID"] = 10;

$arParams["CACHE_TIME"] = IntVal($arParams["CACHE_TIME"]);
$CACHE_ID = SITE_ID."|".$APPLICATION->GetCurPage()."|";
// cache depends only on the prepared parameters without "~"
foreach ($this->arParams as $k => $v)
    if (strncmp("~", $k, 1))
        $CACHE_ID .= ",".$k."=".$v;
$CACHE_ID .= "|".$USER->GetGroups();

$cache = new CPageCache;
if ($cache->StartDataCache($arParams["CACHE_TIME"],
                           $CACHE_ID,
                           "/".SITE_ID.$this->GetRelativePath()))
{
    // Query data and form the $arResult array
    $arResult = array("a" => 1, "b" => 2);

    // Include the component template
    $this->IncludeComponentTemplate();

    $templateCachedData = $this->GetTemplateCachedData();

    $cache->EndDataCache(
        array(
            "arResult" => $arResult,
            "templateCachedData" => $templateCachedData
        )
    );
}
else
{
    extract($cache->GetVars());
    $this->SetTemplateCachedData($templateCachedData);
}

See Also

  • Component caching
  • CBitrixComponent::SetTemplateCachedData
    • © 2001-2007 Bitrix Bitrix Site Manager


GetTemplateName

CBitrixComponent::GetTemplateName

string
GetTemplateName();

The method returns the component template name as it was specified when including the component.

Example

$name = $this->GetTemplateName();
© 2001-2007 Bitrix Bitrix Site Manager


GetTemplatePage

CBitrixComponent::GetTemplatePage

string
GetTemplatePage();

The method returns the component template page name.

Example

$name = $this->GetTemplatePage();
© 2001-2007 Bitrix Bitrix Site Manager


IncludeComponentTemplate

CBitrixComponent::IncludeComponentTemplate

void
IncludeComponentTemplate([
 string templatePage]
);

The method initializes and includes the component template. If the template initialization fails, error is displayed.

Parameters

Parameter | Description
templatePage | The name of a component template page. For compound components, this parameter must be specified. For simple components, it may be an empty string or may be omitted.

Example

$this->IncludeComponentTemplate();

See Also

  • CBitrixComponent::InitComponentTemplate
  • CBitrixComponent::ShowComponentTemplate
    • © 2001-2007 Bitrix Bitrix Site Manager


InitComponentTemplate

CBitrixComponent::InitComponentTemplate

bool
InitComponentTemplate([
 string templatePage]
);

The method initializes the component template. After calling this method, a template object can be obtained using CBitrixComponent::GetTemplate. In this case, the component template is included using CBitrixComponent::ShowComponentTemplate.

If the component does not require template, use CBitrixComponent::IncludeComponentTemplate which initializes and includes the template at a single call.

Parameters

Parameter | Description
templatePage | The name of a component template page. For compound components, this parameter must be specified. For simple components, it may be an empty string or may be omitted.

Return Values

Returns true on success, or false otherwise.

Example

if ($this->InitComponentTemplate($templatePage))
{
    $template = & $this->GetTemplate();
    $folderPath = $template->GetFolder();
    if (strlen($folderPath) > 0)
    {
        * * *
    }
    $this->ShowComponentTemplate();
}

See Also

  • CBitrixComponent::ShowComponentTemplate
  • CBitrixComponent::GetTemplate
  • CBitrixComponent::IncludeComponentTemplate
    • © 2001-2007 Bitrix Bitrix Site Manager


SetTemplateCachedData

CBitrixComponent::SetTemplateCachedData

void
SetTemplateCachedData(
 mixed templateCachedData
);

The SetTemplateCachedData method is called if the proprietary component caching mechanism is not used, but calls to CBitrixComponent::IncludeComponentTemplate is cached. This method returns data that were saved in cache.

Example

// Check and initialize input parameters
if ($arParams["ID"] <= 0)
   $arParams["ID"] = 10;

$arParams["CACHE_TIME"] = IntVal($arParams["CACHE_TIME"]);
$CACHE_ID = SITE_ID."|".$APPLICATION->GetCurPage()."|";
// cache depends only on the prepared parameters without "~"
foreach ($this->arParams as $k => $v)
    if (strncmp("~", $k, 1))
        $CACHE_ID .= ",".$k."=".$v;
$CACHE_ID .= "|".$USER->GetGroups();

$cache = new CPageCache;
if ($cache->StartDataCache($arParams["CACHE_TIME"], $CACHE_ID, "/".SITE_ID.$this->GetRelativePath()))
{
    // Query data and form the $arResult array
    $arResult = array("a" => 1, "b" => 2);

    // Include the component template
    $this->IncludeComponentTemplate();

    $templateCachedData = $this->SetTemplateCachedData();

    $cache->EndDataCache(
        array(
            "arResult" => $arResult,
            "templateCachedData" => $templateCachedData
        )
    );
}
else
{
    extract($cache->GetVars());
    $this->SetTemplateCachedData($templateCachedData);
}

See Also

  • Component caching
  • CBitrixComponent::GetTemplateCachedData
    • © 2001-2007 Bitrix Bitrix Site Manager


ShowComponentTemplate

CBitrixComponent::ShowComponentTemplate

void
ShowComponentTemplate();

The method connects the component template. Before calling this method, the template must be initialized by CBitrixComponent::InitComponentTemplate.

If the component does not require template, use CBitrixComponent::IncludeComponentTemplate which initializes and includes the template at a single call.

Example

if ($this->InitComponentTemplate($templatePage))
{
    $template = & $this->GetTemplate();
    $folderPath = $template->GetFolder();
    if (strlen($folderPath) > 0)
    {
        * * *
    }
    $this->ShowComponentTemplate();
}

See Also

  • CBitrixComponent::GetTemplate
    • © 2001-2007 Bitrix Bitrix Site Manager


StartResultCache

CBitrixComponent::StartResultCache

bool
StartResultCache([
 int cacheTime [,
 string additionalCacheID [,
 string cachePath]]]
);

This helper method is used by components for internal caching.

If the cache is valid, the method displays its contents, fills in $arResult and returns False. If the cache is not valid, the method returns True, caching completes and the cache is saved when calling CBitrixComponent::IncludeComponentTemplate or CBitrixComponent::ShowComponentTemplate upon including the component template.

Parameters

Parameter | Description
cacheTime | Cache valid period, in seconds. If the parameter is false, the period is taken from the $arParams["CACHE_TIME"] input parameter.
additionalCacheID | The cache depends on the current site (SITE_ID), component name, path to the file and input parameters $arParams. If there are any other parameters on which the cache should depend, they must be specified here as a string. By default, the parameter is false which means that the cache only depends on the current site SITE_ID, component name, path to the file and input parameters $arParams.
cachePath | Path to the cache file relative to the cache folder. By default - "/".SITE_ID.<path to the component relative to bitrix/components>.

Return Values

Returns true on success, or false otherwise.

Example

// Check and initialize input parameters
if ($arParams["ID"] <= 0)
    $arParams["ID"] = 10;

// If there is no valid cache, query data and
// a valid cache is to be created
if ($this->StartResultCache())
{
    // Query data and fill in $arResult
    $arResult = array(
        "ID" => rand(1, 100)
    );

    for ($i = 0; $i < 5; $i++)
        $arResult["FIELDS"][] = rand(1, 100);

    // If any condition is true,
    // it is not necessary to cache data
    if ($arParams["ID"] < 10)
        $this->AbortResultCache();

    // Include output template
    $this->IncludeComponentTemplate();
}

// Set the page title using the delay
// function
$APPLICATION->SetTitle($arResult["ID"]);

// cache has to depend on user groups
// where the user is a member
if ($this->StartResultCache(false, $USER->GetGroups()))
{
   // There is no valid cache.
   // Fetch data from the data base into
   // $arResult
}

See Also

  • CBitrixComponent::AbortResultCache
  • CBitrixComponent::ClearResultCache
    • © 2001-2007 Bitrix Bitrix Site Manager


Класс CBitrixComponentTemplate

CBitrixComponentTemplate

The CBitrixComponentTemplate class is a component template wrapper. For each component template, a separate instance of CBitrixComponent is created, which exists until the component instance is destroyed.

To access methods of this class inside the component (after the template is initialized), obtain the template instance handle using the CBitrixComponent::GetTemplate method:

$template = & $this->GetTemplate();
$templateFile = $template->GetFile();
© 2001-2007 Bitrix Bitrix Site Manager


GetFile

CBitrixComponentTemplate::GetFile

string
GetFile();

The method returns the path to the template file relative to the site root.

Example

// In the component code
В коде компонента
$template = & $this->GetTemplate();
$templateFile = $template->GetFile();
© 2001-2007 Bitrix Bitrix Site Manager


GetFolder

CBitrixComponentTemplate::GetFolder

string
GetFolder();

The method returns the path to the template folder relative to the site root, if the template resides in a folder. If the template is a file, the method returns an empty string.

Example

// In the component code
$template = & $this->GetTemplate();
$templateFolder = $template->GetFolder();
© 2001-2007 Bitrix Bitrix Site Manager


GetName

CBitrixComponentTemplate::GetName

string
GetName();

The method returns the component template name.

Example

// In the component code
$template = & $this->GetTemplate();
$templateName = $template->GetName();
© 2001-2007 Bitrix Bitrix Site Manager


GetSiteTemplate

CBitrixComponentTemplate::GetSiteTemplate

string
GetSiteTemplate();

The method returns the site template where the component template reside. If it is a system component template (that is, it exists in the component folder), an empty string is returned.

Example

// In the component code
$template = & $this->GetTemplate();
$siteTemplate = $template->GetSiteTemplate();
© 2001-2007 Bitrix Bitrix Site Manager


Класс CComponentEngine

CComponentEngine class

The CComponentEngine class encapsulates helper methods that can be used for component development.

© 2001-2007 Bitrix Bitrix Site Manager


InitComponentVariables

CComponentEngine::InitComponentVariables

void
InitComponentVariables(
 string componentPage ,
 array arComponentVariables ,
 array arVariableAliases ,
 array & arVariables
);

The method is used with aliases of variables in compound components (also with human-friendly URL's). This method restores original variable values from $_REQUEST based on their aliases.

Parameters

Parameter | Description
componentPage | For human-friendly URL's: code of the path template that was obtained using CComponentEngine::ParseComponentPath. For non human friendly URL's, this parameters must be false.
arComponentVariables | An array of variable names which the component may obtain from the query. This parameter has the following format: array("variable name 1", "variable name 2", ...).
arVariableAliases An array of variable aliases.

The parameter has the following format for human-friendly URL's:
array(
    "code of the path template 1" => array(
        "variable name 11" => "variable alias 11",
        "variable name 12" => "variable alias 12",
        * * *
    ),
    "code of the path template 2" => array(
        "variable name 21" => "variable alias 21",
        "variable name 22" => "variable alias 22",
        * * *
    ),
    * * *
)
For non human friendly URL's:
array(
    "variable name" => "variable alias",
    * * *
)
arVariables | A variable in which all restored variables are returned.

Example

// For human friendly URL's

// Store values of original variables in this variable
$arVariables = array();

// Build an array of path templates from such array...
// "by default" $arDefaultUrlTemplates404
// and an array passed in $arParams["SEF_URL_TEMPLATES"]
$arUrlTemplates =
    CComponentEngine::MakeComponentUrlTemplates($arDefaultUrlTemplates404,
                                                $arParams["SEF_URL_TEMPLATES"]);

// Build an array of variable aliases from such array...
// "by default" $arDefaultVariableAliases404
// and an array passed in $arParams["VARIABLE_ALIASES"]
$arVariableAliases =
    CComponentEngine::MakeComponentVariableAliases($arDefaultVariableAliases404,
                                                   $arParams["VARIABLE_ALIASES"]);

// Define the template code
// to which the current queried page corresponds
$componentPage = CComponentEngine::ParseComponentPath(
    $arParams["SEF_FOLDER"],
    $arUrlTemplates,
    $arVariables
);

// If the requested page does not correspond to any template
// specify the contents explicitly
if (StrLen($componentPage) <= 0)
    $componentPage = "list";

// Now that we have the code of the path template and variables
// that were passed as the path to a requested
// page, register in $arVariables

// Restore the variables that were passed in the query parameters
// and append them to $arVariables
CComponentEngine::InitComponentVariables($componentPage,
                                         $arComponentVariables,
                                         $arVariableAliases,
                                         $arVariables);

// Now, based on the code of the path template $componentPage
// and original variables $arVariables
// define which page of the component template should be displayed

if ($componentPage == "element")
    $componentPage = "element";
elseif ($componentPage == "section1" || $componentPage == "section2")
    $componentPage = "section";
else
    $componentPage = "list";

$this->IncludeComponentTemplate(
    array(
        "FOLDER" => $arParams["SEF_FOLDER"],
        "URL_TEMPLATES" => $arUrlTemplates,
        "VARIABLES" => $arVariables,
        "ALIASES" => $arVariableAliases
    ),
    $componentPage
);

// For non human friendly URL's

// Store values of original variables in this variable
$arVariables = array();

// Build an array of variable aliases from such array...
// "by default" $arDefaultVariableAliases
// and an array passed in $arParams["VARIABLE_ALIASES"]
$arVariableAliases =
    CComponentEngine::MakeComponentVariableAliases($arDefaultVariableAliases,
                                                   $arParams["VARIABLE_ALIASES"]);

// Restore the variables that were passed in the query parameters
// and append them to $arVariables
CComponentEngine::InitComponentVariables(False, $arComponentVariables,
                                         $arVariableAliases, $arVariables);

// Now, based on the original variables $arVariables
// define which page of the component template should be displayed

$componentPage = "";
if (IntVal($arVariables["ELEMENT_ID"]) > 0)
    $componentPage = "element";
elseif (IntVal($arVariables["IBLOCK_ID"]) > 0 ||
        IntVal($arVariables["SECTION"]) > 0)
    $componentPage = "section";
else
    $componentPage = "list";

$this->IncludeComponentTemplate(
    array(
        "VARIABLES" => $arVariables,
        "ALIASES" => $arVariableAliases
    ),
    $componentPage
);

See Also

  • Compound component structure
  • Input parameter aliases
  • CComponentEngine::MakeComponentVariableAliases
  • CComponentEngine::MakeComponentUrlTemplates
    • © 2001-2007 Bitrix Bitrix Site Manager


MakeComponentUrlTemplates

CComponentEngine::MakeComponentUrlTemplates

array
MakeComponentUrlTemplates(
 array arDefaultUrlTemplates,
 array arCustomUrlTemplates
);

The method is used with human-friendly URL's in compound components. The method takes default path templates and component path templates, and replaces default path templates with those overridden in the component input parameters.

Parameters

Parameter | Description
arDefaultUrlTemplates | An array of default path templates.
arCustomUrlTemplates | An array of path templates passed in the input parameters on the component.

Return Values

An array of path templates.

Example

// if an array of the default path templates has
// the following format:
$arDefaultUrlTemplates = array(
    "list" => "index.php",
    "element" => "#IBLOCK_ID#/#ELEMENT_ID#.php?SID=#SECTION_ID#"
);

// and the following array is passed in the input parameters
$arParams["SEF_URL_TEMPLATES"] = array(
    "element" => "#IBLOCK_ID#/#SECTION_ID#/#ELEMENT_ID#.php"
);

// calling MakeComponentUrlTemplates:
$arUrlTemplates =
    CComponentEngine::MakeComponentUrlTemplates($arDefaultUrlTemplates,
                                                $arParams["SEF_URL_TEMPLATES"]);

// will create $arUrlTemplates:
$arUrlTemplates = array(
    "list" => "index.php",
    "element" => "#IBLOCK_ID#/#SECTION_ID#/#ELEMENT_ID#.php"
)

See Also

  • Compound component structure
  • CComponentEngine::ParseComponentPath
    • © 2001-2007 Bitrix Bitrix Site Manager


MakeComponentVariableAliases

CComponentEngine::MakeComponentVariableAliases

array
MakeComponentVariableAliases(
 array arDefaultVariableAliases ,
 array arCustomVariableAliases
);

The method takes default variable aliases and the component variable aliases, and replaces default variable aliases with those overridden in the component input parameters.

Parameters

Parameter | Description
arDefaultVariableAliases | An array of default variable aliases.
arCustomUrlTemplates | An array of variable aliases passed in the input parameters of the component.

Return Values

An array of variable aliases.

Example

// say the default variable aliases array is
$arDefaultVariableAliases404 = array();

// and the input parameter has the following aliases
$arParams["VARIABLE_ALIASES"] = array(
    "element" => array(
        "IBLOCK_ID" => "BID",
        "SECTION_ID" => "SID",
    )
);

// calling MakeComponentVariableAliases:
$arVariableAliases =
    CComponentEngine::MakeComponentVariableAliases($arDefaultVariableAliases404,
                                                   $arParams["VARIABLE_ALIASES"]);

// creates the following $arVariableAliases:
$arVariableAliases = array(
    "element" => array(
        "IBLOCK_ID" => "BID",
        "SECTION_ID" => "SID",
    )
)

See Also

  • Compound component structure
  • Input variable aliases
  • CComponentEngine::InitComponentVariables
    • © 2001-2007 Bitrix Bitrix Site Manager


MakePathFromTemplate

CComponentEngine::MakePathFromTemplate

string
MakePathFromTemplate(
 string template ,
 array arParams
);

The method replaces #SITE_DIR#, #SITE#, #SERVER_NAME# in template with values of the system-wide constants SITE_DIR, SITE_ID, SITE_SERVER_NAME, respectively.

Also the method replaces all substrings like "#arParams key#" with the corresponding values according to arParams.

Parameters

Parameter | Description
template | The path template, can contain substrings "#.....#".
arParams An array of replacement rules:
array(
    "key1" => "value 1",
    "key2" => "value 2",
    * * *
)
Defines replacements to be performed in template.

Return Values

Returns a string with substrings replaced according to arParams.

Example

// path temlpate from input parameters
$arParams["SECTION_PAGE_TEMPLATE2"] =
    "/#IBLOCK_ID#/#SECTION_ID#.php?s=#SITE#";

// component computed the following values:
$IBLOCK_ID = 3;
$SECTION_ID = 982;

// create a path using the template and
// the computed values
$pagePath = CComponentEngine::MakePathFromTemplate(
    $arParams["SECTION_PAGE_TEMPLATE2"],
    array(
        "IBLOCK_ID" => $IBLOCK_ID,
        "SECTION_ID" => $SECTION_ID
    )
);

// Now $pagePath contains:
$pagePath = "/3/982.php?s=en";
© 2001-2007 Bitrix Bitrix Site Manager


ParseComponentPath

CComponentEngine::ParseComponentPath

bool
ParseComponentPath(
 string folder404 ,
 array arUrlTemplates ,
 array & arVariables [,
 string requestURL]
);

This method helps handle SEF paths in compound components.

The method takes the component working folder, an array of path templates and the current requested page, and returns the compound component path code. Also the method restores variables that were assigned in the path.

Parameters

Parameter | Description
folder404 | The component working folder in SEF mode. This path is passed in $arParams["SEF_FOLDER"].
arUrlTemplates | An array of component path templates in SEF mode. This array is hard-coded in the component kernel and can be overridden by $arParams["SEF_URL_TEMPLATES"].
arVariables | A variable in which the restored variables for the specified path are returned.
requestURL | The requested path. By default - $APPLICATION->GetCurPage().

Return Values

Returns the template code, or an empty string otherwise.

Example

// if the path template array is
$arUrlTemplates = array(
    "list" => "index.php",
    "element" => "#IBLOCK_ID#/#ELEMENT_ID#.php?SID=#SECTION_ID#"
);
// and SEF_FOLDER is /company/news/
// and the requested address is /company/news/15/7653.php?SID=28

// then after calling ParseComponentPath:
$arVariables = array();
$page =
    CComponentEngine::ParseComponentPath($arParams["SEF_FOLDER"],
                                         $arUrlTemplates, $arVariables);

// the variable $page will contain "element"
// (the code of the corresponding template)
// and $arVariables will be
$arVariables = array(
    "IBLOCK_ID" => 15,
    "ELEMENT_ID" => 7653
)

See Also

  • Complex component structure
  • Input variable aliases
  • CComponentEngine::MakeComponentUrlTemplates
    • © 2001-2007 Bitrix Bitrix Site Manager


CDatabase

The CDatabase class is used to work with the database.

When a page is created, an object $DB of the class CDatabase is automatically created. You must use this object to perform any operation on the database.

Methods

Method | Description
ForSql | Prepares the string for insertion into an SQL query.
Query | Performs a query to the database and returns the query result.
QueryBind | Executes SQL queries like "UPDATE" or "INSERT" that require variable binding.
QueryBindSelect | Executes a "SELECT" SQL query that require variable binding.
Update | Updates records in the table with the values passed.
NextID | Returns the next value from the sequence.
Insert | Inserts a record with fields to the table.
LastID | Returns the ID of the last added record.
PrepareFields | Prepares global variables for insertion in an SQL query.
PrepareInsert | Prepares an array of the two strings for issuing an SQL query used to insert a record in the database.
PrepareUpdate | Prepares an string for issuing an SQL query used to update a record in the database.
InitTableVarsForEdit | Creates global variables used for the display.
ParseSqlBatch | Parses the string containing a bundle of queries.
RunSqlBatch | Executes a set of queries contained in the file.
StartTransaction | Open a transaction.
Commit | Commits the commenced transaction.
Rollback | Rolls back all changes made by the incomplete open transaction.
Connect | Opens a connection to the database.
Disconnect | Closes the previously opened connection to the database.

Date and time handling methods

Method | Description
CurrentDateFunction | Used to obtain the SQL function returning the current date.
CurrentTimeFunction | Returns the function used to obtain the current time.
CharToDateFunction | Returns a string used to insert the date in the database query.
DateToCharFunction | Returns a string used to obtain the date in the database query.
DateFormatToPHP | Converts any date and time format allowed by the site settings to the PHP format.
FormatDate | Converts the date from the source format into another.
CompareDates | Compares two dates.
IsDate | Checks the date for validity.

See Also

  • Handling date and time
  • Date and time handling functions


CharToDateFunction

CDatabase::CharToDateFunction

string
CDatabase::CharToDateFunction(
 string value,
 string type = "FULL",
 string site = false
 )

MySQL

The method CharToDateFunction returns a value converted to the format YYYY-MM-DD [HH:MI:SS].

Oracle

The method CharToDateFunction returns a string TO_DATE with the required parameters.

The date format is specified in either language or site preferences.

Parameters

Parameter | Description
value | If the method is called within the public section, the value parameter is the date in the format of a current site. If the method is called within the administrative section, the value parameter is the date in the format of a current language.
type | Type of the date format: "FULL" - date and time, "SHORT" - date only. Optional; "FULL" by default.
site | Site ID for the public section or language ID for administrative section. Optional; the current ID is used by default.

See Also

  • CDatabase::DateToCharFunction
  • Date and time handling functions

Example

<?
$arr = getdate();
$ndate = mktime(9,0,0,$arr["mon"],$arr["mday"],$arr["year"]);
$next_exec = $DB->CharToDateFunction(GetTime($ndate,"FULL"));
CAgent::AddAgent("SendDailyStatistics();",
                 "statistic","Y",86400,"",
                 "Y",$next_exec, 25);
?>
<?
$strSql = "
    SELECT
        ID
    FROM
        my_table
    WHERE
        DATE_CREATE <= ".$DB->CharToDateFunction("10.01.2003 23:59:59")."
    ";
$rs = $DB->Query($strSql, false, $err_mess.__LINE__);
?>


Commit

CDatabase::Commit

CDatabase::Commit()

The method Commit commits the commenced transaction.

Note
This method is for Oracle version only!

Parameters

No parameters.

See Also

  • CDatabase::Rollback
  • CDatabase::StartTransaction

Example

<?
if (strlen($save)>0)
{
    if (CheckFields())
    {
        $DB->PrepareFields("b_form");
        $arFields = array(
            "TIMESTAMP_X"             => $DB->GetNowFunction(),
            "NAME"                    => "'".trim($str_NAME)."'",
            "VARNAME"                 => "'".trim($str_VARNAME)."'",
            "C_SORT"                  => "'".intval($str_C_SORT)."'",
            "FIRST_SITE_ID"           => "'".$DB->ForSql($FIRST_SITE_ID,2)."'",
            "BUTTON"                  => "'".$str_BUTTON."'",
            "DESCRIPTION"             => "'".$str_DESCRIPTION."'",
            "DESCRIPTION_TYPE"        => "'".$str_DESCRIPTION_TYPE."'",
            "SHOW_TEMPLATE"           => "'".trim($str_SHOW_TEMPLATE)."'",
            "MAIL_EVENT_TYPE"         => "'".$DB->ForSql("FORM_FILLING_".$str_VARNAME,50)."'",
            "SHOW_RESULT_TEMPLATE"    => "'".trim($str_SHOW_RESULT_TEMPLATE)."'",
            "PRINT_RESULT_TEMPLATE"   => "'".trim($str_PRINT_RESULT_TEMPLATE)."'",
            "EDIT_RESULT_TEMPLATE"    => "'".trim($str_EDIT_RESULT_TEMPLATE)."'",
            "FILTER_RESULT_TEMPLATE"  => "'".trim($str_FILTER_RESULT_TEMPLATE)."'",
            "TABLE_RESULT_TEMPLATE"   => "'".trim($str_TABLE_RESULT_TEMPLATE)."'",
            "STAT_EVENT1"             => "'".trim($str_STAT_EVENT1)."'",
            "STAT_EVENT2"             => "'".trim($str_STAT_EVENT2)."'",
            "STAT_EVENT3"             => "'".trim($str_STAT_EVENT3)."'"
            );
        $DB->StartTransaction();
        if ($ID>0)
        {
            $DB->Update("b_form", $arFields, "WHERE ID='".$ID."'", $err_mess.__LINE__);
        }
        else
        {
            $ID = $DB->Insert("b_form", $arFields, $err_mess.__LINE__);
            $new="Y";
        }
        $ID = intval($ID);
        if (strlen($strError)<=0)
        {
            <b>$DB->Commit</b>();
            if (strlen($save)>0) LocalRedirect("form_list.php?lang=".LANGUAGE_ID);
            elseif ($new=="Y") LocalRedirect("form_edit.php?lang=".LANGUAGE_ID."&ID=".$ID);
        }
        else $DB->Rollback();
    }
}?>


CompareDates

CDatabase::CompareDates

int
CDatabase::CompareDates(
 string date1,
 string date2,
)

The method CompareDates compares two dates.

Parameters

Parameter | Description
date1 | First date to be compared.
date2 | Second date to be compared.

Return Values

The method returns the following values.

Condition | Return value
date1 > date2 | 1
date1 < date2 | -1
date1 = date2 | 0

See Also

  • Date and time handling functions
  • CheckFilterDates

Example

<?
// date 1
$date1 = "01.01.2005";

// date 2
$date2 = "01.01.2007";

$result = $DB->CompareDates($date2, $date1);

if ($result==1) echo $date1." > ".$date2;
elseif ($result==-1) echo $date1." < ".$date2;
elseif ($result==0) echo $date1." = ".$date2;
?>


Connect

CDatabase::Connect

bool
CDatabase::Connect(
 string host,
 string db,
 string login,
 string password
)

The method Connect opens a connection to the database.

Parameters

Parameter | Description
host | Database server.
db | Database name.
login | Login
password | Password.

Return Values

Returns true on success or false otherwise.

See Also

  • CDatabase::Disconnect

Example

<?
if(!($DB->Connect($DBHost, $DBName, $DBLogin, $DBPassword)))
{
    if (file_exists($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/php_interface/dbconn_error.php"))
    {
        include($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/php_interface/dbconn_error.php");
    }
    else
    {
        include($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/dbconn_error.php");
    }
    die();
}
?>


CurrentDateFunction

CDatabase::CurrentDateFunction

string
CDatabase::CurrentDateFunction()

The method CurrentDateFunction is used to obtain the SQL function returning the current date: CURRENT_DATE for MySQL or TRUNC(SYSDATE) for Oracle.

Parameters

No parameters.

See Also

  • CDatabase::CurrentTimeFunction
  • Date and time handling functions

Example

<?
$strSql = "UPDATE my_table SET DATE_CHANGE=".$DB->CurrentDateFunction()." WHERE ID=45";
$Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);
?>
<?
$strSql = "
    SELECT
        ID
    FROM
        my_table
    WHERE
        DATE_CREATE <= ".$DB->CurrentDateFunction()."
    ";
$rs = $DB->Query($strSql, false, $err_mess.__LINE__);
?>


CurrentTimeFunction

CDatabase::CurrentTimeFunction

string
CDatabase::CurrentTimeFunction()

The method CurrentTimeFunction returns the string SYSDATE for Oracle version and now() for MySQL.

Parameters

No parameters.

See Also

  • CDatabase::CurrentDateFunction
  • Date and time handling functions

Example

<?
$DB->Update("my_table",
            Array("TIME_CHANGE" => $DB->CurrentTimeFunction()),
"WHERE ID=45", $err_mess.__LINE__);
?>
<?
$strSql = "
    UPDATE my_table SET
        TIME_CHANGE=".$DB->CurrentTimeFunction()."
    WHERE ID=45
    ";
$Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);
?>
<?
$strSql = "
    SELECT
        ID
    FROM
        my_table
    WHERE
        TIME_CHANGE <= ".$DB->CurrentTimeFunction()."
    ";
$rs = $DB->Query($strSql, false, $err_mess.__LINE__);
?>


DateFormatToPHP

CDatabase::DateFormatToPHP

string
CDatabase::DateFormatToPHP(
 string date_format
)

The method DateFormatToPHP converts any date and time format allowed by the site settings to the PHP format.

The following rules apply.

Input formatters | Output formatters | Description
YYYY | Y | Year (0001 - 9999)
MM | m | Month (01 - 12)
DD | d | Day (01 - 31)
HH | H | Hours (00 - 24)
MI | i | Minutes (00 - 59)
SS | s | Seconds (00 - 59)

Parameters

Parameter | Description
date_format | Format to be converted.

See Also

  • CDatabase::FormatDate
  • CSite::GetDateFormat
  • Date and time handling functions

Example

<?
// source format
$format = "DD.MM.YYYY HH:MI:SS";

// convert to the PHP format
$php_format = $DB->DateFormatToPHP($format); // d.m.Y H:i:s
?>
<?
// print current date in the format of the current site
// obtain the site format
$site_format = CSite::GetDateFormat("SHORT");

// convert to the PHP format
$php_format = $DB->DateFormatToPHP($site_format);

// print current date in the format of the current site
echo date($php_format, time());
?>
<?
// print yesterday's date in the format of the current site

// obtain the site format
$site_format = CSite::GetDateFormat("SHORT");

// convert to the PHP format
$php_format = $DB->DateFormatToPHP($site_format);

// print yesterday's date in the format of the current site
echo date($php_format, time()-86400);
?>


DateToCharFunction

CDatabase::DateToCharFunction

string
CDatabase::DateToCharFunction(
 string value,
 string type = "FULL",
 string site = false
 )

The method DateToCharFunction returns the string DATE_FORMAT for MySQL or TO_CHAR for Oracle, with all the required parameters.

The date format is specified in either language or site preferences.

Parameters

Parameter | Description
value | Date in the format of a current site.
type | Type of the date format: "FULL" - date and time, "SHORT" - date only. Optional; "FULL" by default.
site | Site ID for the public section or language ID for administrative section. Optional; the current ID is used by default.

See Also

  • CDatabase::CharToDateFunction
  • Date and time handling functions

Example

<?
$strSql = "
    SELECT
        ID,
        ".$DB->DateToCharFunction("DATE_CREATE")."    DATE_CREATE
    FROM
        my_table
    ";
$rs = $DB->Query($strSql, false, $err_mess.__LINE__);
?>


Disconnect

CDatabase::Disconnect

CDatabase::Disconnect()

The method Disconnect closes the previously opened connection to the database.

Parameters

No parameters.

See Also

  • CDatabase::Connect

Example

<?
$DB->Disconnect();
?>


FormatDate

CDatabase::FormatDate

string
CDatabase::FormatDate(
 string date,
 string from_format = "DD.MM.YYYY HH:MI:SS",
 string to_format = "DD.MM.YYYY HH:MI:SS"
)

The method FormatDate converts the date from the source format into another. The format allows the following symbols.
Formatter | Description
YYYY | Year (0001 - 9999)
MM | Month (01 - 12)
DD | Day (01 - 31)
HH | Hours (00 - 24)
MI | Minutes (00 - 59)
SS | Seconds (00 - 59)

Parameters

Parameter | Description
date | Date to be converted.
from_format | Format of the date to be converted. Optional; the default value is "DD.MM.YYYY HH:MI:SS".
to_format | Target format to convert into. Optional; the default value is "DD.MM.YYYY HH:MI:SS".

See Also

  • CDatabase::DateFormatToPHP
  • CSite::GetDateFormat
  • ConvertDateTime
  • Date and time handling functions

Example

<?
// specify the date
$date = "31.12.2005";

// set the input date format
$format = "DD.MM.YYYY";

// obtain the format of the current site
$new_format = CSite::GetDateFormat("SHORT"); // YYYY-MM-DD

// perform conversion
$new_date = $DB->FormatDate($date, $format, $new_format);

// got the date in the new format!
echo $new_date; // 2005-12-31
?>
<?
// convert the date from the format of one site to that of another

// obtain the format of the "de" site
$format_de = CSite::GetDateFormat("SHORT", "de"); // DD.MM.YYYY

// obtain the format of the "en" site
$format_en = CSite::GetDateFormat("SHORT", "en"); // YYYY-MM-DD

// perform conversion
$new_date = $DB->FormatDate($date, $format_de, $format_en);

// got the date in the new format!
echo $date; // 2005-12-31
?>


ForSql

CDatabase::ForSql

string
CDatabase::ForSql(
 string value,
 int max_length=0
)

The method ForSql prepares the string for insertion into an SQL query (replaces quotes etc.) and optionally truncates it to a specified maximum length.

Parameters

Parameter | Description
value | Source string to be processed.
max_length | Maximum length of the resulting string. Optional; by default (0) the string is not truncated.

See Also

  • CDatabase::Query
  • CDatabase::Update
  • CDatabase::Insert

Example

<?
$strSql = "
    SELECT
        ID
    FROM
        b_stat_phrase_list
    WHERE
        PHRASE='".$DB->ForSql($search_phrase)."'
    and SESSION_ID='".$_SESSION["SESS_SESSION_ID"]."'
    ";
$w = $DB->Query($strSql, false, $err_mess.__LINE__);
?>


InitTableVarsForEdit

CDatabase::InitTableVarsForEdit

CDatabase::InitTableVarsForEdit(
 string table,
 string prefix_from = "str_",
 string prefix_to = "str_",
 string postfix_from = "",
 bool init_anyway = false
 )

The method InitTableVarsForEdit creates global variables with names ${prefix_to.field_name} and sets its values to those of variables ${prefix_from.field_name.postfix_from}. The "field_name" parts are field names of the table. The variables created are HTML safe.

Note
The method operates variables of the global scope. Keep this fact in mind when creating main files of components.

Parameters

Parameter | Description
table | Table name.
prefix_from | Prefix of the source variables. Optional; "str_" by default.
prefix_to | Prefix of the variables to be created. Optional; "str_" by default.
postfix_from | Suffix of the source variables. Optional; the default value is an empty string.
init_anyway | If true, the variables created are always initialised with no respect to their existence . Optional; false by default.

See Also

  • CDatabase::PrepareFields

Example

<?
$stoplist = CStoplist::GetByID($ID);
if (!($stoplist && $stoplist->ExtractFields()))
{
    $ID=0;
    $str_ACTIVE="Y";
    $str_MASK_1="255";
    $str_MASK_2="255";
    $str_MASK_3="255";
    $str_MASK_4="255";
    $str_IP_1 = $net1;
    $str_IP_2 = $net2;
    $str_IP_3 = $net3;
    $str_IP_4 = $net4;
    $str_USER_AGENT = $user_agent;
    $str_DATE_START=GetTime(time(),"FULL");
    $str_MESSAGE = GetMessage("STAT_DEFAULT_MESSAGE");
    $str_MESSAGE_LID = LANGUAGE_ID;
    $str_SAVE_STATISTIC = "Y";
}
if (strlen($strError)>0) $DB->InitTableVarsForEdit("b_stop_list", "", "str_");
?>


Insert

CDatabase::Insert

mixed
CDatabase::Insert(
 string table,
 array fields,
 string error_position = "",
 bool debug = false,
 int exist_id = "",
 bool ignore_errors = false
 )

The method Insert inserts a record with fields to the table. The following conditions must be met for this function to work correctly.

  • The table must have a field "ID" which is the Primary Key for this table.
  • MySQL: the field "ID" must be auto increment (if the parameter exist_id is not specified).
  • Oracle: the sequence named like "SQ_.table" must exist.

Note
Values of all fields must be prepared for an SQL query (for example using the method CDatabase::ForSql).

Parameters

Parameter | Description
table | Name of the table.
fields | Array of field values in the format "field"=>"value",...
error_position | String indicating the method call position in the code (e.g. __LINE__). If an SQL query fails and the file /bitrix/php_interface/dbconn.php has the variable $DBDebug=true;, the error_position and the failure SQL query are printed.
debug | If set to true, text of an SQL query is displayed.
exist_id | If the value specified is a positive number, a field named "ID" with the value of exist_id is created. If this parameter is not specified, a field "ID" with the value of SQ_table.nextval() is added to the Oracle table.
ignore_errors | If true, any SQL errors are ignored and the function does not interrupt.

Return Values

Returns the ID of the created record or false otherwise.

See Also

  • CDatabase::Query
  • CDatabase::ForSql
  • CDatabase::Update
  • CDatabase::PrepareInsert
  • CDatabase::PrepareUpdate

Example

<?
if (strlen($save)>0)
{
    if (CheckFields())
    {
        $DB->PrepareFields("b_form");
        $arFields = array(
            "TIMESTAMP_X"             => $DB->GetNowFunction(),
            "NAME"                    => "'".trim($str_NAME)."'",
            "VARNAME"                 => "'".trim($str_VARNAME)."'",
            "C_SORT"                  => "'".intval($str_C_SORT)."'",
            "FIRST_SITE_ID"           => "'".$DB->ForSql($FIRST_SITE_ID,2)."'",
            "BUTTON"                  => "'".$str_BUTTON."'",
            "DESCRIPTION"             => "'".$str_DESCRIPTION."'",
            "DESCRIPTION_TYPE"        => "'".$str_DESCRIPTION_TYPE."'",
            "SHOW_TEMPLATE"           => "'".trim($str_SHOW_TEMPLATE)."'",
            "MAIL_EVENT_TYPE"         => "'".$DB->ForSql("FORM_FILLING_".$str_VARNAME,50)."'",
            "SHOW_RESULT_TEMPLATE"    => "'".trim($str_SHOW_RESULT_TEMPLATE)."'",
            "PRINT_RESULT_TEMPLATE"   => "'".trim($str_PRINT_RESULT_TEMPLATE)."'",
            "EDIT_RESULT_TEMPLATE"    => "'".trim($str_EDIT_RESULT_TEMPLATE)."'",
            "FILTER_RESULT_TEMPLATE"  => "'".trim($str_FILTER_RESULT_TEMPLATE)."'",
            "TABLE_RESULT_TEMPLATE"   => "'".trim($str_TABLE_RESULT_TEMPLATE)."'",
            "STAT_EVENT1"             => "'".trim($str_STAT_EVENT1)."'",
            "STAT_EVENT2"             => "'".trim($str_STAT_EVENT2)."'",
            "STAT_EVENT3"             => "'".trim($str_STAT_EVENT3)."'"
            );
        $DB->StartTransaction();
        if ($ID>0)
        {
            $DB->Update("b_form", $arFields, "WHERE ID='".$ID."'", $err_mess.__LINE__);
        }
        else
        {
            $ID = $DB->Insert("b_form", $arFields, $err_mess.__LINE__);
            $new="Y";
        }
        $ID = intval($ID);
        if (strlen($strError)<=0)
        {
            $DB->Commit();
            if (strlen($save)>0) LocalRedirect("form_list.php?lang=".LANGUAGE_ID);
            elseif ($new=="Y") LocalRedirect("form_edit.php?lang=".LANGUAGE_ID."&ID=".$ID);
        }
        else $DB->Rollback();
    }
}
?>


IsDate

CDatabase::IsDate

bool
CDatabase::IsDate(
 string date,
 string format=false,
 string site=false,
 string type="SHORT"
 )

The method IsDate checks the date for validity.

Parameters

Parameter | Description
date | Date to be verified.
format | Date format. If false, the date format is inferred from the current site (for public section) or language (for administrative section). Optional; "false" by default.
site | Site ID (for public section) or the language ID (for administrative section). Used to determine the format if format is false. Optional; by default, current site (for public section) or language (for administrative section) are used.
type | Type of the date format: "FULL" - date and time, "SHORT" - date only. Optional; "SHORT" by default.

Return Values

Returns true if the date is valid or false otherwise.

See Also

  • Date and time handling functions
  • CheckFilterDates

Example

<?
if (!$DB->IsDate("12.10.2005 22:34:15", "DD.MM.YYYY HH:MI:SS"))
  echo "Error: invalid date format.";
?>


LastID

CDatabase::LastID

int
CDatabase::LastID()

The method LastID returns the ID of the last added record.

Warning
For use with the MySQL version only!

Parameters

No parameters.

See Also

  • CDatabase::Query

Example

<?
function AddResultAnswer($arFields)
{
    $err_mess = (CForm::err_mess())."<br>Function: AddResultAnswer<br>Line: ";
    global $DB;
    $arInsert = $DB->PrepareInsert("b_form_result_answer", $arFields, "form");
    $strSql = "INSERT INTO b_form_result_answer (".$arInsert[0].") VALUES (".$arInsert[1].")";
    $DB->Query($strSql, false, $err_mess.__LINE__);
    return intval($DB->LastID());
}
?>


NextID

CDatabase::NextID

int
CDatabase::NextID(
 string sequence_name
)

The function returns the next value from the sequence.

Warning
For use with the Oracle version only!

Parameters

Parameter | Description
sequence_name | Name of a sequence.

See Also

  • CDatabase::Query

Example

<?
function AddResultAnswer($arFields)
{
    $err_mess = (CForm::err_mess())."<br>Function: AddResultAnswer<br>Line: ";
    global $DB;
    $arBinds = array();
    $arInsert = $DB->PrepareInsert("b_form_result_answer", $arFields, "form");
    $AID = $DB->NextID("sq_b_form_result_answer");
    $strSql="INSERT INTO b_form_result_answer (ID,".$arInsert[0].") VALUES ($AID,".$arInsert[1].")";
    if (is_set($arFields, "USER_TEXT"))
        $arBinds["USER_TEXT"] = $arFields["USER_TEXT"];
    if (is_set($arFields, "ANSWER_TEXT_SEARCH"))
        $arBinds["ANSWER_TEXT_SEARCH"] = $arFields["ANSWER_TEXT_SEARCH"];
    if (is_set($arFields, "ANSWER_VALUE_SEARCH"))
        $arBinds["ANSWER_VALUE_SEARCH"] = $arFields["ANSWER_VALUE_SEARCH"];
    if (is_set($arFields, "USER_TEXT_SEARCH"))
        $arBinds["USER_TEXT_SEARCH"] = $arFields["USER_TEXT_SEARCH"];
    $DB->QueryBind($strSql, $arBinds);
    return $AID;
}
?>


ParseSqlBatch

CDatabase::ParseSqlBatch

array
CDatabase::ParseSqlBatch(
 string sql
)

The method ParseSqlBatch parses the string containing a bundle of queries and creates an array of queries.

Parameters

Parameter | Description
sql | String containing a bundle of queries. Queries are separated with ";" for the MySQL version or "/" for the Oracle version.

Return Values

Array of queries.

See Also

  • CDatabase::RunSqlBatch
  • CDatabase::Query

Example

<?
function RunSqlBatch($filepath)
{
    $arErr = Array();
    // open a file with queries
    $f = @fopen($filepath, "rb");
    if($f)
    {
        $contents = fread($f, filesize($filepath));
        fclose($f);

        // split into separate queries
        $arSql = $this->ParseSqlBatch($contents);
        for($i=0; $i<count($arSql); $i++)
        {
            $strSql = str_replace("\r\n", "\n", $arSql[$i]);
            if(!$this->Query($strSql, true))
                $arErr[] = $this->db_Error;
        }
    }
    if(count($arErr)>0)
        return $arErr;

    return false;
}
?>


PrepareFields

CDatabase::PrepareFields

CDatabase::PrepareFields(
 string table,
 string prefix = "str_",
 string postfix = ""
)

The method PrepareFields prepares global variables corresponding to the names of fields of the table for writing to the database.

The method creates global variables in the form of ${prefix.field_name.postfix} and sets its values to those of global variables with names as per table field names. All the required type conversion is done automatically.

For example, fields of the int type are defined and evaluated as follows:

${prefix.field_name.postfix} = intval(${field_name});

Field of the type varchar:

${prefix.field_name.postfix} = CDatabase::ForSql(${field_name}, field_size);

Note
The method operates variables of the global scope. Keep this fact in mind when creating main files of components.

Parameters

Parameter | Description
table | Name of the table.
prefix | Prefix for variables. Optional; "str_" by default.
postfix | Suffix variables. Optional; the default value is an empty string.

See Also

  • CDatabase::InitTableVarsForEdit

Example

<?
if (strlen($save)>0)
{
    if (CheckFields())
    {
        $DB->PrepareFields("b_form");
        $arFields = array(
            "TIMESTAMP_X"             => $DB->GetNowFunction(),
            "NAME"                    => "'".trim($str_NAME)."'",
            "VARNAME"                 => "'".trim($str_VARNAME)."'",
            "C_SORT"                  => "'".intval($str_C_SORT)."'",
            "FIRST_SITE_ID"           => "'".$DB->ForSql($FIRST_SITE_ID,2)."'",
            "BUTTON"                  => "'".$str_BUTTON."'",
            "DESCRIPTION"             => "'".$str_DESCRIPTION."'",
            "DESCRIPTION_TYPE"        => "'".$str_DESCRIPTION_TYPE."'",
            "SHOW_TEMPLATE"           => "'".trim($str_SHOW_TEMPLATE)."'",
            "MAIL_EVENT_TYPE"         => "'".$DB->ForSql("FORM_FILLING_".$str_VARNAME,50)."'",
            "SHOW_RESULT_TEMPLATE"    => "'".trim($str_SHOW_RESULT_TEMPLATE)."'",
            "PRINT_RESULT_TEMPLATE"   => "'".trim($str_PRINT_RESULT_TEMPLATE)."'",
            "EDIT_RESULT_TEMPLATE"    => "'".trim($str_EDIT_RESULT_TEMPLATE)."'",
            "FILTER_RESULT_TEMPLATE"  => "'".trim($str_FILTER_RESULT_TEMPLATE)."'",
            "TABLE_RESULT_TEMPLATE"   => "'".trim($str_TABLE_RESULT_TEMPLATE)."'",
            "STAT_EVENT1"             => "'".trim($str_STAT_EVENT1)."'",
            "STAT_EVENT2"             => "'".trim($str_STAT_EVENT2)."'",
            "STAT_EVENT3"             => "'".trim($str_STAT_EVENT3)."'"
            );
        if ($ID>0)
        {
            $DB->Update("b_form", $arFields, "WHERE ID='".$ID."'", $err_mess.__LINE__);
        }
        else
        {
            $ID = $DB->Insert("b_form", $arFields, $err_mess.__LINE__);
            $new="Y";
        }
        $ID = intval($ID);
        if (strlen($strError)<=0)
        {
            if (strlen($save)>0) LocalRedirect("form_list.php?lang=".LANGUAGE_ID);
            elseif ($new=="Y") LocalRedirect("form_edit.php?lang=".LANGUAGE_ID."&ID=".$ID);
        }
    }
}
?>


PrepareInsert

CDatabase::PrepareInsert

array
CDatabase::PrepareInsert(
 string table,
 array fields,
 string dir = "",
 string site = false
)

The method PrepareInsert prepares an array of the two strings for issuing an SQL query used to insert a record in the database. The method converts all values to the SQL-compliant format with respect to the field type and handles file operations returning the ID from the file table.

Parameters

Parameter | Description
table | Name of the table to insert a record into.
fields Array of field values in the form of "field name1"=>"value1", "field name2"=>"value2" [, ...].
Use a value of false to insert NULL. To insert a file attached to a record, set a value to an array of the following format:
Array(
"name" => "file name",
"size" => "file size",
"tmp_name" => "temporary path and name on the server",
"type" => "file type",
"del" => "delete (Y) or not (N) the file",
"MODULE_ID" => "module name");
You can easily build such an array by combining arrays $HTTP_POST_FILES[field name] and Array("del" => ${"field_name"."_del"}, "MODULE_ID" = "module name");
dir Name of the folder to store files (the folder is created in the folder upload). Used for the inserting files attached to a record.
Optional; the default value is an empty string.
site Site ID (for public section) or the language ID (for administrative section). Used to determine the date format when inserting fields of the type date or datetime.
Optional; the current ID is used by default.

Return Values

Returns an array of the two elements. The element with the key "0" contains a list of fields in the form of "field_name1, field_name2[, ...]", while the element [1] contains a string "value1, value2[, ...]".

See Also

  • CDatabase::PrepareUpdate

Example

<?
function AddResultAnswer($arFields)
{
    $err_mess = (CForm::err_mess())."<br>Function: AddResultAnswer<br>Line: ";
    global $DB;
    $arInsert = $DB->PrepareInsert("b_form_result_answer", $arFields, "form");
    $strSql = "INSERT INTO b_form_result_answer (".$arInsert[0].") VALUES (".$arInsert[1].")";
    $DB->Query($strSql, false, $err_mess.__LINE__);
    return intval($DB->LastID());
}
?>


PrepareUpdate

CDatabase::PrepareUpdate

array
CDatabase::PrepareUpdate(
 string table,
 array fields,
 string dir="",
 string site=false
)

The method PrepareUpdate prepares an string for issuing an SQL query used to update a record in the database. The method converts all values to the SQL-compliant format with respect to the field type and handles file operations returning the ID from the file table.

Parameters

Parameter | Description
table | Name of the table.
fields Array of field values in the form of "field name1"=>"value1", "field name2"=>"value2" [, ...].

Use a value of false to insert NULL. To insert a file attached to a record, set a value to an array of the following format:

Array(
"name" => "file name",
"size" => "file size",
"tmp_name" => "temporary path and name on the server",
"type" => "file type",
"del" => "delete (Y) or not (N) the file",
"MODULE_ID" => "module name");
You can easily build such an array by combining arrays $HTTP_POST_FILES[field name] and Array("del" => ${"field_name"."_del"}, "MODULE_ID" = "module name");

Any table field that does not have corresponding entry in the array will remain unchanged.
dir Name of the folder to store files (the folder is created in the folder upload). Used for the inserting files attached to a record.
Optional; the default value is an empty string.
site Site ID (for public section) or the language ID (for administrative section). Used to determine the date format when inserting fields of the type date or datetime.
Optional; the current ID is used by default.

Return Values

Returns the string of the format "field name1=value1, field name2= value2[, ...]".

See Also

  • CDatabase::PrepareInsert

Example

<?
function UpdateResultField($arFields, $RESULT_ID, $FIELD_ID)
{
    $err_mess = (CForm::err_mess())."<br>Function: UpdateResultField<br>Line: ";
    global $DB;
    $RESULT_ID = intval($RESULT_ID);
    $FIELD_ID = intval($FIELD_ID);
    $strUpdate = $DB->PrepareUpdate("b_form_result_answer", $arFields, "form");
    $strSql = "UPDATE b_form_result_answer SET ".$strUpdate." WHERE RESULT_ID=".$RESULT_ID." and FIELD_ID=".$FIELD_ID;
    $DB->Query($strSql, false, $err_mess.__LINE__);
}
?>


Query

CDatabase::Query

mixed
CDatabase::Query(
 string sql,
 bool ignore_errors=false,
 string error_position=""
)

The method Query performs a query to the database and returns the query result.

Parameters

Parameter | Description
sql | SQL query.
ignore_errors | Specifies to ignore errors. If set to true, the method returns false on failure. If set to false, the method breaks the page execution. Optional; false by default.
error_position | String indicating the method call position in the code (e.g. __LINE__). If an SQL query fails and the file /bitrix/php_interface/dbconn.php has the variable $DBDebug=true;, the error_position and the failure SQL query are printed.

Return Values

The method returns an instance of CDBResult on success.

If an error occurs and the ignore_errors parameter is true, the function returns false. If the ignore_errors parameter is false, the method breaks the page execution, having the following operations performed beforehand.

  1. Calls the function AddMessage2Log.
  2. If the current user is an administrator or the file /bitrix/php_interface/dbconn.php has the variable $DBDebug=true; the full error description is printed. Otherwise, the function SendError is called.
  3. The file /bitrix/php_interface/dbquery_error.php is included. If this file does not exist, the file /bitrix/modules/main/include/dbquery_error.php is included instead.

Notes for Oracle version:
1. In case an error occurred and a transaction is open, the metod CDataBase::Rollback is called.
2. Use the method CDatabase::QueryBind to insert the text fields BLOB, CLOB, LONG etc. (if their length is more than 4000 symbols).
3. If the an SQL query (like "SELECT") requires variable binding, use the method CDatabase::QueryBindSelect.

See Also

  • CDatabase::QueryBind
  • CDatabase::QueryBindSelect
  • CDatabase::ForSql
  • AddMessage2Log

Example

<?
function GetByID($ID, $GET_BY_SID="N")
{
    $err_mess = (CForm::err_mess())."<br>Function: GetByID<br>Line: ";
    global $DB;
    $where = ($GET_BY_SID=="N") ? " F.ID = '".intval($ID)."' " : " F.VARNAME='".$DB->ForSql($ID,50)."' ";
    $strSql = "
        SELECT
            F.*,
            F.FIRST_SITE_ID,
            F.FIRST_SITE_ID             LID,
            F.VARNAME,
            F.VARNAME                   SID,
            ".$DB->DateToCharFunction("F.TIMESTAMP_X")." TIMESTAMP_X,
            count(distinct D1.ID)       C_FIELDS,
            count(distinct D2.ID)       QUESTIONS,
            count(distinct S.ID)        STATUSES
        FROM b_form F
        LEFT JOIN b_form_status S ON (S.FORM_ID = F.ID)
        LEFT JOIN b_form_field D1 ON (D1.FORM_ID = F.ID and D1.ADDITIONAL='Y')
        LEFT JOIN b_form_field D2 ON (D2.FORM_ID = F.ID and D2.ADDITIONAL<>'Y')
        WHERE
            $where
        GROUP BY
            F.ID
        ";
    $res = $DB->Query($strSql, false, $err_mess.__LINE__);
    return $res;
}
?>


QueryBind

CDatabase::QueryBind

mixed
CDatabase::QueryBind(
 string sql,
 array binds,
 bool ignore_errors=false,
 string error_position=""
)

The method QueryBind executes SQL queries like "UPDATE" or "INSERT" that require variable binding (usually with fields BLOB, CLOB, LONG etc.).

Note
This method is for use with the Oracle version only!

Parameters

Parameter | Description
sql | SQL query.
binds | Array of fields BLOB, CLOB, LONG etc. in the format array("field name" => "value" [, ...]).
ignore_errors | Specifies to ignore errors. If set to true, the method returns false on failure. If set to false, the method breaks the page execution. Optional; false by default.
error_position | String indicating the method call position in the code (e.g. __LINE__). If an SQL query fails and the file /bitrix/php_interface/dbconn.php has the variable $DBDebug=true;, the error_position and the failure SQL query are printed.

Return Values

The method returns an instance of CDBResult on success.

If an error occurs and the ignore_errors parameter is true, the function returns false. If the ignore_errors parameter is false, the method breaks the page execution, having the following operations performed beforehand.

  1. Calls the function AddMessage2Log.
  2. If the current user is an administrator or the file /bitrix/php_interface/dbconn.php has the variable $DBDebug=true; the full error description is printed. Otherwise, the function SendError is called.
  3. The file /bitrix/php_interface/dbquery_error.php is included. If this file does not exist, the file /bitrix/modules/main/include/dbquery_error.php is included instead.

See Also

  • CDatabase::Query
  • CDatabase::QueryBindSelect
  • CDatabase::ForSql
  • AddMessage2Log

Example

<?
// refresh a field

// refresh field MY_FIELD of the type CLOB
$strSql = "UPDATE my_table SET MY_FIELD = :MY_FIELD WHERE ID=1";

// variable $MY_FIELD_VALUE contains
// the text of length more than 4000 symbols
$arBinds = array("MY_FIELD" => $MY_FIELD_VALUE);

// execute query binding :MY_FIELD to a real value
$DB->QueryBind($strSql, $arBinds);
?>
<?
// insert a new record

$arFields = array(
   // huge field of more than 4000 symbols in length
  "USER_TEXT" => $USER_TEXT,
  "EMAIL" => $EMAIL // short field
);

// prepare array
$arInsert = $DB->PrepareInsert("my_table",
                               $arFields,
                               "my_module_id");

// get the ID of a new record
$id = $DB->NextID("sq_my_table");

// prepare an SQL query having ":USER_TEXT"
// in place of the field USER_TEXT
// that is to be processed by QueryBind
$strSql="INSERT INTO my_table (ID,".$arInsert[0].
        ") VALUES ($id,".$arInsert[1].")";

// prepare the binding array
$arBinds = array("USER_TEXT" => $arFields["USER_TEXT"]);

// insert a new field while
// binding :USER_TEXT to a real value
$DB->QueryBind($strSql, $arBinds);
?>


QueryBindSelect

CDatabase::QueryBindSelect

mixed
CDatabase::QueryBindSelect(
 string sql,
 array binds,
 bool ignore_errors=false,
 string error_position=""
)

The method QueryBindSelect executes a "SELECT" SQL query that require variable binding.

Note
This method is for use with the Oracle version only!

Parameters

Parameter | Description
sql | SQL query.
binds | Array of fields BLOB, CLOB, LONG etc. in the format array("field name" => "value" [, ...]).
ignore_errors | Specifies to ignore errors. If set to true, the method returns false on failure. If set to false, the method breaks the page execution. Optional; false by default.
error_position | String indicating the method call position in the code (e.g. __LINE__). If an SQL query fails and the file /bitrix/php_interface/dbconn.php has the variable $DBDebug=true;, the error_position and the failure SQL query are printed.

Return Values

The method returns an instance of CDBResult on success.

If an error occurs and the ignore_errors parameter is true, the function returns false. If the ignore_errors parameter is false, the method breaks the page execution, having the following operations performed beforehand.

  1. Calls the function AddMessage2Log.
  2. If the current user is an administrator or the file /bitrix/php_interface/dbconn.php has the variable $DBDebug=true; the full error description is printed. Otherwise, the function SendError is called.
  3. The file /bitrix/php_interface/dbquery_error.php is included. If this file does not exist, the file /bitrix/modules/main/include/dbquery_error.php is included instead.

See Also

  • CDatabase::Query
  • CDatabase::QueryBind
  • CDatabase::ForSql
  • AddMessage2Log

Example

<?
$strSql = "
    SELECT
        *
    FROM
        my_table
    WHERE
        :url like '/en/index.php%'
    ";
$arrBind = array("url" => $APPLICATION->GetCurUri());
$rs = $DB->QueryBindSelect($strSql, $arrBind, false, "F: ".__FILE__." L: ".__LINE__);
?>


Rollback

CDatabase::Rollback

CDatabase::Rollback()

The method Rollback rolls back all changes made by the incomplete open transaction.

Note
This method is for use with the Oracle version only!

Parameters

No parameters.

See Also

  • CDatabase::Commit
  • CDatabase::StartTransaction

Example

<?
if (strlen($save)>0)
{
    if (CheckFields())
    {
        $DB->PrepareFields("b_form");
        $arFields = array(
            "TIMESTAMP_X"             => $DB->GetNowFunction(),
            "NAME"                    => "'".trim($str_NAME)."'",
            "VARNAME"                 => "'".trim($str_VARNAME)."'",
            "C_SORT"                  => "'".intval($str_C_SORT)."'",
            "FIRST_SITE_ID"           => "'".$DB->ForSql($FIRST_SITE_ID,2)."'",
            "BUTTON"                  => "'".$str_BUTTON."'",
            "DESCRIPTION"             => "'".$str_DESCRIPTION."'",
            "DESCRIPTION_TYPE"        => "'".$str_DESCRIPTION_TYPE."'",
            "SHOW_TEMPLATE"           => "'".trim($str_SHOW_TEMPLATE)."'",
            "MAIL_EVENT_TYPE"         => "'".$DB->ForSql("FORM_FILLING_".$str_VARNAME,50)."'",
            "SHOW_RESULT_TEMPLATE"    => "'".trim($str_SHOW_RESULT_TEMPLATE)."'",
            "PRINT_RESULT_TEMPLATE"   => "'".trim($str_PRINT_RESULT_TEMPLATE)."'",
            "EDIT_RESULT_TEMPLATE"    => "'".trim($str_EDIT_RESULT_TEMPLATE)."'",
            "FILTER_RESULT_TEMPLATE"  => "'".trim($str_FILTER_RESULT_TEMPLATE)."'",
            "TABLE_RESULT_TEMPLATE"   => "'".trim($str_TABLE_RESULT_TEMPLATE)."'",
            "STAT_EVENT1"             => "'".trim($str_STAT_EVENT1)."'",
            "STAT_EVENT2"             => "'".trim($str_STAT_EVENT2)."'",
            "STAT_EVENT3"             => "'".trim($str_STAT_EVENT3)."'"
            );
        $DB->StartTransaction();
        if ($ID>0)
        {
            $DB->Update("b_form", $arFields, "WHERE ID='".$ID."'", $err_mess.__LINE__);
        }
        else
        {
            $ID = $DB->Insert("b_form", $arFields, $err_mess.__LINE__);
            $new="Y";
        }
        $ID = intval($ID);
        if (strlen($strError)<=0)
        {
            $DB->Commit();
            if (strlen($save)>0)
                LocalRedirect("form_list.php?lang=".LANGUAGE_ID);
            elseif ($new=="Y")
                LocalRedirect("form_edit.php?lang=".LANGUAGE_ID."&ID=".$ID);
        }
        else $DB->Rollback();
    }
}
?>


RunSqlBatch

CDatabase::RunSqlBatch

mixed
CDatabase::RunSqlBatch(
 string path
)

The method RunSqlBatch method executes a set of queries contained in the file path.

Parameters

Parameter | Description
path | File containing the batch of queries. The MySQL queries are separated with ";". The Oracle queries are separated with "/".

Return Values

Returns false is all queries are successfully processed. Otherwise, the method returns the array of errors descriptions each explaining the reason of failure for a specific query.

See Also

  • CDatabase::ParseSqlBatch
  • CDatabase::Query

Example

<?
$arrErrors = $DB->RunSqlBatch($_SERVER["DOCUMENT_ROOT"].
"/bitrix/modules/form/install/db/".strtolower($DB->type)."/install.sql");
?>

Sample file with MySQL queries

create table if not exists b_stat_adv_searcher (
   ID int(11) not null auto_increment,
   ADV_ID int(11) not null,
   SEARCHER_ID int(11) not null,
   primary key (ID));
insert  into b_stat_adv (ID, REFERER1, REFERER2) values (1, 'google', '') ;
insert  into b_stat_adv_searcher (ID, ADV_ID, SEARCHER_ID) values (1, 2, 4) ;

Sample file with Oracle queries

CREATE TABLE B_STAT_ADDITIONAL
(
    ID         NUMBER(18)    NOT NULL,
    C_TYPE     VARCHAR2(255) NOT NULL,
    NAME       NUMBER(18)    NULL,
    SESSIONS   NUMBER(18)    DEFAULT 0 NOT NULL,
    HITS       NUMBER(18)    DEFAULT 0 NOT NULL,
    NEW_GUESTS NUMBER(18)    DEFAULT 0 NOT NULL,
    C_EVENTS   NUMBER(18)    DEFAULT 0 NOT NULL,
    PRIMARY KEY (ID)
)
/
CREATE SEQUENCE SQ_B_STAT_ADDITIONAL
    START WITH 44
    INCREMENT BY 1
    NOMINVALUE
    NOMAXVALUE
    NOCYCLE
    NOCACHE
    NOORDER
/
INSERT INTO B_STAT_ADV (ID, REFERER1, REFERER2) VALUES (1, 'google', '')
/
DROP SEQUENCE SQ_B_STAT_ADV
/
CREATE SEQUENCE SQ_B_STAT_ADV
    START WITH 8
    INCREMENT BY 1
    NOMINVALUE
    NOMAXVALUE
    NOCYCLE
    NOCACHE
    NOORDER
/
INSERT INTO B_STAT_ADV_SEARCHER (ID, ADV_ID, SEARCHER_ID) VALUES (1, 2, 4)
/


StartTransaction

CDatabase::StartTransaction

CDatabase::StartTransaction()

The method StartTransaction open a transaction. Use Commit or Rollback to close it.

Note
This method is for use with the Oracle version only!

Parameters

No parameters.

See Also

  • CDatabase::Commit
  • CDatabase::Rollback

Example

<?
if (strlen($save)>0)
{
    if (CheckFields())
    {
        $DB->PrepareFields("b_form");
        $arFields = array(
            "TIMESTAMP_X"             => $DB->GetNowFunction(),
            "NAME"                    => "'".trim($str_NAME)."'",
            "VARNAME"                 => "'".trim($str_VARNAME)."'",
            "C_SORT"                  => "'".intval($str_C_SORT)."'",
            "FIRST_SITE_ID"           => "'".$DB->ForSql($FIRST_SITE_ID,2)."'",
            "BUTTON"                  => "'".$str_BUTTON."'",
            "DESCRIPTION"             => "'".$str_DESCRIPTION."'",
            "DESCRIPTION_TYPE"        => "'".$str_DESCRIPTION_TYPE."'",
            "SHOW_TEMPLATE"           => "'".trim($str_SHOW_TEMPLATE)."'",
            "MAIL_EVENT_TYPE"         => "'".$DB->ForSql("FORM_FILLING_".$str_VARNAME,50)."'",
            "SHOW_RESULT_TEMPLATE"    => "'".trim($str_SHOW_RESULT_TEMPLATE)."'",
            "PRINT_RESULT_TEMPLATE"   => "'".trim($str_PRINT_RESULT_TEMPLATE)."'",
            "EDIT_RESULT_TEMPLATE"    => "'".trim($str_EDIT_RESULT_TEMPLATE)."'",
            "FILTER_RESULT_TEMPLATE"  => "'".trim($str_FILTER_RESULT_TEMPLATE)."'",
            "TABLE_RESULT_TEMPLATE"   => "'".trim($str_TABLE_RESULT_TEMPLATE)."'",
            "STAT_EVENT1"             => "'".trim($str_STAT_EVENT1)."'",
            "STAT_EVENT2"             => "'".trim($str_STAT_EVENT2)."'",
            "STAT_EVENT3"             => "'".trim($str_STAT_EVENT3)."'"
            );
        $DB->StartTransaction();
        if ($ID>0)
        {
            $DB->Update("b_form", $arFields, "WHERE ID='".$ID."'", $err_mess.__LINE__);
        }
        else
        {
            $ID = $DB->Insert("b_form", $arFields, $err_mess.__LINE__);
            $new="Y";
        }
        $ID = intval($ID);
        if (strlen($strError)<=0)
        {
            $DB->Commit();
            if (strlen($save)>0) LocalRedirect("form_list.php?lang=".LANGUAGE_ID);
            elseif ($new=="Y") LocalRedirect("form_edit.php?lang=".LANGUAGE_ID."&ID=".$ID);
        }
        else $DB->Rollback();
    }
}
?>


Update

CDatabase::Update

int
CDatabase::Update(
 string table,
 array fields,
 string where = "",
 string error_position = "",
 bool debug = false,
 bool ignore_errors = false
 )

The method Update updates records in the table with the valued passed in fields.

Note
Values of all fields must be prepared for an SQL query (for example using the method CDatabase::ForSql).

Parameters

Parameter | Description
table | Name of the table.
fields | Array of field values in the format "field"=>"value",...
where | Condition for the WHERE statement in the SQL format. Optional; all records are updated by default.
error_position | String indicating the method call position in the code (e.g. __LINE__). If an SQL query fails and the file /bitrix/php_interface/dbconn.php has the variable $DBDebug=true;, the error_position and the failure SQL query are printed.
debug | If set to true, the method prints the text of an SQL query.
ignore_errors | Specifies to ignore errors. If set to true, the method ignores any SQL errors and continues execution. Optional; false by default.

Return Values

Returns the number of updated records.

See Also

  • CDatabase::Query
  • CDatabase::ForSql
  • CDatabase::Insert
  • CDatabase::PrepareInsert
  • CDatabase::PrepareUpdate

Example

<?
if (strlen($save)>0)
{
    if (CheckFields())
    {
        $DB->PrepareFields("b_form");
        $arFields = array(
            "TIMESTAMP_X"             => $DB->GetNowFunction(),
            "NAME"                    => "'".trim($str_NAME)."'",
            "VARNAME"                 => "'".trim($str_VARNAME)."'",
            "C_SORT"                  => "'".intval($str_C_SORT)."'",
            "FIRST_SITE_ID"           => "'".$DB->ForSql($FIRST_SITE_ID,2)."'",
            "BUTTON"                  => "'".$str_BUTTON."'",
            "DESCRIPTION"             => "'".$str_DESCRIPTION."'",
            "DESCRIPTION_TYPE"        => "'".$str_DESCRIPTION_TYPE."'",
            "SHOW_TEMPLATE"           => "'".trim($str_SHOW_TEMPLATE)."'",
            "MAIL_EVENT_TYPE"         => "'".$DB->ForSql("FORM_FILLING_".$str_VARNAME,50)."'",
            "SHOW_RESULT_TEMPLATE"    => "'".trim($str_SHOW_RESULT_TEMPLATE)."'",
            "PRINT_RESULT_TEMPLATE"   => "'".trim($str_PRINT_RESULT_TEMPLATE)."'",
            "EDIT_RESULT_TEMPLATE"    => "'".trim($str_EDIT_RESULT_TEMPLATE)."'",
            "FILTER_RESULT_TEMPLATE"  => "'".trim($str_FILTER_RESULT_TEMPLATE)."'",
            "TABLE_RESULT_TEMPLATE"   => "'".trim($str_TABLE_RESULT_TEMPLATE)."'",
            "STAT_EVENT1"             => "'".trim($str_STAT_EVENT1)."'",
            "STAT_EVENT2"             => "'".trim($str_STAT_EVENT2)."'",
            "STAT_EVENT3"             => "'".trim($str_STAT_EVENT3)."'"
            );
        $DB->StartTransaction();
        if ($ID>0)
        {
            $DB->Update("b_form", $arFields, "WHERE ID='".$ID."'", $err_mess.__LINE__);
        }
        else
        {
            $ID = $DB->Insert("b_form", $arFields, $err_mess.__LINE__);
            $new="Y";
        }
        $ID = intval($ID);
        if (strlen($strError)<=0)
        {
            $DB->Commit();
            if (strlen($save)>0) LocalRedirect("form_list.php?lang=".LANGUAGE_ID);
            elseif ($new=="Y") LocalRedirect("form_edit.php?lang=".LANGUAGE_ID."&ID=".$ID);
        }
        else $DB->Rollback();
    }
}
?>


CDBResult

The CDBResult class represents the result of a database query.

The class contains methods that can be used to implement the pagewise navigation and handle the query results. An instance of this class is created automatically and returned by the method CDatabase::Query.

Properties

Property | Description
result | Result description.
arResult | Array describing the result (only valid upon calling NavStart).
NavRecordCount | Number of records (only valid upon calling NavStart).
NavPageCount | Number of pages (only valid upon calling NavStart).
NavPageNomer | Number of the current page in the pagewise navigation sequence (only valid upon calling NavStart)
NavPageSize | Size of a page (only valid upon calling NavStart).
bFirstPrintNav | True if the method CDBResult::NavPrint had been called once (only valid upon calling NavStart).
bShowAll | Specifies (true / false) the link All is to be displayed in the pagewise navigation screen (only valid upon calling NavStart).
NavShowAll | True if the current screen displays all records as opposed to pagewise display (i.e. a user clicked the link All) (only valid upon calling NavStart).
NavNum | Current page ordinal used with the pagewise navigation mode (only valid upon calling NavStart).
nStartPage | True if the first page is currently displayed (only valid upon calling NavStart).
nEndPage | True if the last page is currently displayed (only valid upon calling NavStart).

Methods

Method | Description
Fetch | Retrieves the fields and stores them in an array.
NavNext | Returns an array of field values.
NavPrint | Used to display the pagewise navigation links.
NavStart | Splits the result of the selection into pages.
NavStringForCache | Returns the string which uniquely identify the current state of pagewise navigation.
IsNavPrint | Determines if all records may fit in a single page.
GetNext | Returns an array of field values converted to the HTML safe format.
ExtractFields | Defines global variables by the field names.
FieldName | Returns the name of a field by its ordinal.
FieldsCount | Returns the number of fields in the selection.
SelectedRowsCount | Returns the number of records selected with SELECT.
AffectedRowsCount | Returns a number of records modified by executing such SQL commands as INSERT, UPDATE or DELETE.
InitFromArray | Initializes the instance of CDBResult with the supplied values.


AffectedRowsCount

CDBResult::AffectedRowsCount

int
CDBResult::AffectedRowsCount()

The method AffectedRowsCount returns a number of records modified by executing such SQL commands as "INSERT", "UPDATE" or "DELETE".

Parameters

No parameters.

Return Values

Number of records modified.

See Also

  • CDBResult::SelectedRowsCount

Example

<?
$strSql = "
    INSERT INTO b_stat_day(
        ID,
        DATE_STAT,
        TOTAL_HOSTS)
    SELECT
        SQ_B_STAT_DAY.NEXTVAL,
        trunc(SYSDATE),
        nvl(PREV.MAX_TOTAL_HOSTS,0)
    FROM
        (SELECT	max(TOTAL_HOSTS) AS MAX_TOTAL_HOSTS	FROM b_stat_day) PREV
    WHERE
        not exists(SELECT 'x' FROM b_stat_day D WHERE TRUNC(D.DATE_STAT) = TRUNC(SYSDATE))
    ";
$q = $DB->Query($strSql, true, $err_mess.__LINE__);
if ($q && intval($q->AffectedRowsCount())>0)
{
    $arFields = Array("LAST"=>"'N'");
    $DB->Update("b_stat_adv_day",$arFields,"WHERE LAST='Y'", $err_mess.__LINE__);
    $DB->Update("b_stat_adv_event_day",$arFields,"WHERE LAST='Y'", $err_mess.__LINE__);
    $DB->Update("b_stat_searcher_day",$arFields,"WHERE LAST='Y'", $err_mess.__LINE__);
    $DB->Update("b_stat_event_day",$arFields,"WHERE LAST='Y'", $err_mess.__LINE__);
    $DB->Update("b_stat_country_day",$arFields,"WHERE LAST='Y'", $err_mess.__LINE__);
    $DB->Update("b_stat_guest",$arFields,"WHERE LAST='Y'",$err_mess.__LINE__);
    $DB->Update("b_stat_session",$arFields,"WHERE LAST='Y'",$err_mess.__LINE__);
}
?>


ExtractFields

CDBResult::ExtractFields

mixed
CDBResult::ExtractFields(
 string prefix="str_",
 bool encode=true
)

The method ExtractFields defines global variables with names in the format ${prefix."field name"}. Values of the variables are set to those of the corresponding fields,. Variables can be optionally converted to the HTML safe format.

Parameters

Parameter | Description
prefix | Prefix for the global variables. Optional; str_ by default.
encode | Specifies to convert the global variables to the HTML safe format. Optional; the default value is true.

Return Values

Returns an array like Array("field"=>"value" [, ...]) and moves the pointer to the next record. If no more records are available, the method returns false.

See Also

  • CDBResult::Fetch
  • CDBResult::GetNext
  • CDBResult::NavNext

Example

<select>
<?
$rs = CGroup::GetList($order="ID", $by="ASC");
while ($rs->ExtractFields("g_")) :
   ?><option value="<?=$g_ID?>"
   <?if (IntVal($g_ID)==IntVal($show_perms_for)) echo " selected";?>
   ><?=$g_NAME?></option><?
endwhile;
?>
</select>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Fetch

CDBResult::Fetch

mixed
CDBResult::Fetch()

The method Fetch obtains fields and values of a record and moves the pointer to the next record if more records are available in the result set.

Parameters

No parameters.

Return Values

Returns an array like Array("field"=>"value" [, ...]). If no more records are available, the method returns false.

See Also

  • CDBResult::GetNext
  • CDBResult::ExtractFields
  • CDBResult::NavNext

Example

<?
$rsUser = CUser::GetByID($USER_ID);
$arUser = $rsUser->Fetch();
?>


FieldName

CDBResult::FieldName

mixed
CDBResult::FieldName(
 int column
)

The method FieldName returns the name of a field by its ordinal.

Parameters

Parameter | Description
column | The field ordinal.

Return Values

Name of the field.

See Also

  • CDBResult::FieldsCount

Example

<?
$rs = $DB->Query($query,true);
$intNumFields = $rs->FieldsCount();
$i = 0;
while ($i<$intNumFields)
{
    $arFieldName[] = $rs->FieldName($i);
    $i++;
}
?>


FieldsCount

CDBResult::FieldsCount

int
CDBResult::FieldsCount()

The method FieldsCount returns the number of fields in the selection.

Parameters

No parameters.

Return Values

Number of fields in the selection.

See Also

  • CDBResult::FieldName

Example

<?
$rs = $DB->Query($query,true);
$intNumFields = $rs->FieldsCount();
$i = 0;
while ($i<$intNumFields)
{
    $arFieldName[] = $rs->FieldName($i);
    $i++;
}
?>


GetNext

CDBResult::GetNext

mixed
CDBResult::GetNext(
 bool text_html=true,
 bool original=true
)

The method GetNext returns an array of field values converted to the HTML safe format.

Parameters

Parameter | Description
text_html | If set to true, the method will automatically handle fields that allow for different formats for storing data (text / html). Optional; true by default.
original | If set to true, the returned array also contains original field values; these fields can be accessed by keys with suffix "~" appended to original key names. Optional; true by default.

Return Value

The method returns false if there is no more records to return, or the array otherwise.

See Also

  • CDBResult::Fetch
  • CDBResult::ExtractFields
  • CDBResult::NavNext

Example

<select>
<?
$rs = CGroup::GetList($order="ID", $by="ASC");
while ($arGroup=$rs->GetNext()) :
   ?><option value="<?=$arGroup["ID"]?>"
   <?if (IntVal($arGroup["ID"])==IntVal($show_perms_for)) echo " selected";?>
   ><?=$arGroup["NAME"]?></option><?
endwhile;
?>
</select>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


InitFromArray

CDBResult::InitFromArray

CDBResult::InitFromArray(
 array values
)

The method InitFromArray initializes the instance of CDBResult with the supplied values.

Parameters

Parameter | Description
values | Associated array of values used to initialise the instance of CDBResult.

Return Values

No return values.

Example

<?
$arr = array();
$arr[] = array("ID" => 1, "NAME" => "Title 1");
$arr[] = array("ID" => 2, "NAME" => "Title 2");
$arr[] = array("ID" => 3, "NAME" => "Title 3");
$arr[] = array("ID" => 4, "NAME" => "Title 4");

$rs = new CDBResult;
$rs->InitFromArray($arr);

$rs->NavStart(50);
if($rs->IsNavPrint())
{
     echo "<p>"; $rs->NavPrint("Elements"); echo "</p>";
}
?>
<?
// get a list of files and folders
CFileMan::GetDirList(Array($site_id, $path), $arDirs, $arFiles, $arFilter, Array($by=>$order), "DF");

// combine files and folders in a single array
$arDirContent = array_merge($arDirs, $arFiles);

// create an instance of CDBResult
$rsDirContent = new CDBResult;

// initialise the object with the input array
$rsDirContent->InitFromArray($arDirContent);

// now that we're done we can call
// all methods of the class CDBResult
// e.g. for the pagewise navigation setup:
$rsDirContent->NavStart(50);
if($rsDirContent->IsNavPrint()) echo "<p>"; $rs->NavPrint("Files"); echo "</p>";
while ($arElement = $rsDirContent->Fetch()):
    // folder?
    if ($arElement["TYPE"]=="D"):
        // print its name
        echo $arElement["NAME"];
    else: // file?
        // skip system files
        if ($arElement["NAME"]==".section.php") continue;
        // otherwise print its name
        echo $arElement["NAME"];
    endif;
endwhile;
?>


IsNavPrint

CDBResult::IsNavPrint

bool
CDBResult::IsNavPrint()

The method IsNavPrint determines if all records may fit in a single page.

Note
The method CDBResult::NavStart must be called prior to calling this function.

Parameters

No parameters.

Return Values

Returns false if all records fit in a single page, or false otherwise.

See Also

  • CDBResult::NavPrint
  • CDBResult::NavStart
  • CDBResult::NavNext

Example

<?
$arDirContent = array_merge($arDirs, $arFiles);
$rsDirContent = new CDBResult;
$rsDirContent->InitFromArray($arDirContent);
$rsDirContent->NavStart(50);
if($rsDirContent->IsNavPrint())
{
    echo "<p>";
    $rsDirContent->NavPrint("Files");
    echo "</p>";
}
?>


NavNext

CDBResult::NavNext

mixed
CDBResult::NavNext(
 bool init_globals = true,
 string prefix = "str_",
 bool safe_for_html = true
)

Returns an array of field values. If the parameter init_globals is set, the method defines global variables with names like prefix.field_name.

Note
The method operates variables of the global scope; take this fact into consideration when creating files of components.

Parameters

Parameter | Description
init_globals | If true, the method will define global variables named after names of the fields. Optional; true by default.
prefix | Prefix used to create names of the global variables (if init_globals is set). Optional; "str_" by default.
safe_for_html | Tells to convert global variables to the HTML safe format (if init_globals is set). Optional; true by default.

Return Values

Returns false if there is no more records, or the array of field values otherwise.

See Also

  • CDBResult::NavStart
  • CDBResult::Fetch
  • CDBResult::GetNext
  • CDBResult::ExtractFields

Example

<?
$rsBanners = CAdvBanner::GetList($by, $order, $arFilter, $is_filtered);
$rsBanners->NavStart(20);
echo $rsBanners->NavPrint("Banners");
while($rsBanners->NavNext(true, "f_")):
    echo "[".$f_ID."] ".$f_NAME."<br>";
endwhile;
echo $rsBanners->NavPrint("Banners");
?>


NavPrint

CDBResult::NavPrint

CDBResult::NavPrint(
 string title,
 bool show_always=false,
 string text_css_class="text",
 string template_path=false
)

The method NavPrint is used to display the pagewise navigation links. You have to call the method NavStart prior to calling this function.

By default, the session stores the last opened page of the pagewise navigation pool. If you want to alter the default behavior, you can make the following call prior to calling the NavPrint method:

CPageOption::SetOptionString("main", "nav_page_in_session", "N");

Parameters

Parameter | Description
title | Title of the displayed elements.
show_always | If set to false, the method does not display navigation links if all records fit in a single page. If true, the links are always displayed. Optional; false by default.
text_css_class | CSS class used to display the navigation links. Optional; "text" by default.
template_path | Path to the template used to display the navigation links. Set to false to use the default template.

Return Values

No return value.

See Also

  • CDBResult::NavStart
  • CDBResult::NavNext
  • CDBResult::IsNavPrint
  • Class CPageOption

Example

<?
$rsEvents = CAdv::GetEventList($f_ID,($by="s_def"),($order="desc"), $arF, $is_filtered);
$rsEvents->NavPrint("Events", false, "tablebodytext",
"/bitrix/modules/statistic/admin/adv_navprint.php");
?>

Sample navigation link templates

<?
echo('<font class="'.$StyleText.'">('.$title.' ');
echo(($this->NavPageNomer-1)*$this->NavPageSize+1);
echo(' - ');
if($this->NavPageNomer != $this->NavPageCount)
    echo($this->NavPageNomer * $this->NavPageSize);
else
    echo($this->NavRecordCount);
echo(' '.GetMessage("nav_of").' ');
echo($this->NavRecordCount);
echo(")\n \n</font>");

echo('<font class="'.$StyleText.'">');

if ($this->NavPageNomer > 1)
    echo('<a class="tablebodylink"
             href="'.$sUrlPath.'?PAGEN_'.$this->NavNum.'=1'.
                   $strNavQueryString.'#nav_start'.
                   $add_anchor.'">'.$sBegin.'</a> |
          <a class="tablebodylink"
             href="'.$sUrlPath.'?PAGEN_'.$this->NavNum.'='.
                   ($this->NavPageNomer-1).$strNavQueryString.
                   '#nav_start'.$add_anchor.'">'.$sPrev.'</a>');
else
    echo($sBegin.' | '.$sPrev);

echo(' | ');

$NavRecordGroup = $nStartPage;
while($NavRecordGroup <= $nEndPage)
{
    if($NavRecordGroup == $this->NavPageNomer)
        echo('<b>'.$NavRecordGroup.'</b> ');
    else
        echo('<a class="tablebodylink"
                 href="'.$sUrlPath.'?PAGEN_'.$this->NavNum.'='.
                       $NavRecordGroup.$strNavQueryString.'#nav_start'.
                       $add_anchor.'">'.$NavRecordGroup.'</a> ');
    $NavRecordGroup++;
}

echo('| ');
if($this->NavPageNomer < $this->NavPageCount)
    echo ('<a class="tablebodylink"
              href="'.$sUrlPath.'?PAGEN_'.$this->NavNum.'='.
                    ($this->NavPageNomer+1).$strNavQueryString.'#nav_start'.
                    $add_anchor.'">'.$sNext.'</a> |
           <a class="tablebodylink"
              href="'.$sUrlPath.'?PAGEN_'.$this->NavNum.'='.
                    $this->NavPageCount.$strNavQueryString.'#nav_start'.
                    $add_anchor.'">'.$sEnd.'</a> ');
else
    echo ($sNext.' | '.$sEnd.' ');

if($this->bShowAll)
    echo ($this->NavShowAll? '| <a class="tablebodylink"
                                   href="'.$sUrlPath.'?SHOWALL_'.$this->NavNum.'=0'.
                                         $strNavQueryString.'#nav_start'.
                                         $add_anchor.'">'.$sPaged.'</a> ' : '|
                                <a class="tablebodylink"
                                   href="'.$sUrlPath.'?SHOWALL_'.$this->NavNum.'=1'.
                                         $strNavQueryString.'#nav_start'.
                                         $add_anchor.'">'.$sAll.'</a> ');
echo('</font>');
?>


NavStart

CDBResult::NavStart

CDBResult::NavStart(
 int page_size=10,
 bool show_all=true,
 int page_number=false
)

The method NavStart splits the result of the selection into pages.

To make avail of the embedded automatic pagewise navigation system, you have to first call this method. After you call it, the scope of methods:

  • CDBResult::Fetch
  • CDBResult::GetNext
  • CDBResult::ExtractFields
  • CDBResult::NavNext
will be constrained to the current page rather than the whole selection. To display the pagewise navigation links, you can call the method CDBResult::NavPrint.

Parameters

Parameter | Description
page_size | Page size (1 or more). Optional; 10 by default.
show_all | Specifies to display all records (display the link All in the navigation bar). Optional; true by default.
page_number | Forces the display of the page with the specified number (disregarding the parameters passed on the URL). Optional; false by default (display as is).

Return Values

No return value.

See Also

  • CDBResult::NavNext
  • CDBResult::NavPrint
  • CDBResult::IsNavPrint
  • CDBResult::Fetch
  • CDBResult::GetNext
  • CDBResult::ExtractFields

Example

<?
$rsBanners = CAdvBanner::GetList($by, $order, $arFilter, $is_filtered);
$rsBanners->NavStart(20);
echo $rsBanners->NavPrint("Banners");
while($rsBanners->NavNext(true, "f_")):
    echo "[".$f_ID."] ".$f_NAME."<br>";
endwhile;
echo $rsBanners->NavPrint("Banners");
?>


NavStringForCache

CDBResult::NavStringForCache

string
CDBResult::NavStringForCache(
 int page_size=10,
 bool show_all=true,
 int page_number=false
)

The method NavStringForCache returns the string which uniquely identify the current state of pagewise navigation (number of the current page; display all records or not). The result returned is generally used for building the cache identifier which is used with classes CPageCache and CPHPCache.

Parameters

Parameter | Description
page_size | Page size (1 or more). Optional; 10 by default.
show_all | Specifies to display all records (display the link All in the navigation bar). Optional; true by default.
page_number | Forces the display of the page with the specified number (disregarding the parameters passed on the URL). Optional; false by default (display as is).

Return Values

State identifier.

See Also

  • Class CPageCache
  • Class CPHPCache

Example

<?
// create an instance
$obCache = new CPageCache;

// caching period of 30 minutes
$life_time = 30*60;

// create the ID string describing the current state
$nav = CDBResult::NavStringForCache($PAGE_ELEMENT_COUNT);

// create the cache ID depending on the parameters
// that may affect the resulting HTML
$cache_id = $nav.$ELEMENT_ID.$IBLOCK_TYPE.$USER->GetUserGroupString();

// initialise the buffered output
if($obCache->StartDataCache($life_time, $cache_id, "/")):

    // get a list of element
    if ($rsElements = GetIBlockElementList($IBLOCK_ID, $SECTION_ID)):

        // initialise the pagewise navigation
        $rsElements->NavStart($PAGE_ELEMENT_COUNT);

        // display the pagewise navigation
        echo $rsElements->NavPrint($ELEMENT_NAME);

        // iterate on elements
        while ($obElement = $rsElements->GetNextElement()):

            $arElement = $obElement->GetFields();
            $arProperty = $obElement->GetProperties();

            echo "<pre>"; print_r($arElement); echo "</pre>";
            echo "<pre>"; print_r($arProperty); echo "</pre>";

        endwhile;
    endif;

    // write out the buffered result to the cache file
    $obCache->EndDataCache();
endif;
?>


SelectedRowsCount

CDBResult::SelectedRowsCount

int
CDBResult::SelectedRowsCount()

The method SelectedRowsCount returns the number of records selected (the selection is carried out by issuing the SQL command SELECT ...).

Note
The Oracle version supports this method only after prior call to CDBResult::NavStart; of if the last record of the selection is retrieved.

Parameters

No parameters.

Return Values

Number of records selected.

See Also

  • CDBResult::AffectedRowsCount

Example

<?
$rsBanners = CAdvBanner::GetList($by, $order, $arFilter, $is_filtered);
$rsBanners->NavStart(20);
if (intval($rsBanners->SelectedRowsCount)>0):
    echo $rsBanners->NavPrint("Banners");
    while($rsBanners->NavNext(true, "f_")):
         echo "[".$f_ID."] ".$f_NAME."<br>";
    endwhile;
    echo $rsBanners->NavPrint("Banners");
endif;
?>


CEvent

CEvent is the class to handle mail events.

Methods

Method | Description
CheckEvents | Checks and sends the unsent mail events.
Send | Adds an event to the mail subsystem (registers event for dispatch).

See Also

  • Mail subsystem


CheckEvents

CEvent::CheckEvents

CEvent::CheckEvents()

The method CheckEvents collects the unsent mail events and sends them as e-mail messages. The function is automatically called at the start of every page and needs not to be called manually.

Parameters

No parameters.

See Also

  • Mail subsystem


Send

CEvent::Send

int
CEvent::Send(
 string event_type,
 mixed site,
 array fields,
 string duplicate="Y",
 int template_id=""
)

The method Send creates mail event which will be further sent as e-mail message. Returns the ID of this event.

Parameters

Parameter | Description
event_type | The mail event type ID.
site | The site ID or an array of site ID's.
fields | An array of mail event type fields whose ID is specified by the event_type parameter. The array has the following format: array("field"=>"value" [, ...]).
duplicate | Specifies that the message copy is to be sent to address indicated in the Kernel modules settings, field Comma-separated list of E-mail addresses to receive copies of all the outcoming messages. Optional. "Y" by default.
template_id | The ID of the mail template used to send the message. If this parameter is omitted or empty, the messages will be sent using all templates bound to the mail event type whose ID is specified by the event_type parameter, as well as templates bound to site(s) whose ID is specified by the site parameter. Optional. Empty by default.

See Also

  • Mail subsystem

Example

<?
$arEventFields = array(
    "ID"                  => $CONTRACT_ID,
    "MESSAGE"             => $mess,
    "EMAIL_TO"            => implode(",", $EMAIL_TO),
    "ADMIN_EMAIL"         => implode(",", $ADMIN_EMAIL),
    "ADD_EMAIL"           => implode(",", $ADD_EMAIL),
    "STAT_EMAIL"          => implode(",", $VIEW_EMAIL),
    "EDIT_EMAIL"          => implode(",", $EDIT_EMAIL),
    "OWNER_EMAIL"         => implode(",", $OWNER_EMAIL),
    "BCC"                 => implode(",", $BCC),
    "INDICATOR"           => GetMessage("AD_".strtoupper($arContract["LAMP"]."_CONTRACT_STATUS")),
    "ACTIVE"              => $arContract["ACTIVE"],
    "NAME"                => $arContract["NAME"],
    "DESCRIPTION"         => $description,
    "MAX_SHOW_COUNT"      => $arContract["MAX_SHOW_COUNT"],
    "SHOW_COUNT"          => $arContract["SHOW_COUNT"],
    "MAX_CLICK_COUNT"     => $arContract["MAX_CLICK_COUNT"],
    "CLICK_COUNT"         => $arContract["CLICK_COUNT"],
    "BANNERS"             => $arContract["BANNER_COUNT"],
    "DATE_SHOW_FROM"      => $arContract["DATE_SHOW_FROM"],
    "DATE_SHOW_TO"        => $arContract["DATE_SHOW_TO"],
    "DATE_CREATE"         => $arContract["DATE_CREATE"],
    "CREATED_BY"          => $CREATED_BY,
    "DATE_MODIFY"         => $arContract["DATE_MODIFY"],
    "MODIFIED_BY"         => $MODIFIED_BY
    );
$arrSITE =  CAdvContract::GetSiteArray($CONTRACT_ID);
CEvent::Send("ADV_CONTRACT_INFO", $arrSITE, $arEventFields);
?>


CEventMessage

CEventMessage is the class to deal with mail templates.

Fields

Field | Type | Description
ID | Int | mail template ID
EVENT_NAME | Varchar(50) | mail event ID
LID | Char(2) | language ID
TIMESTAMP_X | Datetime | Last template modification
ACTIVE | Char | active state (Y|N)
EMAIL_FROM | Varchar(255) | Sender
EMAIL_TO | Varchar(255) | Receiver
SUBJECT | Varchar(255) | Subject
MESSAGE | Text | Message body
BODY_TYPE | Char(4) | Message type (text|html)
BCC | Varchar(255) | BCC

Methods

Method | Description
GetList | Returns the filtered list of templates.
GetByID | Returns the template data by its ID.
Add | Adds a new template.
Update | Modifies the existing mail template.
Delete | Removes the template.

See Also

  • Mail subsystem


Add

CEventMessage::Add

mixed
CEventMessage::Add(
 array fields
)

The method Add adds a new mail template. Returns ID of the added template. In case of error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter Description
fields The array of field values of the format array("field"=>"value" [, ...]). The fields can be the following:
  • ACTIVE - mail template active state flag: "Y" - active; "N" - inactive;
  • EVENT_NAME - the mail event type ID;
  • SITE_ID - site ID;
  • EMAIL_FROM - the "From" field;
  • EMAIL_TO - the "To" field;
  • BCC - the "BCC" field;
  • SUBJECT - massage header;
  • BODY_TYPE - type of the mail message: "text" or "html";
  • MESSAGE - message body.

See Also

  • Fields of mail message template
  • CEventMessage::Update

Example

<?
$arr["ACTIVE"] = "Y";
$arr["EVENT_NAME"] = "ADV_CONTRACT_INFO";
$arr["SITE_ID"] = array("ru","en");
$arr["EMAIL_FROM"] = "#DEFAULT_EMAIL_FROM#";
$arr["EMAIL_TO"] = "#EMAIL_TO#";
$arr["BCC"] = "#BCC#";
$arr["SUBJECT"] = "subject";
$arr["BODY_TYPE"] = "text";
$arr["MESSAGE"] = "
Message body
";

$emess = new CEventMessage;
$emess->Add($arr);
?>


Delete

CEventMessage::Delete

mixed
CEventMessage::Delete(
 int id
)

The method Delete removes the mail template. Returns an instance of CDBResult on success, or false otherwise.

Parameters

Parameter | Description
id | the template ID

See Also

  • CDBResult class
  • OnEventMessageDelete event
  • OnBeforeEventMessageDelete event

Example

<?
if(intval($del_id)>0 && $MAIN_RIGHT=="W")
{
    $emessage = new CEventMessage;
    $DB->StartTransaction();
    if(!$emessage->Delete(intval($del_id)))
    {
        $DB->Rollback();
        $strError.=GetMessage("DELETE_ERROR");
    }
    else $DB->Commit();
}
?>


GetByID

CEventMessage::GetByID

CDBResult
CEventMessage::GetByID(
 int id
)

The method GetByID returns the mail template by its ID as the CDBResult instance.

Parameters

Parameter | Description
id | the template ID

See Also

  • Fields of mail message template
  • CEventMessage::GetList
  • CDBResult class

Example

<?
$rsEM = CEventMessage::GetByID($ID);
$arEM = $rsEM->Fetch();
echo "<pre>"; print_r($arEM); echo "</pre>";
?>


GetList

CEventMessage::GetList

CDBResult
CEventMessage::GetList(
 string &by="id",
 string &order="desc",
 array filter
)

The method GetList returns the list of mail templates as CDBResult instance.

Parameters

Parameter Description
by Reference to the variable containing the sorting field. The following values are possible:
  • site_id - site ID;
  • subject - subject;
  • timestamp_x - modification date;
  • event_name - event type;
  • id - template ID;
  • active - active state;
îrder Reference to the variable containing the sorting field. The following values are possible:
  • asc - ascending;
  • desc - descending;
filter An array of the format Array("filtered field"=>"value" [, ...]). The following values are possible:
  • ID - template ID;
  • TYPE - code and header of the event type (complex logic allowed);
  • TYPE_ID - the event type code (complex logic allowed);
  • TIMESTAMP_1 - lower bound of the modification date range ("from");
  • TIMESTAMP_2 - upper bound of the modification date range ("till");
  • SITE_ID - site ID (this field may contain either an array for disjunctive searches or complex logic can be used);
  • ACTIVE - active state flag (Y|N);
  • FROM - "From" field (complex logic allowed);
  • TO - "To" field (complex logic allowed);
  • BCC - "BCC" field (complex logic allowed);
  • SUBJECT - by message subject (complex logic allowed);
  • BODY_TYPE - by message body type (text|html);
  • BODY - by message body (complex logic allowed);

See Also

  • Fields of mail message template
  • CEventMessage::GetByID
  • CDBResult class

Example

<?
$arFilter = Array(
    "ID"            => "12 | 134",
    "TYPE"          => "contract & adv",
    "TYPE_ID"       => "ADV_BANNER | ADV_CONTRACT",
    "TIMESTAMP_1"   => "12.11.2001",
    "TIMESTAMP_2"   => "12.11.2005",
    "SITE_ID"       => "ru | en",
    "ACTIVE"        => "Y",
    "FROM"          => "bitrixsoft.com",
    "TO"            => "#TO#",
    "BCC"           => "admin",
    "SUBJECT"       => "contract",
    "BODY_TYPE"     => "text",
    "BODY"          => "auto"
    );
$rsMess = CEventMessage::GetList($by="site_id", $order="desc", $arFilter);
$is_filtered = $rsMess->is_filtered;
?>


Update

CEventMessage::Update

bool
CEventMessage::Update(
 int id,
 array fields
)

The method Update modifies the mail template defined by the ID. Returns "true" on success. In case of error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter | Description
id | the ID of the updated record
fields | An array of the fields values in the format array("field"=>"value" [, ...]).

See Also

  • Fields of mail message template
  • CEventMessage::Add

Example

<?
if($REQUEST_METHOD=="POST" && (strlen($save)>0 || strlen($apply)>0)&& $MAIN_RIGHT=="W")
{
    $em = new CEventMessage;
    $arFields = Array(
        "ACTIVE"        => $ACTIVE,
        "EVENT_NAME"    => $EVENT_NAME,
        "LID"           => $LID,
        "EMAIL_FROM"    => $EMAIL_FROM,
        "EMAIL_TO"      => $EMAIL_TO,
        "BCC"           => $BCC,
        "SUBJECT"       => $SUBJECT,
        "MESSAGE"       => $MESSAGE,
        "BODY_TYPE"     => $BODY_TYPE
        );
    if($ID>0)
    {
        $res = $em->Update($ID, $arFields);
    }
    else
    {
        $ID = $em->Add($arFields);
        $res = ($ID>0);
    }
    if(!$res)
    {
        $strError .= $em->LAST_ERROR."<br>";
        $bVarsFromForm = true;
    }
    else
    {
        if (strlen($save)>0)
            LocalRedirect(BX_ROOT."/admin/message_admin.php?lang=".LANGUAGE_ID);
        else
            LocalRedirect(BX_ROOT."/admin/message_edit.php?lang=".LANGUAGE_ID."&ID=".$ID);
    }
}
?>


CEventType

CEventType is the class to handle mail event types.

Fields

Field | Type | Description
ID | Int | Mail event type ID.
EVENT_NAME | Varchar(50) | Mail event ID.
LID | Char(2) | Language ID.
SORT | Int | Sort order.
NAME | Varchar(100) | Name.
DESCRIPTION | Text | Description containing text with macros in the format #field# - description.

Methods

Method | Description
GetList | Returns the filtered list of mail event types.
GetByID | Returns the mail event type by its ID.
Add | Adds a new type.
Delete | Removes the type.

See Also

  • Mail subsystem


Add

CEventType::Add

mixed
CEventType::Add(
 array fields
)

The method Add adds the mail event type. Returns the ID of the added template. In case of error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter Description
fields An array of the field values of the format array("field"=>"value" [, ...]). The fields can be the following:
  • SITE_ID - site ID;
  • EVENT_NAME - mail event type ID;
  • NAME - header of the mail event type;
  • DESCRIPTION - description defining fields of the mail event type.

See Also

  • Fields of event type

Example

<?
function UET($EVENT_NAME, $NAME, $SITE_ID, $DESCRIPTION)
{
    $et = new CEventType;
    $et->Add(array(
        "SITE_ID"       => $SITE_ID,
        "EVENT_NAME"    => $EVENT_NAME,
        "NAME"          => $NAME,
        "DESCRIPTION"   => $DESCRIPTION
        ));
}

UET(
"ADV_BANNER_STATUS_CHANGE","Banner state has changed","ru",
"
#EMAIL_TO# - EMail of the message receiver (#OWNER_EMAIL#)
#ADMIN_EMAIL# - EMail of the users with roles \"banner manager\" and \"administrator\"
#ADD_EMAIL# - EMail of the users permitted to manage the contract banners
#STAT_EMAIL# - EMail of the users permitted to view the contract banners
#EDIT_EMAIL# - EMail of the users permitted to modify some contract fields
#OWNER_EMAIL# - EMail of the users with any permission for the contract
#BCC# - BCC (#ADMIN_EMAIL#)
#ID# - banner ID
#CONTRACT_ID# - contract ID
#CONTRACT_NAME# - contract header
#TYPE_SID# - type ID
#TYPE_NAME# - type header
#STATUS# - status
#STATUS_COMMENTS# - status comment
#NAME# - banner header
#GROUP_SID# - banner group
#INDICATOR# - whether the banner is displayed or not
#ACTIVE# - active state flag of the banner [Y | N]
#MAX_SHOW_COUNT# - maximum banner shows
#SHOW_COUNT# - number of banner shows
#MAX_CLICK_COUNT# - maximum banner clicks
#CLICK_COUNT# - number of banner clicks
#DATE_LAST_SHOW# - date of the last banner show
#DATE_LAST_CLICK# - date of the last banner click
#DATE_SHOW_FROM# - date the banner is published
#DATE_SHOW_TO# - date the banner is revoked
#IMAGE_LINK# - URL of the banner image
#IMAGE_ALT# - tooltip text
#URL# - banner link URL
#URL_TARGET# - target frame to open the banner URL
#CODE# - banner code
#CODE_TYPE# - type of the banner code (text | html)
#COMMENTS# - banner comments
#DATE_CREATE# - date of the banner creation
#CREATED_BY# - person who created the banner
#DATE_MODIFY# - date of the banner modification
#MODIFIED_BY# - person who modified the banner
"
);
?>


Delete

CEventType::Delete

CDBResult
CEventType::Delete(
 string type_id
)

The method Delete removes the mail event type. Returns an instance of CDBResult.

Parameters

Parameter | Description
type_id | Mail event type.

See Also

  • CDBResult class>

Example

<?
$et = new CEventType;
$et->Delete("ADV_BANNER_STATUS_CHANGE");
?>


GetByID

CEventType::GetByID

CDBResult
CEventType::GetByID(
 string type_id,
 string site_id
)

The method GetByID returns the mail event type by its ID as the CDBResult instance.

Parameters

Parameter | Description
type_id | The mail event type ID.
site_id | The site ID.

See Also

  • Fields of event type
  • CEventType::GetList
  • CDBResult class>

Example

<?
$rsET = CEventType::GetByID("ADV_BANNER_STATUS_CHANGE", "ru");
$arET = $rsET->Fetch();
?>


GetList

CEventType::GetList

CDBResult
CEventType::GetList(
 array filter
)

The method GetList returns the filtered list of mail event types as CDBResult instance.

Parameters

Parameter Description
filter The filter array of the format array("filtered field"=>"value" [, ...]). The following values are possible:
  • TYPE_ID - the event type ID;
  • LID - the language ID.

See Also

  • Fields of event type
  • CEventType::GetByID
  • CDBResult class>

Example

<?
$arFilter = array(
    "TYPE_ID" => "ADV_BANNER_STATUS_CHANGE",
    "LID"     => "ru"
    );
$rsET = CEventType::GetList($arFilter);
while ($arET = $rsET->Fetch())
{
    echo "<pre>"; print_r($arET); echo "</pre>";
}
?>


CFile

The CFile class is used to handle files and images.

Fields

Field | Type | Description
ID | int | The file ID.
TIMESTAMP_X | timestamp | Record modification date.
MODULE_ID | varchar(50) | The ID of the module to which the file belongs.
HEIGHT | int | Image height (for image files).
WIDTH | int | Image width (for image files).
FILE_SIZE | int | File size (bytes).
CONTENT_TYPE | varchar(255) | File MIME type.
SUBDIR varchar(255) Directory containing the file. Base directory used for file storage is set in the parameter File upload default folder in the Kernel module settings. You can obtain the value of this parameter by the following call:
COption::GetOptionString("main", "upload_dir", "upload");
FILE_NAME | varchar(255) | File name on the server.
ORIGINAL_NAME | varchar(255) | Original name of the file, as it has been uploaded to the server.
DESCRIPTION | varchar(255) | File description.

Methods

Method | Description
GetByID | Returns information on a registered file.
GetPath | Returns the root path of a registered file.
ShowImage | Returns the HTML code that can be used to display an image file.
Show2Images | Returns the HTML code used to display a smaller image with a link which opens a new window with a larger image.
CheckFile | Verifies the size, extension and mime type of the file.
CheckImageFile | Ensures the file is an image and checks its parameters.
IsImage | Checks the file extension and MIME type. Returns true if the file extension and type corresponds to an image file.
MakeFileArray | Creates an array describing a single file. Structure of the array is similar to that of $_FILES[name] (or $HTTP_POST_FILES[name]). This array can be used with methods SaveFile, CheckFile, CheckImageFile.
InputFile | Returns the HTML form code that can be used to upload a new or replace an existing file.
SaveFile | Saves a file and registers it in the file table.
UpdateDesc | Updates the registered file description.
CopyFile | Copies the registered file and returns the ID of a copy.
Delete | Removes a file from the file registrar table and deletes it from the disk.


CheckFile

CFile::CheckFile

string
CFile::CheckFile(
 array file,
 int max_size = 0,
 string mime_types = false,
 string extensions = false
)

The method CheckFile verifies the size, extension and mime type of the file. In case of an error, the method returns a string containing the error description.

Parameters

Parameter Description
file Array with the file information in the format:

Array(
    "name" => "file name",
    "size" => "size",
    "tmp_name" => "temporary file path on server",
    "type" => "file type ",
    "del" => "flag (Y|N) specifying to delete"
             "the existing file from the database",
    "MODULE_ID" => "module name")
This array can be obtained, for example, by joining arrays $_FILES[field_name] and Array("del" => ${"field_name"."_del"}, "MODULE_ID" = "module_name").
max_size Maximum size of a file in bytes.
Optional. The default value is "0", which means no restriction applies.
mime_types Allowed mime type of a file (e.g. "image/"). Verification is performed using data received from a user, this is why you should use extensions for safer checks.
Optional. The default value is false, which means no restriction applies.
extensions Allowed file extensions separated with comma.
Optional. The default value is false, which means no restriction applies.

See Also

  • CFile::CheckImageFile
  • CFile::IsImage

Example

<?
$arrFile = array_merge(
    $_FILES["ATTACHED_IMAGE"],
    array("del" => ${"ATTACHED_IMAGE_del"}, "MODULE_ID" => "forum"));

$res = CFile::CheckFile($arrFile, 200, "image/", CFile::GetImageExtensions());
if (strlen($res)>0) $strError .= $res."<br>";
?>


CheckImageFile

CFile::CheckImageFile

string
CFile::CheckImageFile(
 array file,
 int max_size = 0,
 int max_width = 0,
 int max_height = 0
)

The method CheckImageFile ensures the file is an image and checks its parameters. In case of an error, the method returns a string containing the error description.

Parameters

Parameter Description
file Array with the file information in the format:

Array(
    "name" => "file name",
    "size" => "size",
    "tmp_name" => "temporary file path on server",
    "type" => "file type ",
    "del" => "flag (Y|N) specifying to delete"
             "the existing file from the database",
    "MODULE_ID" => "module name")
This array can be obtained, for example, by joining arrays $_FILES[field_name] and Array("del" => ${"field_name"."_del"}, "MODULE_ID" = "module_name").
max_size Maximum size of a file, in bytes.
Optional. The default value is "0", which means no restriction applies.
max_width Maximum width of the image, in pixels.
Optional. The default value is "0", which means no restriction applies.
max_height Maximum height of the image, in pixels.
Optional. The default value is "0", which means no restriction applies.

See Also

  • CFile::CheckFile
  • CFile::IsImage

Example

<?
$arrFile = array_merge(
    $_FILES["ATTACHED_IMAGE"],
    array("del" => ${"ATTACHED_IMAGE_del"}, "MODULE_ID" => "forum"));

$res = CFile::CheckImageFile($arrFile, 200, 50, 50);
if (strlen($res) > 0)
    $strError .= $res."<br>";
?>


CopyFile

CFile::CopyFile

int
CFile::CopyFile(
 int file_id
)

The method CopyFile copies the registered file and returns the ID of a copy.

Parameters

Parameter | Description
file_id | Numeric ID of the file to be copied.

See Also

  • CopyDirFiles

Example

<?
if ($rsElements = GetIBlockElementListEx($IBLOCK_TYPE,
                                         $IBLOCK_ID,
                                         false,
                                         array($ELEMENT_SORT_FIELD => $ELEMENT_SORT_ORDER,
                                               "ID" => "ASC"),
                                         false, $arrFilter)):
    $rsElements->NavStart($PAGE_ELEMENT_COUNT);
    while ($obElement = $rsElements->GetNextElement()):
        $arElement = $obElement->GetFields();
        $arrNewImages[$arElement["ID"]][] =
                      CFile::CopyFile($arElement["PREVIEW_PICTURE"]);
    endwhile;
endif;
?>


Delete

CFile::Delete

CFile::Delete(
 int id
)

The method Delete removes a file from the file registrar table (b_file) and deletes it from the disk.

Parameters

Parameter | Description
id | Numeric ID of the file.

See Also

  • DeleteDirFiles
  • DeleteDirFilesEx

Example

<?
// delete the form image
$arFilter = array("ID" => 1, "ID_EXACT_MATCH" => "Y");
$rsForm = CForm::GetList($by, $order, $arFilter, $is_filtered);
if ($arForm = $rsForm->Fetch())
{
    if (intval($arForm["IMAGE_ID"])>0) CFile::Delete($arForm["IMAGE_ID"]);
}
?>


GetByID

CFile::GetByID

CDBResult
CFile::GetByID(
 int file_id
)

The method GetByID returns information on a registered file as an instance of the CDBResult class.

Parameters

Parameter | Description
file_id | Numeric ID of the file.

See Also

  • File fields
  • CFile::GetPath
  • CFile::InputFile
  • CFile::SaveFile
  • CFile::CopyFile
  • CFile::Delete

Example

<?
if ($rsElements = GetIBlockElementListEx($IBLOCK_TYPE,
                                         $IBLOCK_ID, false,
                                         array($ELEMENT_SORT_FIELD => $ELEMENT_SORT_ORDER,
                                               "ID" => "ASC"),
                                         false, $arrFilter)):
    $rsElements->NavStart($PAGE_ELEMENT_COUNT);
    while ($obElement = $rsElements->GetNextElement()):
        $arElement = $obElement->GetFields();
        $rsFile = CFile::GetByID($arElement["PREVIEW_PICTURE"]);
        $arFile = $rsFile->Fetch();
        $arrImages[$arElement["ID"]][] = $arFile;
    endwhile;
endif;
?>


GetPath

CFile::GetPath

string
CFile::GetPath(
 int file_id
)

The method GetPath returns the root path of a registered file.

Parameters

Parameter | Description
file_id | File ID.

See Also

  • CFile::GetByID

Example

<?
if ($rsElements = GetIBlockElementListEx($IBLOCK_TYPE,
                                         $IBLOCK_ID,
                                         false,
                                         array($ELEMENT_SORT_FIELD => $ELEMENT_SORT_ORDER,
                                               "ID" => "ASC"),
                                         false, $arrFilter)):
  $rsElements->NavStart($PAGE_ELEMENT_COUNT);
  while ($obElement = $rsElements->GetNextElement()):
    $arElement = $obElement->GetFields();
    $arImagesPath[$arElement["PREVIEW_PICTURE"]] =
        CFile::GetPath($arElement["PREVIEW_PICTURE"]);
  endwhile;
endif;
?>


InputFile

CFile::InputFile

string
CFile::InputFile(
 string input_file_name,
 int input_file_width,
 int file_id,
 string file_path = false,
 int file_max_size = 0,
 string file_type = "IMAGE",
 string add_to_input_file = "class=typefile",
 int input_description_width = 0,
 string add_to_input_description = "class=typeinput",
 string add_to_checkbox_delete = "",
 bool show_file_info = true,
)

The method InputFile returns the HTML form code that can be used to upload a new or replace an existing file.

Parameters

Parameter | Description
input_file_name Name of the file input field:
<input type="file" name="input_file_name" ... >
input_file_width Width of the file input field:
<input type="file" size="input_file_width" ... >
file_id | Numeric ID of the existing file.
file_path Root path of a folder to contain files. For example: "/upload/iblock/".

Optional. False by default, which means system settings are used.
file_max_size Maximum file size, in bytes:
<input type="hidden" name="MAX_FILE_SIZE" value="file_max_size">
Optional. The default value is "0", which means no restriction applies.
file_type File type. If "IMAGE", the file information will contain image dimensions.

Optional. The default value is "IMAGE".
add_to_input_file Arbitrary HTML code to insert in the file input tag:
<input type="file" add_to_input_file ... >
Optional. The default value is "class=typefile", which sets the common CSS selector for file input fields in the administrative section.
input_description_width Width of the file comment input field:
<input type="text" size="input_description_width" ... >
Optional. The default value is "0", which hides the comment field.
add_to_input_description Arbitrary HTML code to insert in the file comment input field:
<input type="text" add_to_input_description ... >
Optional. The default value is "class=typeinput", which sets the common CSS selector for single line text input fields in the administrative section.
add_to_checkbox_delete Arbitrary HTML code to insert in the file deletion checkbox field:
<input type="checkbox" name="input_file_name_del" value="Y" add_to_checkbox_delete ... >
Optional.
show_file_info Allows to show or hide the file information (size and dimensions).

Optional. The default value is true, which displays the file information.

See Also

  • CFile::SaveFile

Example

<tr valign="top">
    <td align="right"><font
                       class="tablefieldtext">
                       <?=GetMessage("VOTE_IMAGE")?></font></td>
    <td><font class="tablebodytext"><?
    echo CFile::InputFile("IMAGE_ID", 20, $str_IMAGE_ID);
    if (strlen($str_IMAGE_ID)>0):
        ?><br><?echo CFile::ShowImage($str_IMAGE_ID,
                                      200, 200,
                                      "border=0", "", true);
    endif;
    ?></font>
    </td>
</tr>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


IsImage

CFile::IsImage

string
CFile::IsImage(
 string file_name,
 mixed mime_type = false
)

The method IsImage checks the file extension and MIME type. Returns true if the file extension and type corresponds to an image file, or false otherwise.

Parameters

Parameter | Description
file_name | File name (without path).
mime_type | MIME type (e.g. "image/"). Optional. The default value is "false", which disables checks for MIME type.

See Also

  • CFile::CheckImageFile
  • CFile::CheckFile

Example

<?
if ($rsFiles = CTicket::GetFileList($v1="s_id",
                                    $v2="asc",
                                    array("HASH" => $hash))) :
  if ($arFile = $rsFiles->Fetch()) :
    $filename = $_SERVER["DOCUMENT_ROOT"]."/".
                COption::GetOptionString("main",
                                         "upload_dir",
                                         "upload")."/".
                $arFile["SUBDIR"]."/".$arFile["FILE_NAME"];
    if ($f = fopen($filename, "rb"))
    {
      $is_image = CFile::IsImage($arFile["FILE_NAME"],
                                 $arFile["CONTENT_TYPE"]);
      // if image
      if ($is_image)
      {
        // send as image
        header("Content-type: ".$arFile["CONTENT_TYPE"]);
        header("Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0");
        header("Expires: 0");
        header("Pragma: public");
        while ($buffer = fread($f, 4096)) echo $buffer;
      }
      else
      {
        // send as text
        header("Content-type: text/html; charset=".LANG_CHARSET);
        header("Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0");
        header("Expires: 0");
        header("Pragma: public");
        echo "<pre>";
        while ($buffer = fread($f, 4096))
            echo htmlspecialchars($buffer);
        echo "</pre>";
      }
      fclose ($f);
      die();
    }
  endif;
endif;
?>


MakeFileArray

CFile::MakeFileArray

array
CFile::MakeFileArray(
 mixed file,
 mixed mime_type = false
)

The method MakeFileArray creates an array describing a single file. Structure of the array is similar to that of $_FILES[name] (or $HTTP_POST_FILES[name]). This array can be used with methods SaveFile, CheckFile, CheckImageFile. The array returned has the following format:

Array(
    "name" => "file name",
    "size" => "size",
    "tmp_name" => "temporary path on server",
    "type" => "file type")

Parameters

Parameter Description
file Can be one of the following values:
  • ID of the file registered with CFile;
  • fully qualified file path (relative to disk root);
  • URL of an external file (on other server).
mime_type File MIME type (e.g. "image/gif").

Optional. The default value is "false", which means the MIME type is to be determined automatically.

See Also

  • CFile::SaveFile
  • CFile::CheckFile
  • CFile::CheckImageFile

Example

<?
$arFile = CFile::MakeFileArray($_SERVER["DOCUMENT_ROOT"]."/images/screen.gif");
$arFile["MODULE_ID"] = "support";
$arFields = array(
  "CREATED_MODULE_NAME"   => "mail",
  "MODIFIED_MODULE_NAME"  => "mail",
  "OWNER_SID"             => "user@mail.com",
  "SOURCE_SID"            => "email",
  "MESSAGE_AUTHOR_SID"    => "user@mail.com",
  "MESSAGE_SOURCE_SID"    => "email",
  "TITLE"                 => "title",
  "MESSAGE"               => "message"
  "FILES"                 => array($arFile)
  );
//$TICKET_ID = 866;
$NEW_TICKET_ID = CTicket::Set($arFields, $MESSAGE_ID, $TICKET_ID, "N");
?>


SaveFile

CFile::SaveFile

mixed
CFile::SaveFile(
 array file,
 string save_path
)

The method SaveFile saves a file and registers it in the file table (b_file).

Parameters

Parameter | Description
file Array with file data in the following format:
Array(
    "name" => "file name",
    "size" => "size",
    "tmp_name" => "temporary path on server",
    "type" => "file type",
    "old_file" => "ID of old file",
    "del" => "flag (Y|N) specifying to delete"
             "the existing file from the database",
    "MODULE_ID" => "module name");
This array can be obtained, for example, by joining arrays $_FILES[field_name] and Array("del" => ${"field_name"."_del"}, "MODULE_ID" = "module_name").
save_path | Path to folder with (relative to /upload).

See Also

  • RewriteFile
  • CFile::InputFile

Example

<?
if (strlen($save)>0 && $REQUEST_METHOD=="POST")
{
    $arIMAGE = $_FILES["IMAGE_ID"];
    $z = $DB->Query("SELECT IMAGE_ID FROM b_vote WHERE ID='$ID'",
                    false, $err_mess.__LINE__);
    $zr = $z->Fetch();
    $arIMAGE["old_file"] = $zr["IMAGE_ID"];
    $arIMAGE["del"] = ${"IMAGE_ID_del"};
    $arIMAGE["MODULE_ID"] = "vote";
    if (strlen($arIMAGE["name"])>0 || strlen($arIMAGE["del"])>0)
    {
        $fid = CFile::SaveFile($arIMAGE, "vote");
        if (intval($fid)>0) $arFields["IMAGE_ID"] = intval($fid);
        else $arFields["IMAGE_ID"] = "null";
        $DB->Update("b_vote",$arFields,
                    "WHERE ID='".$ID."'",$err_mess.__LINE__);
    }
}
?>


CFile::Show2Images

string
CFile::Show2Images(
 mixed image1,
 mixed image2,
 int max_width = 0,
 int max_height = 0,
 string image_params = "border=0",
 string popup_alt = false,
 int image_width = 0,
 int image_height = 0
)

The method Show2Images returns the HTML code used to display a smaller image with a link which opens a new window with a larger image.

Parameters

Parameter | Description
image1 | The ID or path to the file within the current site, or URL to an external file on other server. If this parameter specified path to a file within the current site, it must be defined relative to the root. This parameters specifies the smaller image.
image2 | The ID or path to the file within the current site, or URL to an external file on other server. If this parameter specified path to a file within the current site, it must be defined relative to the root. This parameters specifies the larger image displayed in a popup window.
max_width | Maximum width of the smaller image. If the real width is larger than max_width, it will be proportionally scaled. Optional. The default value is "0", which means no restriction applies.
max_height | Maximum height of the smaller image. If the real height is larger than max_height, it will be proportionally scaled. Optional. The default value is "0", which means no restriction applies.
image_params | Arbitrary HTML code to be added to the IMG tag of the smaller image: <img image_params ...> Optional. The default value is "border=0".
popup_alt | Text of the image tooltip. Optional. The default text is "Click to enlarge" in the page language.
image_width | Image width, in pixels. Meaningful if only the image parameters specifies URL beginning with "http://". Optional. The default value is "0".
image_height | Image height, in pixels. Meaningful if only the image parameters specifies URL beginning with "http://". Optional. The default value is "0".

See Also

  • CFile::ShowImage

Example

<?
if ($rsElements =
        GetIBlockElementListEx($IBLOCK_TYPE,
                               $IBLOCK_ID,
                               false,
                               array($ELEMENT_SORT_FIELD =>
                                     $ELEMENT_SORT_ORDER,
                                     "ID" => "ASC"),
                               false, $arrFilter)):
    $rsElements->NavStart($PAGE_ELEMENT_COUNT);
    while ($obElement = $rsElements->GetNextElement()):
        $arElement = $obElement->GetFields();
        $image1 = intval($arElement["PREVIEW_PICTURE"])<=0 ?
                                       $arElement["DETAIL_PICTURE"] :
                                       $arElement["PREVIEW_PICTURE"];
        $image2 = intval($arElement["DETAIL_PICTURE"])<=0 ?
                                       $arElement["PREVIEW_PICTURE"] :
                                       $arElement["DETAIL_PICTURE"];
        echo CFile::Show2Images($image1, $image2, 150, 150,
                                          "hspace='0' vspace='0' "
                                          "border='0' title='".
                                          $arElement["NAME"]."'",
                                          true);
    endwhile;
endif;
?>


ShowImage

CFile::ShowImage

string
CFile::ShowImage(
 mixed image,
 int max_width = 0,
 int max_height = 0,
 string image_params = "border=0",
 string url = "",
 bool popup = false,
 string popup_alt = false,
 int image_width = 0,
 int image_height = 0
)

The method ShowImage returns the HTML code that can be used to display an image file.

Parameters

Parameter | Description
image | The ID or path to the file within the current site, or URL to an external file on other server. If this parameter specified path to a file within the current site, it must be defined relative to the root.
max_width | Maximum width of an image. If the real width is larger than max_width, it will be proportionally scaled. Optional. The default value is "0", which means no restriction applies.
max_height | Maximum height of an image. If the real height is larger than max_height, it will be proportionally scaled. Optional. The default value is "0", which means no restriction applies.
image_params | Arbitrary HTML code to be added to the IMG tag of the smaller image: <img image_params ...> Optional. The default value is "border=0".
url | Link to open upon click on the image. Optional. The default value is "", which means do not display link.
popup | Specifies to open a new window upon click. Optional. The default value is "false".
popup_alt | Text of the image tooltip (if popup is true). Optional. The default text is "Click to enlarge" in the page language.
image_width | Image width, in pixels. Meaningful if only the image parameters specifies URL beginning with "http://". Optional. The default value is "0".
image_height | Image height, in pixels. Meaningful if only the image parameters specifies URL beginning with "http://". Optional. The default value is "0".

See Also

  • CFile::Show2Images

Example

<tr valign="top">
    <td align="right"><font class="tablefieldtext"><?echo
    GetMessage("VOTE_IMAGE")?></font></td>
    <td><font class="tablebodytext"><?
    echo CFile::InputFile("IMAGE_ID", 20, $str_IMAGE_ID);
    if (strlen($str_IMAGE_ID)>0):
        ?><br><?
        echo CFile::ShowImage($str_IMAGE_ID, 200, 200, "border=0", "", true);
    endif;
    ?></font>
    </td>
</tr>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


UpdateDesc

CFile::UpdateDesc

CDBResult
CFile::UpdateDesc(
 int file_id,
 string description
)

The method UpdateDesc updates the registered file description. Returns an instance of the CDBResult class.

Parameters

Parameter | Description
file_id | Numeric ID of the file.
description | New file description.

See Also

  • RewriteFile
  • CMain::SaveFileContent
  • CFile::GetByID

Example

<?
if ($rsElements =
        GetIBlockElementListEx($IBLOCK_TYPE,
                               $IBLOCK_ID, false,
                               array($ELEMENT_SORT_FIELD => $ELEMENT_SORT_ORDER,
                                     "ID" => "ASC"),
                               false, $arrFilter)):
    $rsElements->NavStart($PAGE_ELEMENT_COUNT);
    while ($obElement = $rsElements->GetNextElement()):
        $arElement = $obElement->GetFields();
        CFile::UpdateDesc($arElement["PREVIEW_PICTURE"],
                                    "Element # ".$arElement["ID"]);
    endwhile;
endif;
?>


CGroup

CGroup is the class to deal with the user groups.

Fields

Field | Type | Description
ID | Int | Group ID.
TIMESTAMP_X | datetime | Date and time of the last modification.
ACTIVE | char | Active state (Y|N).
NAME | varchar (50) | Name of the group.
DESCRIPTION | varchar (255) | Description.

Methods

Method | Description
GetList | Returns a filtered list of groups.
GetByID | Returns the user group by its ID.
GetGroupUser | Returns an array of all users of the group.
Add | Adds a new group of users.
Update | Modifies the existing group.
Delete | Removes group.


Add

CGroup::Add

mixed
CGroup::Add(
 array fields
)

The method Add adds a new group and returns the ID of the added group. In case of error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter | Description
fields | An array of the fields value of the format array("field"=>"value" [, ...]).

See Also

  • CGroup fields
  • CGroup::Delete
  • CGroup::Update

Example

<?
$group = new CGroup;
$arFields = Array(
  "ACTIVE"       => "Y",
  "C_SORT"       => 100,
  "NAME"         => "Name of the group",
  "DESCRIPTION"  => "Description of the group",
  "USER_ID"      => array(128, 134)
  );
$NEW_GROUP_ID = $group->Add($arFields);
if (strlen($group->LAST_ERROR)>0) ShowError($group->LAST_ERROR);
?>


Delete

CGroup::Delete

mixed
CGroup::Delete(
 int id
)

The method Delete removes group. Returns an instance of CDBResult on success, or false otherwise.

Parameters

Parameter | Description
id | Group ID.

See Also

  • CGroup::Add
  • CGroup::Update
  • OnBeforeGroupDelete event
  • OnGroupDelete event

Example

<?
if(IntVal($del_id)>2)
{
  $del_id = IntVal($del_id);
  $group = new CGroup;
  $DB->StartTransaction();
  if(!$group->Delete($del_id))
  {
    $DB->Rollback();
    $strError.=GetMessage("DELETE_ERROR");
  }
  $DB->Commit();
}
?>


GetByID

CGroup::GetByID

CDBResult
CGroup::GetByID(
 int id,
 string get_users_amount = "N"
)

The method GetByID returns the user group by its ID as an instance of CDBResult class.

Parameters

Parameter | Description
id | Group ID.
get_users_amount | If set to "Y", the selection will include the field "USERS" containing the number of users in the group; if set to "N", the selection will not include such field (default behaviour).

See Also

  • CGroup fields
  • CGroup::GetList

Example

<?
$rsGroup = CGroup::GetByID(2, "Y");
$arGroup = $rsGroup->Fetch();
echo "<pre>"; print_r($arGroup); echo "</pre>";
?>


GetGroupUser

CGroup::GetGroupUser

array
CGroup::GetGroupUser(
 int group_id
)

The method GetGroupUser returns an array of all users of the group specified by the group ID parameter.

Parameters

Parameter | Description
group_id | Group ID.

See Also

  • CGroup fields
  • CUser fields

Example

<?
$arUsers = CGroup::GetGroupUser(1);
echo "<pre>"; print_r($arUsers); echo "</pre>";
?>


GetList

CGroup::GetList

CDBResult
CGroup::GetList(
 string &by = "c_sort",
 string &order = "asc",
 array filter,
 string get_users_amount = "N"
)

The method GetList returns a list of groups as an instance of CDBResult class.

Parameters

Parameter | Description
by Reference to the variable containing the sorting field. The following values are possilble:
  • id - group ID;
  • timestamp_x - date of modification;
  • name - name;
  • active - active state;
  • c_sort - sort order;
  • description - description;
  • users - number of users in a group.
îrder Reference to the variable containing the sort order. The following values are possible:
  • asc - ascending;
  • desc - descending.
filter An array used to filter users. The following keys are possible:
  • ID - group ID (complex logic allowed);
  • TIMESTAMP_1 - lower bound of the settings modification date range ("from");
  • TIMESTAMP_2 - upper bound of the settings modification date range ("till");
  • ACTIVE - filter by active state (Y|N);
  • ADMIN - filter by group type ("Y" - administrators| "N" - not administrators);
  • NAME - by name (complex logic allowed);
  • DESCRIPTION - by description (complex logic allowed);
  • USERS_1 - lower bound of the number of users ("from");
  • USERS_2 - upper bound of the number of users ("to").
get_users_amount | If set to "Y", the selection will include the field "USERS" containing the number of users in the group; if set to "N", the selection will not include such field (default behaviour).

See Also

  • CGroup fields
  • CGroup::GetByID

Example

<?
$filter = Array
(
    "ID"             => "1 | 2",
    "TIMESTAMP_1"    => "04.02.2004", // in the format of the current site
    "TIMESTAMP_2"    => "04.02.2005",
    "ACTIVE"         => "Y",
    "NAME                 => "Techsupport",
    "DESCRITION"     => "special | support",
    "USERS_1"        => "2", // from 2 users
    "USERS_2"        => "10" // to 10 users
);
$rsGroups = CGroup::GetList(($by="c_sort"), ($order="desc"), $filter); // select groups
$is_filtered = $rsGroups->is_filtered; // whether the selection is filtered
$rsGroups->NavStart(50); // paginate by 50 records
echo $rsGroups->NavPrint(GetMessage("PAGES")); // display per page navigation
while($rsGroups->NavNext(true, "f_")) :
    echo "[".$f_ID."] ".$f_NAME." ".$f_DESCRIPTION."<br>";
endwhile;
?>


Update

CGroup::Update

bool
CGroup::Update(
 int id,
 array fields
)

The method Update modifies the group defined by the ID. Returns "true" on success. In case of error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter | Description
id | the ID of the updated record.
fields | An array of the fields values in the format array("field"=>"value" [, ...]).

See Also

  • CGroup fields
  • CGroup::Add
  • CGroup::Delete

Example

<?
$group = new CGroup;
$arFields = Array(
  "ACTIVE"       => "Y",
  "C_SORT"       => 100,
  "NAME"         => "Name of the group",
  "DESCRIPTION"  => "Description of the group",
  "USER_ID"      => array(128, 134)
  );
$group->Update($GROUP_ID, $arFields);
if (strlen($group->LAST_ERROR)>0) ShowError($group->LAST_ERROR);
?>


CLanguage

CLanguage is the class to handle languages of the system.

Fields

Field | Type | Description
LID | char(2) | Double-character language ID.
SORT | int | Sort order.
DEF | char | Language by default (Y|N).
ACTIVE | char | Active state (Y|N).
NAME | varchar (50) | Name.
FORMAT_DATE | varchar (50) | Date format for the administrative section.
FORMAT_DATETIME | varchar (50) | Time and date format for the administartive section.
CHARSET | varchar (255) | Charset used to display pages in this language.

Methods

Method | Description
GetList | Returns the list of languages.
GetByID | Returns information on the specified language.
SelectBox | Creates the drop-down list of languages.
Add | Adds a new language.
Update | Modifies the existing language.
Delete | Deletes language.

See Also

  • Languages


Add

CLanguage::Add

mixed
CLanguage::Add(
 array fields
)

The method Add adds a new language. Returns the ID of the added language. In case of an error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter | Description
fields | An array of the field values in the form of array("field"=>"value" [, ...]).

See Also

  • CLanguage fields
  • CLanguage::Update
  • CLanguage::Delete

Example

<?
$arFields = Array(
  "LID"              => "en",
  "ACTIVE"           => "Y",
  "SORT"             => 100,
  "DEF"              => "N",
  "NAME"             => "English",
  "FORMAT_DATE"      => "MM/DD/YYYY",
  "FORMAT_DATETIME"  => "MM/DD/YYYY HH:MI:SS",
  "CHARSET"          => "iso-8859-1"
  );
$obLang = new CLanguage;
$obLang->Add($arFields);
if (strlen($obLang->LAST_ERROR)>0) $strError .= $obLang->LAST_ERROR;
?>


Delete

CLanguage::Delete

CDBResult
CLanguage::Delete(
 string id
)

The method Delete deletes language. Returns the CDBResult class instance.

Parameters

Parameter | Description
id | Double-character language ID.

See Also

  • CLanguage::Add
  • CLanguage::Update
  • OnBeforeLanguageDelete event
  • OnLanguageDelete event

Example

<?
if (CLanguage::Delete("en"))
  echo "The language has been deleted successfully.";
?>


GetByID

CLanguage::GetByID

CDBResult
CLanguage::GetByID(
 string id
)

The method GetByID returns language by its ID as an instance of CDBResult class.

Parameters

Parameter | Description
id | Double-character language ID.

See Also

  • CLanguage fields
  • CLanguage::GetList
  • CLanguage::SelectBox

Example

<?
$rsLang = CLanguage::GetByID("en");
$arLang = $rsLang->Fetch();
echo "<pre>"; print_r($arLang); echo "</pre>";
?>


GetList

CLanguage::GetList

CDBResult
CLanguage::GetList(
 string &by = "sort",
 string &order = "asc",
 array filter = array()
)

The method GetList returns the list of languages as the CDBResult instance.

Parameters

Parameter Description
by Name of the field by which the list is to be sorted. The following values are possible:
  • lid - by language ID;
  • active - by the active state flag;
  • name - by name;
  • def - by the default language flag.
îrder Sort order. The following values are possible:
  • asc - ascending;
  • desc - descending.
filter An array of the format Array("filtered field"=>"value" [, ...]). Filtered field can have the following values:
  • LID - double-character language ID;
  • NAME - name of the language;
  • ACTIVE - active state flag (Y|N).

See Also

  • CLanguage fields
  • CLanguage::GetByID

Example

<?
$rsLang = CLanguage::GetList($by="sort", $order="desc", Array("NAME" => "russian"));
while ($arLang = $rsLang->Fetch())
{
  echo "<pre>"; print_r($arLang); echo "</pre>";
}
?>


SelectBox

CLanguage::SelectBox

string
CLanguage::SelectBox(
 string name,
 string value,
 string default_value = "",
 string js_function = "",
 string add_to_select = "class=typeselect"
)

The method SelectBox returns the HTML code containing the drop-down list of languages (the select tag).

Parameters

Parameter | Description
name | Name of the drop-down list: <select name="name" ...>
value | Current value (to initialize the selected option).
default_value | If specified, it will be rendered as the first item in the list (for example: select language). Optional. Empty by default.
js_function | Name of JS function which is to be called upon selecting an item in the drop-down list: <select OnChange="js_function" ...> Optional. Empty by default.
add_to_select | An arbitrary HTML code which is to be added to the select tag: <select add_to_select ...> Optional. The standard CSS class is used for the drop-down lists of administrative section by default.

Example

<table>
  <tr>
    <td>Language:</td>
    <td><?=CLanguage::SelectBox("LANGUAGE", LANGUAGE_ID)?></td>
  </tr>
</table>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CLanguage::Update

bool
CLanguage::Update(
 int id,
 array fields
)

The method Update modifies language settings. In case of an error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter | Description
id | Double-character language ID.
fields | An array of the field values in the format array("field"=>"value" [, ...]).

See Also

  • CLanguage fields
  • CLanguage::Add
  • CLanguage::Delete

Example

<?
$arFields = Array(
  "ACTIVE"           => "Y",
  "SORT"             => 100,
  "DEF"              => "N",
  "NAME"             => "English",
  "FORMAT_DATE"      => "MM/DD/YYYY",
  "FORMAT_DATETIME"  => "MM/DD/YYYY HH:MI:SS",
  "CHARSET"          => "iso-8859-1"
  );
$obLang = new CLanguage;
$obLang->Update("en", $arFields);
if (strlen($obLang->LAST_ERROR)>0) $strError .= $obLang->LAST_ERROR;
?>


CMain

The CMain class represents a page.

Every time a new page is created, system creates an instance of this class. You can access the CMain object via the $APPLICATION variable.

Methods

Page title

Method | Description
ShowTitle | Displays the page title.
GetTitle | Returns the page title.
SetTitle | Sets the page title.

CSS

Method | Description
ShowCSS | Emits the CSS of a page.
GetCSS | Retrieves the CSS of the page.
SetTemplateCSS | Assigns the CSS to the component.
SetAdditionalCSS | Sets the CSS for the page.

Navigation chain

Method | Description
ShowNavChain | Emits the navigation chain
GetNavChain | Returns the HTML code of the navigation chain
AddChainItem | Adds an item to the end of the navigation chain

Menu

Method | Description
GetMenu | Returns an instance of the CMenu class.
GetMenuHtml | Returns the HTML code which displays the menu of the specified type.
GetMenuHtmlEx | Similar to GetMenuHtml but applies different menu template.

Page and section properties

Method | Description
ShowProperty | Displays page properties, with respect to the section properties.
GetProperty | Returns the property value of the current page or section.
GetPageProperty | Returns the value of a property of the current page.
GetDirProperty | Returns the specified property of the current section.
GetPagePropertyList | Returns an array of all page properties
GetDirPropertyList | Returns an array of the section properties, collected recursively up to the site root.
SetPageProperty | Sets the value of the specified property of the current page.
SetDirProperty | Sets the value of the property for the current section.
ShowMeta | Emits the page property as the META tag.
GetMeta | Retrieves the page property decorated in the <meta> tag.

Files

Method | Description
SaveFileContent | Saves the page to disk.
GetFileContent | Retrieves the file contents.
GetFileRecursive | Searches for a file recursively up the folder hierarchy.
GetFileAccessPermission | Retrieves the access permission of a file or folder
SetFileAccessPermission | Sets the access permissions for a file or folder
CopyFileAccessPermission | Opies the access permissions of one file or folder to another file or folder.
RemoveFileAccessPermission | Deletes the access permissions of a file or folder

Module access permissions and roles

Method | Description
GetUserRight | Returns the access permission assigned to a number of groups.
GetUserRoles | Returns array of roles (in the form of a string) assigned to a number of groups.

Current address of page

Method | Description
GetCurUri | Used to obtain the path and name of the current page relative to the site root
GetCurPage | Used to obtain the path and name of the current page relative to the site root, without parameters.
GetCurPageParam | Returns the path and name of the current page relative to the site root and optionally modifies (adds or removes) the URL parameters.
GetCurDir | Returns the folder of the current page relative to the site root
SetCurPage | Used to set the current page and its parameters in the instance of the CMain class.

Control toolbar

Method | Description
ShowPanel | Displays the control toolbar in the public section of the site.
GetPanel | Returns the HTML code of the public section control toolbar.
AddPanelButton | Adds a button to the control toolbar

Cookies

Method | Description
set_cookie | Sets the cookie.
get_cookie | Returns the value of a cookie.
ShowSpreadCookieHTML | Emits the HTML code indended for spreading cookies among domains.

Components

Method | Description
IncludeFile | Includes any files within the page body, prologue or epilogue
GetTemplatePath | Creates the path to the component relative to the site root from the specified path to component.

Other methods

Method | Description
IncludeAdminFile | Includes the specified file with the administrative prologue and epilogue attached.
IncludeString | Takes a string and returns the HTML code of the specified text bordered in the frame.
GetShowIncludeAreas | Urns true if the button Show include areas is checked.
AddBufferContent | Used to create delay functions
ShowBanner | Includes the Advertising module and displays a banner of the specified type.
GetSiteByDir | Returns an array describing the site defined by the specified path and domain.
AuthForm | Displays the authorization form, or includes other components depending on the parameters passed.
IsHTTPS | Determines if the current protocol is secured (HTTPS).


AddBufferContent

CMain::AddBufferContent

CMain::AddBufferContent(
 callback function,
 mixed parameter_1,
 mixed parameter_2,
 ...
 mixed parameter_N
)

The method AddBufferContent is used to create delay functions.

Parameters

Parameter | Description
function | Name of the function that is to be delayed. For global functions, pass the function name in this parameter. For class methods, pass an array having a class name in the first entry and a method name in the second one.
parameter_1 ... parameter_N | Parameters which are to be passed to the function.

See Also

  • Delay functions
  • CMain::ShowTitle
  • CMain::ShowCSS
  • CMain::ShowNavChain
  • CMain::ShowProperty
  • CMain::ShowMeta
  • CMain::ShowPanel

Example

<?
function myShowProperty($property_id, $default_value=false)
{
    global $APPLICATION;
    echo $APPLICATION->AddBufferContent(Array(&$APPLICATION, "GetProperty"),
    $property_id, $default_value);
}
?>
<?
function myShowTitle($property_name="title", $strip_tags = true)
{
    global $APPLICATION;
    echo $APPLICATION->AddBufferContent(Array(&$APPLICATION, "GetTitle"),
    $property_name, $strip_tags);
}
?>
<?
function myShowPanel()
{
    global $APPLICATION;
    echo $APPLICATION->AddBufferContent(Array(&$APPLICATION, "GetPanel"));
}
?>


AddChainItem

CMain::AddChainItem

CMain::AddChainItem(
 string title,
 string url = "",
 bool convert_html_entity = true
)

The method AddChainItem adds an item to the end of the navigation chain.

Parameters

Parameter | Description
title | Text of a new item in the navigation chain.
url | URL to assign to the new item of the navigation chain.
convert_html_entity If set to true, the title string will have the following replacements made:
  • &amp; with &
  • &quot; with "
  • &#039; with '
  • &lt; with <
  • &gt; with >
If false, no replacements are made. Optional; true by default.

See Also

  • Navigation chain
  • CMain::ShowNavChain
  • CMain::GetNavChain

Example

<?
$APPLICATION->AddChainItem("Forum &quot;Comments&quot;", "/en/forum/list.php?FID=3");
?>


AddPanelButton

CMain::AddPanelButton

CMain::AddPanelButton(
 array button
)

The method AddPanelButton adds a button to the control toolbar.

Parameters

Parameter Description
button Array describing a button. The array has the following keys:
  • HREF - hyperlink assigned to a button;
  • SRC - path to an image file from the site root;
  • ALT - tooltip text to be assigned to a button;
  • MAIN_SORT - sort index for a single group of buttons. The standard groups have the following indices:
    • 100 - Site Explorer buttons;
    • 200 - Workflow buttons;
    • 300 - Information Blocks buttons.
  • SORT - button sort index within a group.
If you want to display a button even if a user has not enough permissions for an operation, leave the HREF field empty. The button will be displayed desaturated without a link assigned.

See Also

  • Control toolbar
  • CMain::ShowPanel
  • The OnPanelCreate event

Example

<?
// obtain the current access permissions to the Web Forms module
$FORM_RIGHT = $APPLICATION->GetUserRight("form");
// if we can access -
if($FORM_RIGHT>"D"):
    // add a button that opens a list of web forms
    $APPLICATION->AddPanelButton(array(
        "HREF"      => "/bitrix/admin/form_list.php",
        "SRC"       => "/bitrix/images/fileman/panel/web_form.gif",
        "ALT"       => "Edit web form",
        "MAIN_SORT" => 400,
        "SORT"      => 100
    ));
endif;
?>


AuthForm

CMain::AuthForm

CMain::AuthForm(
 mixed message,
 bool show_header = true,
 bool show_footer = true,
 string not_show_links = "N"
)

The method AuthForm includes components depending on the parameters passed in the URL.
Parameter | Value | Component | Path to component
forgot_password | yes | Lost password retrieval | main/auth/forgot_password.php
change_password | yes | Lost password change | main/auth/change_password.php
register | yes | Registration form | main/auth/registration.php
authorize_registration | yes | Authorization and registration form | main/auth/authorize_registration.php

If neither of the parameters are specified, the method includes the Authorization form component (main/auth/authorize.php).

Note
The method stops the execution of the current page after the inclusion of the required component.

Parameters

Parameter | Description
message | String containing the error message, or array in the format Array("MESSAGE" => message, "TYPE" => "ERROR"|"OK") (processed in the ShowMessage function)
show_header | If true, the method emits the prologue code (top part of a page). If set to false, the prolog is not emitted.
show_footer | If true, the method emits the epilogue code (bottom part of a page). If set to false, the prolog is not emitted.
not_show_links | This parameter is passed to the component Authorization form (main/auth/authorize.php). If set to Y, the links to register, retrieve or change the forgotten password are not displayed. If set to N, the links are displayed (the default behaviour).

See Also

  • Components
  • Access permissions
  • ShowMessage

Example

<?
// get read access permission for the file
// "/download/document.doc" for the current user
$FILE_PERM = $APPLICATION->GetFileAccessPermission("/download/document.doc");
$FILE_PERM = (strlen($FILE_PERM)>0 ? $FILE_PERM : "D");
// display the auth. form is read access is denied
if($FILE_PERM<"R") $APPLICATION->AuthForm("Cannot access this file.");
?>


CopyFileAccessPermission

CMain::CopyFileAccessPermission

bool
CMain::CopyFileAccessPermission(
 string path_from,
 string path_to,
 bool overwrite = false
)

The method CopyFileAccessPermission copies the access permissions of one file or folder to another file or folder.

Parameters

Parameter Description
path_from Source object to copy the permissions from. In case of multiple sites, if the DOCUMENT_ROOT (specified in the field Path to the web server root folder in the site settings, System settings -> Sites -> the site) of the source and target sites are different, pass an array in the following format:
array("Site ID", "Source path")
path_to Target object to assign the permissions to. In case of multiple sites, if the DOCUMENT_ROOT (specified in the field Path to the web server root folder in the site settings, System settings -> Sites -> the site) of the source and target sites are different, pass an array in the following format:
array("Site ID", "Target path")
overwrite If true, the method does not preserve the existing permissions of the target object.
Optional; false by default.

Return Values

Returns true on success or false otherwise.

See Also

  • Access permissions
  • CMain::GetFileAccessPermission
  • CMain::SetFileAccessPermission
  • CMain::RemoveFileAccessPermission

Example

<?
// set the following permissions to the file /en/index.php:
// the group #23: read only
// the group #5: write access
// deny access for all other groups
if ($APPLICATION->SetFileAccessPermission("/en/index.php", array("23" => "R", "5" => "W", "*" => "D")))
{
    ShowNote("Access permissions successfully assigned.");

    // copy the permissions of the file "/en/index.php" to the file "/de/index.php"
    if ($APPLICATION->CopyFileAccessPermission("/en/index.php", "/de/index.php", true))
         ShowNote("Access permissions successfully copied.");
}
?>


get

CMain::get

CMain::get_cookie(
 string name,
 mixed name_prefix = false
)

The method get returns the value of a cookie.

Parameters

Parameter | Description
name | Name of the cookie.
name_prefix Prefix used with the cookie name.
Optional. By default, this parameters is set to the value of the parameter Cookie name prefix in the setting of the Kernel module. You can obtain the value by making the call:
COption::GetOptionString("main", "cookie_name", "BITRIX_SM")

See Also

  • Transferring visitors
  • CMain::set_cookie
  • CMain::ShowSpreadCookieHTML

Example

<?
global $APPLICATION;
$VISITOR_ID = $APPLICATION->get_cookie("VISITOR_ID");
?>


GetCSS

CMain::GetCSS

string
CMain::GetCSS(
 bool external = true
)

The method GetCSS retrieves the CSS of the page. The CSS can be assigned by calling CMain::SetAdditionalCSS or CMain::SetTemplateCSS. In addition to the user-assigned CSS, the method always returns styles of the current site template defined in the file /bitrix/templates/template ID/styles.css.

Parameters

Parameter Description
external If true, the method emits the HTML code of the link to an external CSS. For example:
<LINK
 href="/bitrix/templates/demo/styles.css"
 type="text/css"
 rel="stylesheet">
If false, the inline CSS is generated. For example:
<style type="text/css">
body
{
    margin: 0px;
    padding:0px;
    background-color: #FFFFFF
}
...
</style>
The CSS stored in the folder /bitrix/modules/ are always included as the inline CSS (generally used in the standard components).

See Also

  • CMain::ShowCSS
  • CMain::SetTemplateCSS
  • CMain::SetAdditionalCSS


GetCurDir

CMain::GetCurDir

string
CMain::GetCurDir()

The method GetCurDir returns the folder of the current page relative to the site root.

Parameters

No parameters.

See Also

  • CMain::GetCurUri
  • CMain::GetCurPage
  • CMain::GetCurPageParam
  • CMain::SetCurPage
  • GetDirPath
  • GetPagePath

Example

<?
// current page: /en/support/index.php?id=3&s=5
global $APPLICATION;
$dir = $APPLICATION->GetCurDir();
// $dir contains "/en/support/"
?>


GetCurPage

CMain::GetCurPage

string
CMain::GetCurPage()

The method GetCurPage is used to obtain the path and name of the current page relative to the site root, without parameters.

Note
If the file of the current page is not defined explicitly, the index page of a folder is determined using the algorithm of the function GetDirIndex.

Parameters

No parameters.

See Also

  • CMain::GetCurUri
  • CMain::GetCurDir
  • CMain::GetCurPageParam
  • CMain::SetCurPage
  • GetPagePath
  • GetDirPath

Example

<?
// current page: /en/?id=3&s=5
$page = $APPLICATION->GetCurPage(); // returns /en/index.php
?>


GetCurPageParam

CMain::GetCurPageParam

string
CMain::GetCurPageParam(
  string add_params = "",
  array remove_params = array()
)

The method GetCurPageParam returns the path and name of the current page relative to the site root and optionally modifies (adds or removes) the URL parameters.

Note
If the file of the current page is not defined explicitly, the index page of a folder is determined using the algorithm of the function GetDirIndex.

Parameters

Parameter | Description
add_params | String containing parameters to be added to the returned string. Optional. The default value is an empty string.
remove_params | Array with parameters to be removed from the returned string. Optional. The default value is an empty array.

See Also

  • DeleteParam
  • CMain::GetCurPage
  • CMain::GetCurUri
  • CMain::GetCurDir
  • GetPagePath
  • GetDirPath

Example

<?
// current page: /en/?id=3&s=5&d=34
$page = $APPLICATION->GetCurPageParam("id=45", array("id", "d"));
// result: /en/index.php?id=45&s=5
?>
// sample links "Logout" and "Register"

<?if ($USER->IsAuthorized()):?>

 <a href="<?echo $APPLICATION->GetCurPageParam("logout=yes", array(
     "login",
     "logout",
     "register",
     "forgot_password",
     "change_password"));?>">Logout</a>

<?else:?>

 <a href="<?echo $APPLICATION->GetCurPageParam("register=yes", array(
     "login",
     "logout",
     "forgot_password",
     "change_password"));?>">Register</a>

<?endif;?>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetCurUri

CMain::GetCurUri

string
CMain::GetCurUri(
 string add_params = ""
)

The method GetCurUri is used to obtain the path and name of the current page relative to the site root, with the parameters passed on URL.

Note
If the file of the current page is not defined explicitly, the index page of a folder is determined using the algorithm of the function GetDirIndex.

Parameters

Parameter | Description
add_params | String containing parameters to be added to the returned string. Optional. The default value is an empty string.

See Also

  • CMain::GetCurPage
  • CMain::GetCurDir
  • CMain::GetCurPageParam
  • CMain::SetCurPage
  • GetPagePath
  • GetDirPath

Example

<?
// current page: /en/?id=3&s=5
$uri = $APPLICATION->GetCurUri("r=1&t=2"); // result: /en/index.php?id=3&s=5&r=1&t=2
?>


GetDirProperty

CMain::GetDirProperty

string
CMain::GetDirProperty(
 string property_id,
 mixed path = false,
 mixed default_value = false
)

The method GetDirProperty returns the specified property of the current section (folder).

Parameters

Parameter | Description
property_id | The property ID whose value is to be returned.
path Path to the folder. In case of multiple sites, if the DOCUMENT_ROOT (specified in the field Path to the web server root folder in the site settings, System settings -> Sites -> the site) of the site of interest is different, pass an array in the following format:
array("Site ID", "Path")
Optional. False by default, which means the current folder.
default_value Default value of the property.
Optional. False by default, which means that the property has no default value.

See Also

  • Page properties and meta tags
  • CMain::ShowProperty
  • CMain::GetProperty
  • CMain::GetPageProperty
  • CMain::GetPagePropertyList
  • CMain::GetDirPropertyList
  • CMain::SetPageProperty
  • CMain::SetDirProperty

Example

<?
$APPLICATION->GetDirProperty("keywords");
?>


GetDirPropertyList

CMain::GetDirPropertyList

array
CMain::GetDirPropertyList(
 string path = false
)

The method GetDirPropertyList returns an array of the section properties, collected recursively up to the site root.

Parameters

Parameter Description
path Path to the folder. In case of multiple sites, if the DOCUMENT_ROOT (specified in the field Path to the web server root folder in the site settings, System settings -> Sites -> the site) of the site of interest is different, pass an array in the following format:
array("Site ID", "Path")
Optional. False by default, which means the current folder.

Return Values

Array of the section properties.

See Also

  • Page properties and meta tags
  • CMain::ShowProperty
  • CMain::GetProperty
  • CMain::GetPageProperty
  • CMain::GetDirProperty
  • CMain::GetPagePropertyList
  • CMain::SetPageProperty
  • CMain::SetDirProperty

Example

<?
$props = $APPLICATION->GetDirPropertyList();
foreach($props as $key=>$val)
    echo '<meta name="'.$key.'" content="'.htmlspecialchars($val).'">';
?>


GetException

CMain::GetException

CApplicationException
CMain::GetException();

The method GetException returns an instance of the CApplicationException class containing the last exception.

Parameters

No parameters.

Return Values

Instance of the CApplicationException class.

See Also

  • CApplicationException
  • CMain::ThrowException

Example

<?
if(!$langs->Delete($del_id))
{
   if($ex = $APPLICATION->GetException())
      $strError = $ex->GetString();
}
?>


GetFileAccessPermission

CMain::GetFileAccessPermission

string
CMain::GetFileAccessPermission(
 mixed path,
 array groups
)

The method GetFileAccessPermission retrieves the access permission of a file or folder.

Parameters

Parameter Description
path Path to the file or folder relative to the site root. In case of multiple sites, if the DOCUMENT_ROOT of the site of interest is different, pass an array in the following format:
array("Site ID", "Path to the file or folder")
groups Array of the user groups ID's for which the access permissions are to be retrieved. If false, permissions for the current user are returned.
Optional; false by default.

Return Values

Returns a symbol which defines the permission:

  • D - access denied;
  • R - read access (view the file contents);
  • U - workflow (edit file in the workflow mode);
  • W - write (direct modification is allowed);
  • X - full access (both direct file modification and editing the access permission are allowed).

See Also

  • Access permissions
  • CMain::SetFileAccessPermission
  • CMain::CopyFileAccessPermission
  • CMain::RemoveFileAccessPermission

Example

<?
if ($APPLICATION->GetFileAccessPermission("/en/index.php")<="D")
   ShowError("Access to file denied.");
?>


GetFileContent

CMain::GetFileContent

mixed
CMain::GetFileContent(
 string abs_path
)

The method GetFileContent retrieves the file contents.

Parameters

Parameter | Description
abs_path | Absolute path to the file.

Return Values

String containing the file contents. The method returns false if the file cannot be found.

See Also

  • CMain::SaveFileContent

Example

<?
$APPLICATION->GetFileContent($_SERVER["DOCUMENT_ROOT"]."/en/index.php");
?>


GetFileRecursive

CMain::GetFileRecursive

mixed
CMain::GetFileRecursive(
 string file,
 mixed dir
)

The method GetFileRecursive searches for a file recursively up the folder hierarchy.

Parameters

Parameter | Description
file | Name of the file.
dir | Path to the folder from which the search is to be performed. If set to false, the search will start from the current folder. Optional, false by default.

Return Values

Returns the path to the found file relative to the site root, or false otherwise.

Example

<?
// search for the file params.php up the folder hierarchy
// starting from the current folder.
// if the file can be found, include it
include($_SERVER["DOCUMENT_ROOT"].$APPLICATION->GetFileRecursive("params.php"));
?>


GetMenu

CMain::GetMenu

CMenu
CMain::GetMenu(
 string type = "left",
 bool use_ext = false,
 mixed template_path = false,
 mixed init_dir = false
)

The method GetMenu returns an instance of the CMenu class. The object returned is initialised by calling the method CMenu::Init. In case of an error, the LAST_ERROR property of the calling object contains the error description.

Parameters

Parameter | Description
type | Type of the menu. Optional; left by default.
use_ext | If true, the menu is built using files .menu type.menu_ext.php in addition to the standard files .menu type.menu.php. The _ext files allows you to modify the menu array $aMenuLinks as desired, for example: add menu items. Optional; false by default.
template_path | Path relative to the site root to the menu template. Optional; false by default, which specifies to search for the template using the algorithm described in the "Menu" section.
init_dir | Folder for which the menu is to be built. Optional; false by default, which means the current folder.

See Also

  • Menu
  • CMenu
  • CMenu::Init
  • CMain::GetMenuHtml
  • CMain::GetMenuHtmlEx

Example

<?
// display menu of the type "left"
// use files .menu type.menu_ext.php
// explicitly specify the template and
// the folder to build the menu for

$obMenu = $APPLICATION->GetMenu(
    "left",
    true,
    "/bitrix/php_interface/".SITE_ID."/left.menu_template.php",
    SITE_DIR
    );

// display the menu
echo $obMenu->GetMenuHtml();
?>


GetMenuHtml

CMain::GetMenuHtml

string
CMain::GetMenuHtml(
 string type = "left",
 bool use_ext = false,
 mixed template_path = false,
 mixed init_dir = false
)

The method GetMenuHtml returns the HTML code which displays the menu of the specified type. Unlike the method CMain::GetMenuHtmlEx, the menu template is applied to every item of the menu.

Parameters

Parameter | Description
type | Type of the menu. Optional; left by default.
use_ext | If true, the menu is built using files .menu type.menu_ext.php in addition to the standard files .menu type.menu.php. The _ext files allows you to modify the menu array $aMenuLinks as desired, for example add menu items. Optional; false by default.
template_path | Path relative to the site root to the menu template. Optional; false by default, which specifies to search for the template using the algorithm described in the "Menu" section.
init_dir | Folder for which the menu is to be built. Optional; false by default, which means the current folder.

See Also

  • Menu
  • CMenu
  • CMenu::Init
  • CMain::GetMenu
  • CMain::GetMenuHtmlEx

Examples

The following is an example of the left menu with items collected from the information block.

Displaying the menu in the file /bitrix/templates/demo/header.php:

<?
echo $APPLICATION->GetMenuHtml("left", true);
?>

File /.left.menu.php:

<?
// main menu
// this file can be edited in the menu editor
$aMenuLinks = Array(
);
?>

File /.left.menu_ext.php:

<?
// additional menu
// adds sections of the phone catalogue to the main menu array
if (CModule::IncludeModule("iblock")):

    $IBLOCK_TYPE = "catalog";   // information block type
    $IBLOCK_ID = 21;            // information block ID
    $CACHE_TIME = 3600;         // cache for 1 hour

    $aMenuLinksNew = array();

    // create an object to cache the menu
    $CACHE_ID = __FILE__.$IBLOCK_ID;
    $obMenuCache = new CPHPCache;
    // if the array is cached...
    if($obMenuCache->InitCache($CACHE_TIME, $CACHE_ID, "/"))
    {
        // take data from the cache
        $arVars = $obMenuCache->GetVars();
        $aMenuLinksNew = $arVars["aMenuLinksNew"];
    }
    else
    {
        // otherwise, build it
        $rsSections = GetIBlockSectionList($IBLOCK_ID,
                                           false,
                                           array("SORT" => "ASC", "ID" => "ASC"),
                                           false,
                                           array("ACTIVE"=>"Y"));
        while ($arSection = $rsSections->Fetch())
        {
            $arrAddLinks =
                array(SITE_DIR."catalog/phone/element.php?SECTION_ID=".$arSection["ID"]);
            // iterate the section elements
            if ($rsElements =
                GetIBlockElementListEx($IBLOCK_TYPE,
                                       false, false, array(), false,
                                       array("ACTIVE" => "Y",
                                             "IBLOCK_ID" => $IBLOCK_ID,
                                             "SECTION_ID" => $arSection["ID"]),
                                       array("ID", "IBLOCK_ID", "DETAIL_PAGE_URL")))
            {
                while ($arElement = $rsElements->GetNext())
                       $arrAddLinks[] = $arElement["DETAIL_PAGE_URL"];
            }
            $aMenuLinksNew[] = array(
                $arSection["NAME"],
                SITE_DIR."catalog/phone/section.php?SECTION_ID=".$arSection["ID"],
                $arrAddLinks);
        }
    }
    // store data in the cache
    if($obMenuCache->StartDataCache())
    {
        $obMenuCache->EndDataCache(Array("aMenuLinksNew" => $aMenuLinksNew));
    }

    // merge the main and additional menu arrays
    $aMenuLinks = array_merge($aMenuLinksNew, $aMenuLinks);

endif;
?>

Menu template /bitrix/templates/demo/left.menu_template.php:

<?
// This file is the template for one menu item iteration

// Set item mark: selected folder, folder, page
if ($ITEM_TYPE=="D")
{
    if ($SELECTED)
        $strDir = "<td width='0%' bgcolor='#A0C4E0' valign='middle'
                       align='center'><img height='13'
                                           src='/bitrix/templates/demo/images/left_folder_open.gif'
                                           width='17' border='0'></td>";
    else
        $strDir = "<td width='0%' bgcolor='#CCDFEE' valign='middle'
                       align='center'><img height='13'
                                           src='/bitrix/templates/demo/images/left_folder.gif'
                                           width='17' border='0'></td>";
}
else
{
    if ($SELECTED)
    {
        $strDir = "<td width='0%' bgcolor='#A0C4E0' valign='middle'
                       align='center'><img height='13'
                                           src='/bitrix/templates/demo/images/left_bullet.gif'
                                           width='17' border='0'></td>";
        $strDir_d = "<td width='0%' bgcolor='#A0C4E0' valign='middle'
                         align='center'><img height='13'
                                             src='/bitrix/templates/demo/images/left_bullet_d.gif'
                                             width='17' border='0' alt='Private section'></td>";
    }
    else
    {
        $strDir = "<td width='0%' bgcolor='#CCDFEE' valign='middle'
                       align='center'><img height='13'
                                           src='/bitrix/templates/demo/images/left_bullet.gif'
                                           width='17' border='0'></td>";
        $strDir_d = "<td width='0%' bgcolor='#CCDFEE' valign='middle'
                         align='center'><img height='13'
                                             src='/bitrix/templates/demo/images/left_bullet_d.gif'
                                             width='17' border='0' alt='Private section'></td>";
    }
}

// if $SELECTED then this item is current (active) item
if ($SELECTED)
    $strtext = "leftmenuact";
else
    $strtext = "leftmenu";

// if $PARAMS["SEPARATOR"]=="Y" this item
// should be shown with different style applied

if ($PARAMS["SEPARATOR"]=="Y")
{
    $strstyle = " style='background-color: #D5ECE6; border-top: 1px solid #A6D0D7;
                  border-bottom: 1px solid #A6D0D7; padding:8;'";
    $strDir = "<img height='13' src='/bitrix/templates/demo/images/1.gif'
                    width='17' border='0'>";
    $strtext = "leftmenu";
}
else
    $strstyle = " style='padding:8;'";

// Content of variable $sMenuProlog is typed
// just before all menu items iterations
// Content of variable $sMenuEpilog is typed
// right after all menu items iterations
$sMenuProlog = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";
$sMenuEpilog = '<tr><td colspan=2
                        background="/bitrix/templates/demo/images/l_menu_border.gif"><img
                        src="/bitrix/templates/demo/images/1.gif"
                        width="1" height="1"></td></tr></table>';

// if $PERMISSION > "D" then current user can access this page
if ($PERMISSION > "D")
{
    $sMenuBody = '<tr><td colspan=2
                          background="/bitrix/templates/demo/images/l_menu_border.gif"><img
                          src="/bitrix/templates/demo/images/1.gif"
                          width="1" height="1"></td></tr><tr>'.$strDir.'<td
                          valign="top"'.$strstyle.' width="100%"><a
                          href="'.$LINK.'" class="'.$strtext.'">'.$TEXT.'</a></td></tr>';
}
else
{
    $sMenuBody = '<td colspan=2
                      background="/bitrix/templates/demo/images/l_menu_border.gif"><img
                      src="/bitrix/templates/demo/images/1.gif"
                      width="1" height="1"></td></tr><tr>'.$strDir_d.'</td><td
                      valign="top"'.$strstyle.' width="100%"><a
                      href="'.$LINK.'" class='.$strtext.'>'.$TEXT.'</a></td></tr>';

}
?>


GetMenuHtmlEx

CMain::GetMenuHtmlEx

string
CMain::GetMenuHtmlEx(
 string type = "left",
 bool use_ext = false,
 mixed template_path = false,
 mixed init_dir = false
)

The method GetMenuHtmlEx emits the HTML code which displays the menu of the specified type. Unlike the method CMain::GetMenuHtml, the menu template is applied only once.

Note
The menu template used by this method must have the variable $sMenu initialised. This variable must contain the HTML code describing the whole menu.

Parameters

Parameter | Description
type | Type of the menu. Optional; left by default.
use_ext | If true, the menu is built using files .menu type.menu_ext.php in addition to the standard files .menu type.menu.php. The _ext files allows you to modify the menu array $aMenuLinks as desired, for example add menu items. Optional; false by default.
template_path | Path relative to the site root to the menu template. Optional; false by default, which specifies to search for the template using the algorithm described in the "Menu" section.
init_dir | Folder for which the menu is to be built. Optional; false by default, which means the current folder.

See Also

  • Menu
  • CMenu
  • CMenu::Init
  • CMain::GetMenu
  • CMain::GetMenuHtml

Example

The following is an example of the drop-down top menu.

Displaying the menu in the file /bitrix/templates/demo/header.php:

<script language="JavaScript1.2" src="/bitrix/templates/demo/js/ddnmenu.js"></script>
<?echo $APPLICATION->GetMenuHtmlEx("top");?>

File /.top.menu.php:

<?
// main menu
// this file can be edited in the menu editor
$aMenuLinks = Array(
    Array(
        "Main",
        "/index.php",
        Array(),
        Array(),
        ""
    ),
    Array(
        "Catalog",
        "/catalog/",
        Array(),
        Array(),
        ""
    ),
    Array(
        "Support",
        "/support/",
        Array(),
        Array(),
        ""
    ),
    Array(
        "Partners",
        "/partners/",
        Array(),
        Array(),
        ""
    ),
    Array(
        "Company",
        "/about/",
        Array(),
        Array(),
        ""
    )
);
?>

File /bitrix/templates/demo/top.menu_template.php:

<?
// menu template
$sMenu = '<table width="100%" border="0"
                 cellspacing="0" cellpadding="0"><tr><td width="0%"><img
                 src="/bitrix/templates/demo/images/top_menu_corner.gif"
                 alt="" width="15" height="19"></td>';

for($i=0; $i<count($arMENU); $i++)
{
    $MENU_ITEM = $arMENU[$i];
    extract($MENU_ITEM);

    if($SELECTED)
        $clrtext = 'topmenuact';
    else
        $clrtext = 'topmenu';

    $sMenu .= '<td>';
    $sMenu .= '<table border="0" cellspacing="0" cellpadding="0"><tr>';
    $sMenu .= '<td bgcolor="#7B9DBB" onmouseover="show('.$i.')"
                   onmouseout="hidden('.$i.')"><a href="'.$LINK.'"
                   class="'.$clrtext.'"><nobr> '.$TEXT.' </nobr></a></td>';
    $sMenu .= '<td width="0%" bgcolor="#7B9DBB">';

    if($i<count($arMENU)-1) // add vertical divider after all items
                            // but not after the last one
        $sMenu .= '<img src="/bitrix/templates/demo/images/top_menu_divider.gif"
                        width="15" height="19" alt="">';
    else
        $sMenu .= '<img src="/bitrix/templates/demo/images/1.gif"
                        width="1" height="19" alt="">';

    $sMenu .= '</td></tr></table>';

    // check if menu of left type exists in the folder
    // that the menu item points to
    $popup_menu = new CMenu("left");
    $popup_menu->Init($LINK);
    if(count($popup_menu->arMenu) > 0)
    {
        // if left menu exists then we display it in the hidden layer
        $popup_menu->template = "/bitrix/templates/demo/popup.menu_template.php";
        $sMenu .= '<div style="position:relative; width: 100%;">';
        $sMenu .= '<div onMouseOver="show('.$i.')" onMouseOut="hidden('.$i.')"
                        id="menu'.$i.'"
                        style="visibility: hidden; position: absolute;
                               z-index: +1; top: 0px;" >';
        $sMenu .= $popup_menu->GetMenuHtmlEx();
        $sMenu .= '</div></div>';
    }
    $sMenu .= '</td>';
}
$sMenu .= '<td width="100%" bgcolor="#7B9DBB"><img
               src="/bitrix/templates/demo/images/1.gif"
               width="50" height="1" alt=""></td></tr></table>';
?>

File /bitrix/templates/demo/popup.menu_template.php:

<?
$sMenu =
    '<table border="0" cellspacing="0" cellpadding="0" width="110">'.
    '<tr><td bgcolor="#E6EFF7" valign="top"><table
             border="0" cellspacing="0" cellpadding="0" width="100%">';

for($i=0; $i<count($arMENU); $i++)
{
    $MENU_ITEM = $arMENU[$i];
    extract($MENU_ITEM);

    if ($PERMISSION > "D")
    {
        $sMenu .=
        '<tr valign="top"><td nowrap onmouseover="this.className=\'popupmenuact\'"
             onmouseout="this.className=\'popupmenu\'"
             onclick="window.location=\''.$LINK.'\'"
             class="popupmenu" style="cursor: hand">'.
        '<nobr><a href="'.$LINK.'"
                  style="text-decoration: none;"><font
                  class="popupmenutext">'.$TEXT.'</font></a>'.
        '</nobr></td></tr>';
    }
    else
    {
        $sMenu .=
        '<tr valign="top"><td nowrap onmouseover="this.className=\'popupmenuact\'"
             onmouseout="this.className=\'popupmenu\'"
             onclick="window.location=\''.$LINK.'\'"
             class="popupmenu" style="cursor: hand">'.
        '<nobr><font class="popupmenuclosed">'.$TEXT.'</font>'.
        '</nobr></td></tr>';
    }
}
$sMenu .= '</table></td></tr></table>';
?>

File /bitrix/templates/demo/js/ddnmenu.js:

var brname=navigator.appName, BrVer='';
if(brname.substring(0,2)=="Mi")
    BrVer='E';
var timer = 0;
lastid = -1;

function show(id)
{
    if (!((document.all) ?
           document.all['menu'+id] :
           document.getElementById('menu'+id)))
    {
        return;
    }

    clearTimeout(timer);
    if ((id != lastid) && (lastid!=-1))
        ((document.all) ?
          document.all['menu'+lastid] :
          document.getElementById('menu'+lastid)).style.visibility = 'hidden';
    hideElement("SELECT", document.getElementById('menu'+lastid));
    lastid = id;
    ((document.all) ?
      document.all['menu'+lastid] :
      document.getElementById('menu'+lastid)).style.visibility = 'visible';
}

function hidden(id)
{
    if (!((document.all) ?
          document.all['menu'+id] :
          document.getElementById('menu'+id)))
        return;
    showElement("SELECT");
    timer = setTimeout("if('"+id+"' == '"+lastid+"'){((document.all)?document.all['menu"+lastid+"']:document.getElementById('menu"+lastid+"')).style.visibility = 'hidden';}",
                       500)
}

function GetPos(el)
{
    if (!el || !el.offsetParent)return false;
    var res=Array()
    res["left"] = el.offsetLeft;
    res["top"] = el.offsetTop;
    var objParent = el.offsetParent;
    while (objParent.tagName.toUpperCase()!="BODY")
    {
        res["left"] += objParent.offsetLeft;
        res["top"] += objParent.offsetTop;
        objParent = objParent.offsetParent;
    }
    res["right"]=res["left"]+el.offsetWidth;
    res["bottom"]=res["top"]+el.offsetHeight;
    return res;
}

function hideElement(elName, Menu)
{
    if(BrVer!='E') return;
    for (i = 0; i < document.all.tags(elName).length; i++)
    {
        Obj = document.all.tags(elName)[i];
        if(!(pMenu=GetPos(Menu)))continue;
        if(!(pObj=GetPos(Obj)))continue;

        if (pObj["left"]  < pMenu["right"] &&
            pMenu["left"] < pObj["right"] &&
            pObj["top"]   < pMenu["bottom"] &&
            pMenu["top"]  < pObj["bottom"])
            Obj.style.visibility = "hidden";
    }
}

function showElement(elName)
{
    if(BrVer!='E') return;
    for (i = 0; i < document.all.tags(elName).length; i++)
    {
        obj = document.all.tags(elName)[i];
        if (!obj || !obj.offsetParent)continue;
        if(obj.style.visibility=="hidden")
            obj.style.visibility = "visible";
    }
}


GetMeta

CMain::GetMeta

string
CMain::GetMeta(
 string property_id,
 string meta_name = false
)

The method GetMeta retrieves the page property decorated in the <meta> tag. If the page does not have the required property, the method searches for the one in parent sections recursively. If the method fails to find the required property, an empty string is returned.

Parameters

Parameter | Description
property_id | Identifier of the page or section property whose value will be rendered in the content attribute of the <meta> tag: <meta content="value" ...>
meta_name | Contents of the name attribute of the <meta> tag: <meta name="meta_name" ...> Optional; by default, the property_id name is used.

See Also

  • Page properties and meta tags
  • CMain::ShowMeta
  • CMain::SetPageProperty
  • CMain::SetDirProperty

Example

<?
$meta_keywords = $APPLICATION->GetMeta("keywords_prop", "keywords");
if (strlen($meta_keywords)>0) echo $meta_keywords;
?>


GetNavChain

CMain::GetNavChain

string
CMain::GetNavChain(
 mixed path = false,
 int start_from = 0,
 mixed template_path = false
)

The method GetNavChain returns the HTML code of the navigation chain.

If you do not want some page to display the navigation chain, simply initialise the page property NOT_SHOW_NAV_CHAIN with "Y":

$APPLICATION->SetPageProperty("NOT_SHOW_NAV_CHAIN", "Y");
The method GetNavChain supports this property and respects its value.

Parameters

Parameter Description
path Path for which the navigation chain is to be built. In case of multiple sites, if the DOCUMENT_ROOT of the site is different, pass an array in the following format:
array("Site ID", "Path")
Optional. False by default, which means the current site.
start_from Ordinal of item from which to build the chain.
Optional; zero by default.
template_path Path to the navigation chain template.
Optional. The default value is false, which implies searching for the navigation chain template using the algorithm described in the Navigation chain section.

See Also

  • Navigation chain
  • CMain::ShowNavChain
  • CMain::AddChainItem


GetPageProperty

CMain::GetPageProperty

string
CMain::GetPageProperty(
 string property_id,
 mixed default_value = false
)

The method GetPageProperty returns the value of a property of the current page .

Parameters

Parameter | Description
property_id | Property identifier.
default_value | Default value of the property. Optional; the default value is false which means no default value is assigned.

See Also

  • Page properties and meta tags
  • CMain::ShowProperty
  • CMain::GetProperty
  • CMain::GetDirProperty
  • CMain::GetPagePropertyList
  • CMain::GetDirPropertyList
  • CMain::SetPageProperty
  • CMain::SetDirProperty

Example

<?
$APPLICATION->GetPageProperty("keywords");
?>


GetPagePropertyList

CMain::GetPagePropertyList

array
CMain::GetPagePropertyList()

The method GetPagePropertyList returns an array of all page properties.

Parameters

No parameters.

See Also

  • Page properties and meta tags
  • CMain::ShowProperty
  • CMain::GetProperty
  • CMain::GetPageProperty
  • CMain::GetDirProperty
  • CMain::GetDirPropertyList
  • CMain::SetPageProperty
  • CMain::SetDirProperty

Example

<?
$props = $APPLICATION->GetPagePropertyList();
foreach($props as $key=>$val)
    echo '<meta name="'.$key.'" content="'.htmlspecialchars($val).'">';
?>


GetPanel

CMain::GetPanel

string CMain::GetPanel()

The method GetPanel returns the HTML code of the public section control toolbar.

Parameters

No parameters.

See Also

  • CMain::ShowPanel
  • CMain::AddPanelButton


GetProperty

CMain::GetProperty

string
CMain::GetProperty(
 string property_id,
 mixed default_value = false
)

The method GetProperty returns the property value of the current page or section. If the page does not have the required property, the method searches for the one in parent sections recursively.

Parameters

Parameter | Description
property_id | Identifier of the page or section property whose value is to be returned.
default_value | Default value of the property. Optional; the default value is false which means no default value is assigned.

See Also

  • Page properties and meta tags
  • CMain::ShowProperty
  • CMain::GetPageProperty
  • CMain::GetDirProperty
  • CMain::GetPagePropertyList
  • CMain::GetDirPropertyList
  • CMain::SetPageProperty
  • CMain::SetDirProperty

Example

<?
$keywords = $APPLICATION->GetProperty("keywords");
if (strlen($keywords)>0) echo $keywords;
?>


GetShowIncludeAreas

CMain::GetShowIncludeAreas

bool
CMain::GetShowIncludeAreas()

The method GetShowIncludeAreas returns true if the button Show include areas is checked on the control toolbar, or false otherwise.

Parameters

No parameters.

See Also

  • CMain::IncludeString

Example

<?
$text = "Some HTML";

// if Show include areas is on...
if ($APPLICATION->GetShowIncludeAreas())
{
    $arIcons = Array();
    $arIcons[] =
            Array(
                "URL" => "/bitrix/admin/my_script1.php",
                "SRC" => "/images/my_icon1.gif",
                "ALT" => "tooltip text"
            );
    $arIcons[] =
            Array(
                "URL" => "/bitrix/admin/my_script2.php",
                "SRC" => "/images/my_icon2.gif",
                "ALT" => "tooltip text"
            );

    // print text "Some HTML" in border,
    // with images my_icon1.gif and my_icon2.gif in the top right corner
    // with links to scripts my_script1.php and my_script2.php

    echo $APPLICATION->IncludeString($text, $arIcons);
}
else
{
    // otherwise, just print "Some HTML"
    echo $text;
}
?>
<?
// file /bitrix/modules/advertising/classes/general/advertising.php
// class CAdvBanner

// returns HTML code of a banner by type
function Show($TYPE_SID, $HTML_BEFORE="", $HTML_AFTER="")
{
    global $APPLICATION, $USER;
    $arBanner = CAdvBanner::GetRandom($TYPE_SID);
    $strReturn = CAdvBanner::GetHTML($arBanner);
    if (strlen($strReturn)>0)
    {
        CAdvBanner::FixShow($arBanner);
        if ($APPLICATION->GetShowIncludeAreas())
        {
            $isDemo = CAdvContract::IsDemo();
            $arrPERM = CAdvContract::GetUserPermissions($arBanner["CONTRACT_ID"]);
            if (($isDemo ||
                (is_array($arrPERM) &&
                count($arrPERM)>0)) &&
                $USER->IsAuthorized())
            {
                $arIcons = Array();
                $arIcons[] =
                        Array(
                            "URL" => "/bitrix/admin/adv_banner_edit.php?lang=".
                                     LANGUAGE_ID."&ID=".$arBanner["ID"].
                                     "&CONTRACT_ID=".$arBanner["CONTRACT_ID"],
                            "SRC" => "/bitrix/images/advertising/panel/edit_ad.gif",
                            "ALT" => GetMessage("AD_PUBLIC_ICON_EDIT_BANNER")
                        );
                $arIcons[] =
                        Array(
                            "URL" => "/bitrix/admin/adv_banner_list.php?lang=".
                                     LANGUAGE_ID."&find_id=".$arBanner["ID"].
                                     "&find_id_exact_match=Y&find_contract_id[]=".
                                     $arBanner["CONTRACT_ID"].
                                     "&find_type_sid[]=".
                                     $arBanner["TYPE_SID"]."&set_filter=Y",
                            "SRC" => "/bitrix/images/advertising/panel/edit_ad_list.gif",
                            "ALT" => GetMessage("AD_PUBLIC_ICON_BANNER_LIST")
                        );
                $strReturn = $APPLICATION->IncludeString($strReturn, $arIcons);
            }
        }
        $strReturn = $HTML_BEFORE.$strReturn.$HTML_AFTER;
        return $strReturn;
    }
    else return false;
}
?>


GetSiteByDir

CMain::GetSiteByDir

array
CMain::GetSiteByDir(
 mixed path = false,
 mixed host = false
)

The method GetSiteByDir returns an array describing the site defined by the specified path and domain. The method uses the following algorithm.

  1. Searches for site satisfying both path and host; return the found site on success; otherwise -
  2. Searches for site satisfying the path; return the found site on success; otherwise -
  3. Searches for site satisfying the host; return the found site on success; otherwise -
  4. Return the site for which the Default option is set..

Parameters

Parameter | Description
path | Path relative to the root . Optional; the default value is the path to the current page.
host | Domain name. Optional; the default value is the current domain.

Return Values

Array describing the site with keys described in the CSite fields section.

See Also

  • CSite fields
  • Sites

Example

<?
// obtain the referrer URL, or the last URL of the current session
if (strlen($_SERVER["HTTP_REFERER"])<=0)
    $referer_url = $_SESSION["SESS_HTTP_REFERER"];
else
    $referer_url = $_SERVER["HTTP_REFERER"];

// parse URL to get the domain and page
$arUrl = parse_url($referer_url);

// obtain the site descriptor array
$arSite = $APPLICATION->GetSiteByDir($arUrl["path"],
                                     $arUrl["host"]);
?>


GetTemplatePath

CMain::GetTemplatePath

string
CMain::GetTemplatePath(
 string component_path
)

The method GetTemplatePath creates the path to the component relative to the site root from the specified path to component.

Parameters

Parameter Description
component_path Path to the component.

The following algorithm is used to search for the path relative to the site root:
  1. Search for file of the component in
    /bitrix/templates/current site template ID/component_path
  2. If not found, search in
    /bitrix/templates/.default/component_path
  3. If still not found, search in
    /bitrix/modules/module ID/install/templates/component_path
where module ID is the first subdirectory in the folder component_path.

See Also

  • Components
  • CMain::IncludeFile

Example

<?
// obtain the real path to a component
$path = $APPLICATION->GetTemplatePath("iblock/catalog/element.php");
// $path may contain the following:
// "/bitrix/templates/.default/iblock/catalog/element.php"
?>


GetTitle

CMain::GetTitle

string
CMain::GetTitle(
 string property_name = "title",
 bool strip_tags = true
)

The method GetTitle returns the page title.

Parameters

Parameter | Description
property_name | Identifier of the page property whose value is to be printed as the title (effective if the property had been previously set by CMain::SetPageProperty). Optional; title by default.
strip_tags | If true, deletes all HTML tags from the title. Optional; true by default.

See Also

  • CMain::ShowTitle
  • CMain::SetTitle


GetUserRight

CMain::GetUserRight

string
CMain::GetUserRight(
 string module_id,
 mixed groups = false,
 string use_default = "Y",
 string max_for_admin = "Y"
)

The method GetUserRight returns the access permission assigned to a number of groups (group of a current user by default) for the specified module. The permission descriptor returned is meaningful for the specified module.

Generally, each module has specific access permission descriptors. At the same time, there are several common descriptors:

  • D - access to the module is denied;
  • R - permission to view pages of the module (read-only access);
  • W - data modification is allowed.
A unique set of permissions can be assigned to the module using the method GetModuleRightList of a class named by the module ID. For example, the Web Forms module exposes method form::GetModuleRightList() defined in the file /bitrix/modules/form/install/index.php. Permissions are usually assigned using the module settings form.

Some modules require that the permissions are assigned individually (e.g. Information blocks) and some does not have access permissions at all (e.g. Compression). The method GetModuleRightList is not applicable to such modules.

Note
For any module, maximum level of permission is always indicated with the symbol W (write), while the minimum permission - with D (deny).

Parameters

Parameter | Description
module_id | Module ID.
groups | Array of groups for which the maximum permission is to be determined. Setting this parameter to false assumes the array of groups of the current user. Optional; false by default.
use_default | If set to "Y", the default access permission level is taken into consideration to determine the maximum permission level Optional; "Y" by default.
max_for_admin | If set to "Y" and the parameter groups is false, the maximum permission W is always returned for users in the Administrators group (#1) regardless of the module settings. Optional; "Y" by default.

See Also

  • Access permissions
  • CMain::GetUserRoles
  • CModule::GetModuleRightList

Example

<?
// obtain the maximum access permission
// for the WebForms module for the current user
if($APPLICATION->GetUserRight("form")<="D")
    $APPLICATION->AuthForm("access denied.");
?>


GetUserRoles

CMain::GetUserRoles

string
CMain::GetUserRoles(
 string module_id,
 mixed groups = false,
 string use_default = "Y",
 string max_for_admin = "Y"
)

The method GetUserRight returns array of roles (in the form of a string) assigned to a number of groups (group of a current user by default) for the specified module. The role descriptor returned is meaningful for the specified module.

Generally, each module has specific role descriptors. A unique set of roles can be assigned to the module using the method GetModuleRightList of a class named by the module ID. For example, the Support module exposes method support::GetModuleRightList() defined in the file /bitrix/modules/support/install/index.php. Roles are usually assigned using the module settings form.

Note
For any module, role of the maximum level of permission (module administrator) is always indicated with the symbol W, while the role of the minimum level of permission - with D (deny).

Parameters

Parameter | Description
module_id | Module ID.
groups | Array of groups for which the roles are to be retrieved. Setting this parameter to false assumes the array of groups of the current user. Optional; false by default.
use_default | If set to "Y", the default role is taken into consideration to determine the required role. Optional; "Y" by default.
max_for_admin | If set to "Y" and the parameter groups is false, the role of the maximum permission level (W) is always included in the returned array of roles. Optional; "Y" by default.

See Also

  • Access permissions
  • CMain::GetUserRight
  • CModule::GetModuleRightList

Example

<?
// obtain the array of roles of the current user in the Support module
$arRoles = $APPLICATION->GetUserRoles("support");

if(in_array("R",$arRoles))
    $strNote = "You can post questions to the techsupport.";

if(in_array("T",$arRoles))
    $strNote = "You are the techsupport team member.";

if(in_array("V",$arRoles))
    $strNote = "You are allowed to view tickets but not modify them.";

if(in_array("W",$arRoles))
    $strNote = "You are the techsupport administrator.";

if ($arRoles==array("D"))
    $APPLICATION->AuthForm("Access denied.");

ShowNote($strNote);
?>


IncludeAdminFile

CMain::IncludeAdminFile

CMain::IncludeAdminFile(
 string title,
 string abs_path
)

The method IncludeAdminFile includes the specified file with the administrative prologue and epilogue attached.

Parameters

Parameter | Description
title | Page title.
abs_path | Absolute path to the included file.

See Also

  • Module description

Example

<?
function DoInstall()
{
    global $DB, $APPLICATION, $step;
    $FORM_RIGHT = $APPLICATION->GetGroupRight("form");
    if ($FORM_RIGHT=="W")
    {
        $step = IntVal($step);
        if($step<2)
            $APPLICATION->IncludeAdminFile(GetMessage("FORM_INSTALL_TITLE"),
            $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/install/step1.php");
        elseif($step==2)
            $APPLICATION->IncludeAdminFile(GetMessage("FORM_INSTALL_TITLE"),
            $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/install/step2.php");
    }
}
?>


IncludeFile

CMain::IncludeFile

CMain::IncludeFile(
 string path,
 array params = array(),
 array function_params = array()
)

The method IncludeFile is the main function you use to include any files within the page body, prologue or epilogue. It is the only method to use to include component. The visual aspect of the included file represents the include area.

The following buttons and icons relate to this method.
 | Show Include Areas button on the control toolbar. If checked, the include files become framed in colour border. The controls that may be displayed in the top right corner of the frame are described below.
Include area frame controls
 | Means that the included file is a standard component shipped with the module; the component will be copied to the folder /bitrix/templates/current site template ID/ before editing.
 | Means that the include file is stored in either /bitrix/templates/.default/ or /bitrix/templates/current site template ID/ (the file may be a component).
 | Means that the Workflow module is installed and the include file can be edited using the workflow facilities.

Parameters

Parameter Description
path Path to the included file.

If the parameter contains the path relative to the site root, the method includes this file unconditionally. If the file cannot be found and the button Show include areas is checked, the frame-placeholder contains the blue button linked to the page allowing to create a new file in the folder specified in the parameter path.

If the parameter specifies the path to the main file of the component, the method attempts to find and include the file using the following rules.
  1. In the folder
    /bitrix/templates/current site template ID/path
  2. If the file is not found, the method tries the folder
    /bitrix/templates/.default/path
  3. If the file is still not found, the method attempts to locate it in the module installation location:
    /bitrix/modules/module ID/install/templates/path,
    where module ID is the first folder of the path.
params Array of parameters to be passed to the include file. Array has the following format:
array(
 "parameter name 1" => "parameter value 1",
 "parameter name 2" => "parameter value 2",
 ...)
The include file initialises variables with names taken from the array keys; the variables values are the corresponding values of the array. This operation is performed using the standard PHP function extract(params).
function_params Array with the parameters for the method. The following keys allowed.
  • SHOW_BORDER - specifies to show or hide the design frame and buttons:
    • true - show frame if the button Show include areas is checked (default);
    • false - hide frame.
  • NAME - the Edit button tooltip text;
  • LANG - two-character identifier of the language that should be used to edit the file in the administrative section (current site language by default);
  • BACK_URL - page to which the user should be returned after the editing completes. By default, the current page in the public section.
  • WORKFLOW - specifies the include file is a part of the workflow:
    • true - the Edit link points to the Workflow module;
    • false - the Edit link points to the Site Explorer module (default).
  • MODE - editing mode:
    • text - edit file as text (link to edit the file in plain text mode);
    • html - edit file as HTML (link to edit the file in the HTML mode);
    • php - edit file as PHP (link to edit the source code of the file) (default).
  • TEMPLATE - if the path parameters specifies the absolute path to a missing file, this entry of the array should contain the name of the template file which is used to create a new file (by default, the method takes the first template according to their sort weight specified in the file /bitrix/templates/current site template ID/page_templates/.content.php)

See Also

  • Components
  • IncludeTemplateLangFile
  • CMain::IncludeString

Example

The following example shows how to include a component in a page.

<?
// the component displaying the information block contents
$APPLICATION->IncludeFile("iblock/catalog/element.php", Array(
    // Type of information block
    "IBLOCK_TYPE"       => "catalog",
    // information block
    "IBLOCK_ID"         => "21",
    // element ID
    "ELEMENT_ID"        => $_REQUEST["ID"],
    // URL to the page with the section contents
    "SECTION_URL"       => "/catalog/phone/section.php?",
    // type of information block whose elements are linked to the current one
    "LINK_IBLOCK_TYPE"  => "catalog",
    // ID of information block whose elements are linked to the current one
    "LINK_IBLOCK_ID"    => "22",
    // property with link
    "LINK_PROPERTY_SID" => "PHONE_ID",
    // URL of the page displaying the link of linked elements
    "LINK_ELEMENTS_URL" => "/catalog/accessory/byphone.php?",
    // Fields
    "arrFIELD_CODE" => Array(
         "DETAIL_TEXT",
         "DETAIL_PICTURE"),
     // properties
    "arrPROPERTY_CODE" => Array(
         "YEAR",
         "STANDBY_TIME",
         "TALKTIME",
         "WEIGHT",
         "STANDART",
         "SIZE",
         "BATTERY",
         "SCREEN",
         "WAP",
         "VIBRO",
         "VOICE",
         "PC",
         "MORE_PHOTO",
         "MANUAL"),
    // cache time (sec.)
    "CACHE_TIME"        => "3600",
    ));
?>

Example of including a file in the site epilogue.

<?
// include area
$APPLICATION->IncludeFile($APPLICATION->GetCurDir()."sect_inc.php",
                          Array(),
                          Array(
                          "MODE"      => "html",// use html editor
                          "NAME"      => "Edit include area", // tooltip text
                          // new file template:
                          "TEMPLATE"  => "section_include_template.php"
                          ));
?>


IncludeString

CMain::IncludeString

string
CMain::IncludeString(
 string text,
 array icons = array()
)

The method IncludeString takes a string and returns the HTML code of the specified text bordered in the frame decorated with the specified buttons.

Parameters

Parameter | Description
text | Text to insert in the frame (HTML code).
icons Array of button descriptors. Each descriptor is an array with the following keys:
  • URL - the link to open upon click;
  • SRC - path to the button image;
  • ALT - tooltip text.

See Also

  • CMain::GetShowIncludeAreas

Example

<?
$text = "Some HTML";

// if the button Show Include Areas is checked...
if ($APPLICATION->GetShowIncludeAreas())
{
    $arIcons = Array();
    $arIcons[] =
            Array(
                "URL" => "/bitrix/admin/my_script1.php",
                "SRC" => "/images/my_icon1.gif",
                "ALT" => "tooltip"
            );
    $arIcons[] =
            Array(
                "URL" => "/bitrix/admin/my_script2.php",
                "SRC" => "/images/my_icon2.gif",
                "ALT" => "tooltip"
            );

    // display text "Some HTML" in the frame,
    // with buttons my_icon1.gif and my_icon2.gif
    // linked to scripts my_script1.php and my_script2.php

    echo $APPLICATION->IncludeString($text, $arIcons);
}
else
{
    // otherwise display "Some HTML"
    echo $text;
}
?>
<?
// file /bitrix/modules/advertising/classes/general/advertising.php
// CAdvBanner

// returns HTML of a banner by its type
function Show($TYPE_SID, $HTML_BEFORE="", $HTML_AFTER="")
{
    global $APPLICATION, $USER;
    $arBanner = CAdvBanner::GetRandom($TYPE_SID);
    $strReturn = CAdvBanner::GetHTML($arBanner);
    if (strlen($strReturn)>0)
    {
        CAdvBanner::FixShow($arBanner);
        if ($APPLICATION->GetShowIncludeAreas())
        {
            $isDemo = CAdvContract::IsDemo();
            $arrPERM = CAdvContract::GetUserPermissions($arBanner["CONTRACT_ID"]);
            if (($isDemo || (is_array($arrPERM) &&
                             count($arrPERM)>0)) &&
                             $USER->IsAuthorized())
            {
                $arIcons = Array();
                $arIcons[] =
                        Array(
                            "URL" => "/bitrix/admin/adv_banner_edit.php?lang=".
                                     LANGUAGE_ID.
                                     "&ID=".$arBanner["ID"].
                                     "&CONTRACT_ID=".$arBanner["CONTRACT_ID"],
                            "SRC" => "/bitrix/images/advertising/panel/edit_ad.gif",
                            "ALT" => GetMessage("AD_PUBLIC_ICON_EDIT_BANNER")
                        );
                $arIcons[] =
                        Array(
                            "URL" => "/bitrix/admin/adv_banner_list.php?lang=".
                                     LANGUAGE_ID.
                                     "&find_id=".$arBanner["ID"].
                                     "&find_id_exact_match=Y&find_contract_id[]=".
                                     $arBanner["CONTRACT_ID"]. "&find_type_sid[]=".
                                     $arBanner["TYPE_SID"]."&set_filter=Y",
                            "SRC" => "/bitrix/images/advertising/panel/edit_ad_list.gif",
                            "ALT" => GetMessage("AD_PUBLIC_ICON_BANNER_LIST")
                        );
                $strReturn = $APPLICATION->IncludeString($strReturn, $arIcons);
            }
        }
        $strReturn = $HTML_BEFORE.$strReturn.$HTML_AFTER;
        return $strReturn;
    }
    else return false;
}
?>


IsHTTPS

CMain::IsHTTPS

bool
CMain::IsHTTPS()

The method IsHTTPS determines if the current protocol is secured (HTTPS).

Parameters

No parameters.

Example

<?
global $APPLICATION;
// get the full URI of the current page
$CURRENT_PAGE = (CMain::IsHTTPS()) ? "https://" : "http://";
$CURRENT_PAGE .= $_SERVER["HTTP_HOST"];
$CURRENT_PAGE .= $APPLICATION->GetCurUri();
// $CURRENT_PAGE may contain
// "http://www.mysite.com/en/index.php?id=23"
?>


RemoveFileAccessPermission

CMain::RemoveFileAccessPermission

bool
CMain::RemoveFileAccessPermission(
 string path,
 mixed groups = false
)

The method RemoveFileAccessPermission deletes the access permissions of a file or folder.

Parameters

Parameter Description
path Path to the file or folder relative to the site root. In case of multiple sites, if the root directory is different, this parameters should specify an array:
array("site ID", "Path to the file or folder relative to the site root")
groups Array of groups whose permissions are to be deleted. If false, the method deletes the access permissions of all groups.
Optional; false by default.

Return Values

Returns true on success or false otherwise.

See Also

  • Access permissions
  • CMain::GetFileAccessPermission
  • CMain::CopyFileAccessPermission
  • CMain::SetFileAccessPermission

Example

<?
// delete permissions for the file
// /en/index.php of user groups #5 and #23
if ($APPLICATION->RemoveFileAccessPermission("/en/index.php", array(5, 23)))
    ShowNote("Access permissions modified.");
?>


ResetException

CMain::ResetException

CMain::ResetException()

The method ResetException resets the last exception.

See Also

  • CApplicationException
  • CMain::ThrowException
  • CMain::GetException

Example

<?
$events = GetModuleEvents("main", "OnAfterUserLogin");
while($arEvent = $events->Fetch())
{
   $APPLICATION->ResetException();
   ExecuteModuleEvent($arEvent, $login, $password, $remember, $USER_ID);
   if($err = $APPLICATION->GetException())
      $RESULT_MESSAGE = Array("MESSAGE"=>$err->GetString()."<br>", "TYPE"=>"ERROR");
}
?>


SaveFileContent

CMain::SaveFileContent

bool
CMain::SaveFileContent(
 string abs_path,
 string content
)

The method SaveFileContent saves the page to disk. This method fires the event OnChangeFile.

Parameters

Parameter | Description
abs_path | Fully qualified file path.
content | File contents.

Return Values

Returns true on success or false otherwise.

See Also

  • CMain::GetFileContent
  • Event OnChangeFile
  • RewriteFile

Example

<?
$file_content = '
    <?
    require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
    $APPLICATION->SetTitle("Title");
    ?>
    Page contents...
    <?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>
    ';

$abs_path = $_SERVER["DOCUMENT_ROOT"]."/en/index.php";
if(!$APPLICATION->SaveFileContent($abs_path, $file_content))
    ShowError("Error saving file");
?>


set

CMain::set

CMain::set_cookie(
 string name,
 string value,
 mixed expire = false,
 string path = "/",
 mixed domain = false,
 bool secure = false,
 bool spread = true,
 mixed name_prefix = false
)

The method set sets the cookie and optionally stores its parameters to spread the cookie among sites of different domains.

Parameters

Parameter | Description
name | Name of the cookie.
value | Value of the cookie.
expire Date of the cookie expiration after which the cookie value is not transferred from the client to the site, in the Unix format.
Optional. By default, the cookie is declared valid within 1 year.
path Section (folder) of the site for which the cookie is effective.
Optional; by default the cookie is set for the whole site.
domain Domain for which the cookie is effective.
Optional. By default, the current site is used.
secure Specifies the secure cookie to be set. If true, the cookie value is transferred to the site if only a visitor has connected to the site via the HTTPS protocol.
Optional. The default value is false.
spread | If set to true, the cookie parameters are stored for the subsequent spread among domains (administrative menu Sites, the field Domain name in the site settings).
name_prefix Prefix of the cookie name.
Optional. By default, the value of the parameter Cookie name prefix is used (this parameter is specified in the settings of the Kernel module). You can obtain the value of this parameter using the following call:
COption::GetOptionString("main", "cookie_name", "BITRIX_SM")

See Also

  • Transferring visitors
  • CMain::get_cookie
  • CMain::ShowSpreadCookieHTML

Example

<?
global $APPLICATION;
// set the cookie for 2 years, effective for the directory /en/
$APPLICATION->set_cookie("UK_VISITOR_ID",
                         156,
                         time()+60*60*24*30*12*2,
                         "/en/");
?>


SetAdditionalCSS

CMain::SetAdditionalCSS

CMain::SetAdditionalCSS(
 string path
)

The method SetAdditionalCSS sets the CSS for the page.

Parameters

Parameter | Description
path | Path to the CSS file relative to the root.

See Also

  • CMain::ShowCSS
  • CMain::GetCSS
  • CMain::SetTemplateCSS

Example

<?
$APPLICATION->SetAdditionalCSS("/bitrix/templates/demo/additional.css");
?>


SetCurPage

CMain::SetCurPage

CMain::SetCurPage(
  string page,
  mixed params = false
)

The method SetCurPage is used to set the current page and its parameters in the instance of the CMain class.

Parameters

Parameter | Description
page | Address of the page. For example: "/en/index.php".
params | Strings with parameters. For example: "id=2&s=3&t=4". Optional; if omitted, the current parameters in the CMain instance remain unchanged.

See Also

  • CMain::GetCurUri
  • CMain::GetCurPage
  • CMain::GetCurPageParam
  • CMain::GetCurDir

Example

<?
$APPLICATION->SetCurPage("/en/index.php", "id=2&s=3");
?>


SetDirProperty

CMain::SetDirProperty

CMain::SetDirProperty(
 string property_id,
 string property_value
)

The method SetDirProperty sets the value of the property for the current section.

Parameters

Parameter | Description
property_id | Property identifier.
property_value | Property value.

See Also

  • Page properties and meta tags
  • CMain::ShowProperty
  • CMain::GetProperty
  • CMain::GetPageProperty
  • CMain::GetDirProperty
  • CMain::GetPagePropertyList
  • CMain::GetDirPropertyList
  • CMain::SetPageProperty

Example

<?
$APPLICATION->SetDirProperty("keywords", "design, web, site");
?>


SetFileAccessPermission

CMain::SetFileAccessPermission

bool
CMain::SetFileAccessPermission(
 string path,
 array permissions,
 bool overwrite = true
)

The method SetFileAccessPermission sets the access permissions for a file or folder.

Parameters

Parameter Description
path Path to the file or folder relative to the root. In case of multiple sites, if the root directory is different, this parameters should specify an array:
array("site ID", "Path to the file or folder relative to the site root")
permissions Array with the access permissions in the format Array("user group ID"=>"permission" [, ...]). The permission can be the following:
  • D - access denied;
  • R - read (view file contents);
  • U - workflow (edit file in the Workflow);
  • W - write (direct editing);
  • X - full access (direct editing and permission modification).
The user group ID key can have the value of "*", which means all user groups.
overwrite If true, the existing permissions will be overwritten.
Optional; true by default.

Return Values

Returns true on success or false otherwise.

See Also

  • Access permissions
  • CMain::GetFileAccessPermission
  • CMain::CopyFileAccessPermission
  • CMain::RemoveFileAccessPermission
  • Event OnChangePermissions

Example

<?
// set the following permissions for the file /en/index.php:
// for group #23 - read
// for group #5 - write
// other groups - deny access
if ($APPLICATION->SetFileAccessPermission("/en/index.php",
    array("23" => "R", "5" => "W", "*" => "D")))
    ShowNote("Permissions successfully modified.");
?>


SetPageProperty

CMain::SetPageProperty

CMain::SetPageProperty(
 string property_id,
 string property_value
)

The method SetPageProperty sets the value of the specified property of the current page.

Parameters

Parameter | Description
property_id | Property identifier.
property_value | Property value.

See Also

  • Page properties and meta tags
  • CMain::ShowProperty
  • CMain::GetProperty
  • CMain::GetPageProperty
  • CMain::GetDirProperty
  • CMain::GetPagePropertyList
  • CMain::GetDirPropertyList
  • CMain::SetDirProperty

Example

<?
$APPLICATION->SetPageProperty("keywords", "web, development, programming");
?>


SetTemplateCSS

CMain::SetTemplateCSS

CMain::SetTemplateCSS(
 string rel_path
)

The method SetTemplateCSS assigns the CSS to the component.

Parameters

Parameter | Description
rel_path | Relative path to the CSS file.

See Also

  • CMain::ShowCSS
  • CMain::GetCSS
  • CMain::SetAdditionalCSS

Example

$APPLICATION->SetTemplateCSS("form/form.css");


SetTitle

CMain::SetTitle

CMain::SetTitle(
 string title
)

The method SetTitle sets the page title. If the page title is emitted using CMain::ShowTitle, you can specify it after the output of the prologue.

Parameters

Parameter | Description
title | Page title.

See Also

  • CMain::ShowTitle
  • CMain::GetTitle

Example

<?
$APPLICATION->SetTitle("Page title");
?>


ShowBanner

CMain::ShowBanner

CMain::ShowBanner(
 string banner_type,
 string html_before = false,
 string html_after = false
)

The method ShowBanner includes the Advertising module and displays a banner of the specified type.

Parameters

Parameter | Description
banner_type | Banner type (menu Advertising -> Banner types).
html_before | HTML code to insert before the banner.
html_after | HTML code to insert after the banner.

See Also

  • Advertising module
  • Advertising classes

Example

<?
// connect the advertising module and display the "LEFT" banner
$APPLICATION->ShowBanner("LEFT",
                         "<div align=\"center\">",
                         "<br></div><br>");
?>


ShowCSS

CMain::ShowCSS

CMain::ShowCSS(
 bool external = true
)

The method ShowCSS emits the CSS of a page.

This method utilizes the delay function technology allowing to specify CSS (e.g. inside a component) after the site prologue is emitted.

Parameters

Parameter Description
external If true, the HTML tag <LINK> with the link to the CSS file is emitted:
<LINK href="/bitrix/templates/demo/styles.css" type="text/css" rel="stylesheet">
If false, the inline CSS is outputted:
<style type="text/css">
body { margin: 0px; padding:0px; background-color: #FFFFFF}
...
</style>
Styles located in /bitrix/modules/ are always connected inline (this is generally used in standard components).

See Also

  • Delay functions
  • CMain::GetCSS
  • CMain::SetTemplateCSS
  • CMain::SetAdditionalCSS

Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?= LANG_CHARSET;?>">
<META NAME="ROBOTS" content="ALL">
<?$APPLICATION->ShowMeta("keywords")?>
<?$APPLICATION->ShowMeta("description")?>
<title><?$APPLICATION->ShowTitle()?></title>
<?$APPLICATION->ShowCSS();?>
</head>
<body link="#525252" alink="#F1555A" vlink="#939393" text="#000000">
...


ShowMeta

CMain::ShowMeta

CMain::ShowMeta(
 string property_id,
 string meta_name = false
)

The method ShowMeta emits the page property as the META tag.

If the page does not have the required property, the method searches for the one in parent sections recursively.

This method utilizes the delay function technology allowing to specify meta tags (using CMain::SetPageProperty or CMain::SetDirProperty) after the site prologue is emitted.

Parameters

Parameter | Description
property_id | Identifier of the page or section property whose value will be rendered in the content attribute of the <meta> tag: <meta content="value" ...>
meta_name | Contents of the name attribute of the <meta> tag: <meta name="meta_name" ...> Optional; by default, the property_id name is used.

See Also

  • Delay functions
  • Page properties and meta tags
  • CMain::GetMeta
  • CMain::SetPageProperty
  • CMain::SetDirProperty

Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?=LANG_CHARSET?>">
<META NAME="ROBOTS" content="ALL">
<?$APPLICATION->ShowMeta("keywords")?>
<?$APPLICATION->ShowMeta("description")?>
<title><?$APPLICATION->ShowTitle()?></title>
<?$APPLICATION->ShowCSS();?>
</head>
<body link="#525252" alink="#F1555A" vlink="#939393" text="#000000">
...


ShowNavChain

CMain::ShowNavChain

CMain::ShowNavChain(
 mixed path = false,
 int start_from = 0,
 mixed template_path = false
)

The method ShowNavChain emits the navigation chain.

This method utilizes the delay function technology allowing to add items to the navigation chain after the site prologue is emitted.

If you do not want some page to display the navigation chain, simply initialise the page property NOT_SHOW_NAV_CHAIN with "Y":

$APPLICATION->SetPageProperty("NOT_SHOW_NAV_CHAIN", "Y");

The method ShowNavChain supports this property and respects its value

Parameters

Parameter Description
path Path for which the navigation chain is to be built. In case of multiple sites, if the DOCUMENT_ROOT of the site is different, pass an array in the following format:
array("Site ID", "Path")
Optional. False by default, which means the current site.
start_from Ordinal of item from which to build the chain.
Optional; zero by default.
template_path Path to the navigation chain template.
Optional. The default value is false, which implies searching for the navigation chain template using the algorithm described in the Navigation chain section.

See Also

  • Navigation chain
  • Delay functions
  • CMain::AddChainItem
  • CMain::GetNavChain

Example

<?
// display navchain on the current page
// starting from the first item
// using the template "chain_template.php"
// located in either "/bitrix/templates/<current site template>/",
// or "/bitrix/templates/.default/".
$APPLICATION->ShowNavChain();
?>
<?
// display navchain on the current page
// starting from the second item
// using the template chain_template_bottom.php
$APPLICATION->ShowNavChain(false, 2,
                           "/bitrix/templates/.default/chain_template_bottom.php");
?>

Example of the navigation chain template:

<?
// file /bitrix/templates/.default/chain_template.php

$sChainProlog = "";   // HTML before the navchain
$sChainBody = "";     // navchain item
$sChainEpilog = "";   // HTML after the navchain

// separator
if ($ITEM_INDEX > 0)
   $sChainBody = "<font class=\"chain\">&nbsp;/&nbsp;</font>";

// if the link exists
if (strlen($LINK)>0)
{
    // display link
    $sChainBody .= "<a href=\"".$LINK."\" class=\"chain\">".
                   htmlspecialchars($TITLE)."</a>";
}
else // otherwise
{
    // text
    $sChainBody .= "<font class=\"chain\">".htmlspecialchars($TITLE).
                   "</font>";
}
?>


ShowPanel

CMain::ShowPanel

CMain::ShowPanel()

The method ShowPanel displays the control toolbar in the public section of the site.

This method utilizes the delay function technology allowing to add items to the toolbar after the site prologue is emitted.

If a user does not have enough permissions for at least one command of the toolbar, the toolbar hides. If the toolbar should always be displayed, add the following code to the page:

$APPLICATION->ShowPanel = true;

The following code can be used to determine whether the toolbar has been displayed (using the property PanelShowed of $APPLICATION):

if ($APPLICATION->PanelShowed) echo "Toolbar has been shown!"

Parameters

No parameters.

See Also

  • Control toolbar
  • Delay functions
  • CMain::AddPanelButton
  • Event OnPanelCreate

Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?=LANG_CHARSET;?>">
<META NAME="ROBOTS" content="ALL">
<?$APPLICATION->ShowMeta("keywords")?>
<?$APPLICATION->ShowMeta("description")?>
<title><?$APPLICATION->ShowTitle()?></title>
<?$APPLICATION->ShowCSS();?>
</head>
<body link="#525252" alink="#F1555A" vlink="#939393" text="#000000">
<?$APPLICATION->ShowPanel();?>
...


ShowProperty

CMain::ShowProperty

CMain::ShowProperty(
 string property_id,
 mixed default_value = false
)

The method ShowProperty displays page properties, with respect to the section properties.

This method utilizes the delay function technology allowing to define page properties (e.g. inside a component) after the site prologue is emitted.

Parameters

Parameter | Description
property_id | Property identifier.
default_value | Default value of the property. Optional; the default value is false which means no default value is assigned.

See Also

  • Delay functions
  • Page properties and meta tags
  • CMain::GetProperty
  • CMain::GetPageProperty
  • CMain::GetDirProperty
  • CMain::GetPagePropertyList
  • CMain::GetDirPropertyList
  • CMain::SetPageProperty
  • CMain::SetDirProperty

Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?=LANG_CHARSET;?>">
<META NAME="ROBOTS" content="ALL">
<?$APPLICATION->ShowMeta("keywords")?>
<?$APPLICATION->ShowMeta("description")?>
<title><?$APPLICATION->ShowProperty("page_title")?></title>
<?$APPLICATION->ShowCSS();?>
</head>
<body link="#525252" alink="#F1555A" vlink="#939393" text="#000000">
...


ShowSpreadCookieHTML

CMain::ShowSpreadCookieHTML

CMain::ShowSpreadCookieHTML()

The method ShowSpreadCookieHTML emits the HTML code containing a set of IFRAME tags indended for spreading cookies among domains. This functionality is used with transferring visitors among sites and is included in the visible section of epilogue.

Parameters

No parameter.

See Also

  • Transferring visitors
  • CMain::set_cookie
  • CMain::get_cookie


ShowTitle

CMain::ShowTitle

CMain::ShowTitle(
 string property_name = "title",
 bool strip_tags = true
)

The method ShowTitle displays the page title.

This method utilizes the delay function technology allowing to define page title (e.g. inside a component) after the site prologue is emitted.

Parameters

Parameter | Description
property_name | Identifier of the page property whose value is to be printed as the title (effective if the property had been previously set by CMain::SetPageProperty). Optional; title by default.
strip_tags | If true, deletes all HTML tags from the title. Optional; true by default.

See Also

  • Delay functions
  • CMain::GetTitle
  • CMain::SetTitle

Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type"
      content="text/html; charset=<?= LANG_CHARSET;?>">
<META NAME="ROBOTS" content="ALL">
<?$APPLICATION->ShowMeta("keywords")?>
<?$APPLICATION->ShowMeta("description")?>
<title><?$APPLICATION->ShowTitle()?></title>
<?$APPLICATION->ShowCSS();?>
</head>
<body link="#525252" alink="#F1555A"
      vlink="#939393" text="#000000">
...


ThrowException

CMain::ThrowException

CMain::ThrowException(
 mixed msg,
 mixed id = false
)

The method ThrowException throws an exception msg with the specified id. You can obtain the last exception by calling $APPLICATION->GetException().

Parameters

Parameter | Description
msg | Error description or an instance of class inherited from CApplicationException.
id | Error identifier.

See Also

  • CMain::ResetException
  • CMain::GetException

Example

<?
if($login=='')
{
   global $APPLICATION;
   $APPLICATION->ThrowException('Login must not be empty.');
   return false;
}
?>


CMainPage

CMainPage is the class for use with index page.

Note!
Methods of this class are used if the sites use method 1 to make multiple sites environment.

Methods

Method | Description
GetSiteByHost | Returns site ID, defining it by the current host.
GetSiteByAcceptLanguage | Returns the site ID by the Accept-Language variable in the user browser settings.
RedirectToSite | Redirects to the index page.
GetIncludeSitePage | Returns the absolute path to the index page of the specified site, for further inclusion using require() or include().

See Also

  • List of terms
  • Multiple sites: howtos


GetIncludeSitePage

CMainPage::GetIncludeSitePage

mixed
CMainPage::GetIncludeSitePage(
 string site_id
)

The method GetIncludeSitePage returns the absolute path to the index page of the specified site, for further inclusion using require() or include(). If no site can be identified by host, the function returns false.

Parameters

Parameter | Description
site_id | Site ID.

See Also

  • List of terms
  • Multiple sites: howtos

Example

<?
require($_SERVER['DOCUMENT_ROOT']."/bitrix/modules/main/include/mainpage.php");

if($page = CMainPage::GetIncludeSitePage(CMainPage::GetSiteByHost()))
    require_once($page);

require($_SERVER['DOCUMENT_ROOT']."/bitrix/header.php");?>
<?require($_SERVER['DOCUMENT_ROOT']."/bitrix/footer.php");?>


GetSiteByAcceptLanguage

CMainPage::GetSiteByAcceptLanguage

mixed
CMainPage::GetSiteByAcceptLanguage(
 bool compare_site_id = false
)

The method GetSiteByAcceptLanguage returns the site ID by the Accept-Language variable in the user browser settings. The language order reported by the user browser settings defines the language selection priority for this function. If none of these languages can be found appropriate, a site whose flag Site by default is set will be selected.

Parameters

Parameter | Description
compare_site_id | If the value is true, the search will be performed by matching the language identifier from Accept-Language against the site ID. If set to false, the search will be performed by matching the language identifier against the language ID taken from site settings. Optional. False by default.

See Also

  • List of terms
  • Multiple sites: howtos

Example

Note!
If you intend to use the below example as the index page, please ensure:
1. Your sites use method 1 to make multiple sites environment.
2. None of sites has a value of "/" in the field Site Folder.

<?
require($_SERVER['DOCUMENT_ROOT']."/bitrix/modules/main/include/mainpage.php");

if ($sid = CMainPage::GetSiteByAcceptLanguage())
    CMainPage::RedirectToSite($sid);

require($_SERVER['DOCUMENT_ROOT']."/bitrix/header.php");?>
<?require($_SERVER['DOCUMENT_ROOT']."/bitrix/footer.php");?>


GetSiteByHost

CMainPage::GetSiteByHost

mixed
CMainPage::GetSiteByHost()

The method GetSiteByHost returns site ID, defining it by the current host. If the obtained site ID in invalid the method will return false.

Parameters

No parameters.

See Also

  • List of terms
  • Multiple sites: howtos

Example

<?
require($_SERVER['DOCUMENT_ROOT']."/bitrix/modules/main/include/mainpage.php");

if($page = CMainPage::GetIncludeSitePage(CMainPage::GetSiteByHost()))
    require_once($page);

require($_SERVER['DOCUMENT_ROOT']."/bitrix/header.php");?>
<?require($_SERVER['DOCUMENT_ROOT']."/bitrix/footer.php");?>


RedirectToSite

CMainPage::RedirectToSite

mixed
CMainPage::RedirectToSite(
 string site_id
)

The method RedirectToSite redirects to the index page.

Parameters

Parameter | Description
site_id | Site ID.

See Also

  • List of terms
  • Multiple sites: howtos

Example

Note!
If you intend to use the below example as the index page, please ensure:
1. Your sites use method 1 to make multiple sites environment.
2. None of sites has a value of "/" in the field Site Folder. It means that the root of a site is a separate subdirectory.

<?
require($_SERVER['DOCUMENT_ROOT']."/bitrix/modules/main/include/mainpage.php");

if ($sid = CMainPage::GetSiteByAcceptLanguage())
    CMainPage::RedirectToSite($sid);

require($_SERVER['DOCUMENT_ROOT']."/bitrix/header.php");?>
<?require($_SERVER['DOCUMENT_ROOT']."/bitrix/footer.php");?>


CMenu

CMenu is the class to handle menu.

Properties

Parameter | Description
type | Menu type.
arMenu | An array of menu items (available only after CMenu::Init).
MenuDir | Folder containing file with menu items and parameters (available only after CMenu::Init).
template | Path to file with template (available only after CMenu::Init).

Methods

Method | Description
CMenu | Initializes a menu of the specified type.
Init | Searches for a menu recursively starting from the folder.
GetMenuHtml | Returns the HTML code that can be used to display a menu.
GetMenuHtmlEx | Returns the HTML code that can be used to display a menu.

See Also

  • Menu


CMenu (constructor)

CMenu(
 string type = "left"
)

Creates an instance of the CMenu class.

Parameters

Parameter | Description
type | Menu type. Menu types are defined in the Site explorer module settings. Optional. Left by default.

See Also

  • Menu
  • CMain::GetMenu

Example

<?
$lm = new CMenu("left");
$lm->Init($APPLICATION->GetCurDir(), true);
$lm->template = "/bitrix/templates/demo/left.menu_template.php";
echo $lm->GetMenuHtml();
?>


GetMenuHtml

CMenu::GetMenuHtml

string
CMenu::GetMenuHtml()

The method GetMenuHtml returns the HTML code that can be used to display a menu.

Parameters

No parameters.

See Also

  • Menu
  • CMenu::GetMenuHtmlEx
  • CMain::GetMenuHtml
  • CMain::GetMenuHtmlEx

Example

<?
$lm = new CMenu("left");
$lm->Init($APPLICATION->GetCurDir(), true);
$lm->template = "/bitrix/templates/demo/left.menu_template.php";
echo $lm->GetMenuHtml();
?>


GetMenuHtmlEx

CMenu::GetMenuHtmlEx

string
CMenu::GetMenuHtmlEx()

The method GetMenuHtmlEx returns the HTML code that can be used to display menu. Unlike the method CMenu::GetMenuHtml the menu template will be included only once.

Note!
The menu template used by this function must explicitly initialize the variable $sMenu, with the HTML code describing the whole menu.

Parameters

No parameters.

See Also

  • Menu
  • CMenu::GetMenuHtml
  • CMain::GetMenuHtml
  • CMain::GetMenuHtmlEx

Example

<?
$lm = new CMenu("left");
$lm->Init($APPLICATION->GetCurDir(), true);
$lm->template = "/bitrix/templates/demo/left.menu_template.php";
echo $lm->GetMenuHtmlEx();
?>


Init

CMenu::Init

bool
CMenu::Init(
 string dir
 bool use_ext = false,
 string template_path = false
)

The method Init initializes the CMenu class instance (fills it with menu items). Returns true if the site directory contains the menu file .menu type.menu.php (the search is performed up the directory hierarchy starting from the folder dir). Otherwise, it returns false.

Parameters

Parameter | Description
dir | The folder from which the search for file .menu type.menu.php is performed (file with menu items and parameters ).
use_ext If true the file .menu type.menu_ext.php. will be included in addition to .menu type.menu.php to create the menu array. These files allow to handle the menu array $aMenuLinks as desired (for example: add menu items from information blocks).
Optional. False by default.
template_path Template used to display menu.

Optional. False by default, which means first searching for the template in the file /bitrix/templates/current site template ID/menu type.menu_template.php. If the template cannot be found, the file /bitrix/templates/.default/menu type.menu_template.php will be searched.

The following preset variables are available in the template:
  • $arMENU - copy of menu array;
  • $arMENU_LINK - link to the current menu array;
  • $TEXT - text of the current menu item;
  • $LINK - link on the current menu item;
  • $SELECTED - whether the menu item is currently selected;
  • $PERMISSION - access permission for the page specified in the $LINK field. Following values are possible:
    • D - access denied;
    • R - read access (view the file contents);
    • U - workflow (edit file in the workflow mode);
    • W - write (direct modification is allowed);
    • X - full access (both direct file modification and editing the access permission are allowed).
  • $ADDITIONAL_LINKS - additional links for menu highlighting;
  • $ITEM_TYPE - "D" stands for directory (if $LINK ends with "/"), otherwise "P" (page);
  • $ITEM_INDEX - menu item ordinal;
  • $PARAMS - parameters of menu items.
The menu template needs to have the following variables initialized:
  • $sMenuProlog - the HTML code to add before menu items;
  • $sMenuEpilog - the HTML code to add after menu items;
  • $sMenuBody - the HTML code describing a menu item;
  • $sMenu - the HTML code describing the whole menu (only for functions GetMenuHtmlEx).

See Also

  • Menu
  • CMain::GetMenu

Example

<?
$lm = new CMenu("left");
$lm->Init($APPLICATION->GetCurDir(), true);
$lm->template = "/bitrix/templates/demo/left.menu_template.php";
echo $lm->GetMenuHtml();
?>


CModule

CModule is the class to handle modules.

All the classes describing the specific modules in the system must inherit from the CModule class. Classes implementing any module must have name equal to the module ID. The module description must reside in file /bitrix/modules/module ID/install/index.php.

Properties

Parameter | Description
MODULE_ID | Module ID.
MODULE_VERSION | Current module version.
MODULE_VERSION_DATE | Date of the current module version.
MODULE_NAME | Module name.
MODULE_DESCRIPTION | Module description.
MODULE_GROUP_RIGHTS | If "Y", the module supports the access permission distribution schema specified in the module settings.

Methods

Method | Description
GetList | Returns a list of modules installed in the system.
GetDropDownList | Returns selection from the database which can be passed to functions SelectBox.
Add | Adds the module ID to the table b_module.
Remove | Deletes the module ID from the table b_module.
GetModuleRightList | Returns the array describing a specialized schema of the module access permission distribution.
DoInstall | Launches the module installation procedure.
DoUninstall | Launches the module uninstallation procedure.
IncludeModule | Checks whether the module is installed and if so, includes it (namely, includes file /bitrix/modules/module ID/include.php).
IsInstalled | Determines whether the module is installed.

See Also

  • Modules
  • Module ID's
  • Functions to handle modules


Add

CModule::Add()

The method Add adds the module ID to the table b_module.

Parameters

No parameters.

See Also

  • RegisterModule
  • CModule::Remove

Example

<?
$m = new CModule;
$m->MODULE_ID = "iblock";
$m->Add();
?>


DoInstall

CModule::DoInstall

CModule::DoInstall()

The method DoInstall launches the module installation procedure.

Parameters

No parameters.

See Also

  • RegisterModule

Example

<?
// if "Install" or "Uninstall" is clicked...
if(strlen($uninstall)>0 || strlen($install)>0)
{
    // check if the required file exists in the module directory
    if(@file_exists($DOCUMENT_ROOT."/bitrix/modules/".$module_id."/install/index.php"))
    {
        include_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/".$module_id."/install/index.php");
        $obModule = new $module_id;
        if($obModule->IsInstalled() && strlen($uninstall)>0) $obModule->DoUninstall();
        elseif(!$obModule->IsInstalled() && strlen($install)>0) $obModule->DoInstall();
    }
}
?>


DoUninstall

CModule::DoUninstall

CModule::DoUninstall()

The method DoUninstall launches the module uninstallation procedure.

Parameters

No parameters.

See Also

  • UnRegisterModule

Example

<?
// if "Install" or "Uninstall" is clicked...
if(strlen($uninstall)>0 || strlen($install)>0)
{
    // check if the required file exists in the module directory
    if(@file_exists($DOCUMENT_ROOT."/bitrix/modules/".$module_id."/install/index.php"))
    {
        include_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/".$module_id."/install/index.php");
        $obModule = new $module_id;
        if($obModule->IsInstalled() && strlen($uninstall)>0) $obModule->DoUninstall();
        elseif(!$obModule->IsInstalled() && strlen($install)>0) $obModule->DoInstall();
    }
}
?>


GetDropdownList

CDBResult
CModule::GetDropdownList(
 string sql = "ORDER BY ID"
)

The method GetDropdownList returns a list of modules as the CDBResult instance which can be passed to functions SelectBox or SelectBoxM used to emit the HTML tag <select>.

Parameters

Parameter | Description
sql | The SQL code can be used to specify the sorting of selected modules ID's. Optional. By default, ID's are sorted in descending order by the field ID.

See Also

  • CModule::GetList
  • SelectBox
  • SelectBoxM

Example

<?
$rs = CModule::GetDropdownList();
echo SelectBoxFromArray("module_id", $rs, $module_id);
?>


GetList

CDBResult
CModule::GetList()

The method GetList returns a list of modules as the CDBResult instance.

Parameters

No parameters.

See Also

  • CModule::GetDropDownList

Example

<?
$rsInstalledModules = CModule::GetList();
while ($ar = $rsInstalledModules->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetModuleRightList

CModule::GetModuleRightList

array
CModule::GetModuleRightList()

The method GetModuleRightList returns an array describing a specialized schema of the module access permission distribution. This function is a method of class describing the specific module. If a module requires the specialized schema of access permission distribution, the CModule class of that module should implement this method.

A situation is possible when a module supports the schema of access permission distribution (property MODULE_GROUP_RIGHTS="Y") alike the standard one and the default schema is used. In this case, the array describing the default schema can be obtained using the CMain::GetDefaultRightList() function.

Note!
The array describing the schema of the Kernel module access permission distribution can be obtained using the CMain::GetMainRightList() function.

Parameters

No parameters.

See Also

  • Access permissions
  • CMain::GetUserRight
  • CMain::GetUserRoles

Example

<?
// display permissions of installed modules
$rs = CModule::GetList();
while ($ar = $rs->Fetch()) :
    $MID = $ar["ID"];
    if ($MID!="main") :
        include_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/".$MID."/install/index.php");
        if (class_exists($MID)) :
            $obModule = new $MID;
            if ($obModule->MODULE_GROUP_RIGHTS=="Y") :
                if (method_exists($obModule, "GetModuleRightList"))
                    $arRights = call_user_method("GetModuleRightList",$obModule);
                else
                    $arRights = $APPLICATION->GetDefaultRightList();

                echo $MID.": ".SelectBoxFromArray("RIGHTS_MODULE_".$MID, $arRights, ${"RIGHTS_MODULE_".$MID}, "<by default>");
            endif;
        endif;
    else:
        $arRights = $APPLICATION->GetMainRightList();
        echo $MID.": ".SelectBoxFromArray("RIGHTS_MODULE_".$MID, $arRights, ${"RIGHTS_MODULE_".$MID}, "<by default>");
    endif;
endwhile;
?>


IncludeModule

CModule::IncludeModule

bool
CModule::IncludeModule(
 string module_id
)

The method IncludeModule checks whether the module is installed and if so, includes it (namely, includes file /bitrix/modules/module ID/include.php). Returns true on success, false otherwise.

Parameters

Parameter | Description
module_id | Module ID.

See Also

  • IsModuleInstalled
  • CModule::IsInstalled
  • Module ID's

Example

<?
//  check whether the Information blocks module is installed and if so, include it
if (CModule::IncludeModule("iblock")):
    // call the Information blocks module functions here
    ...
endif;
?>


IsInstalled

CModule::IsInstalled

mixed
CModule::IsInstalled()

The method IsInstalled determines whether the module is installed. Returns true if the module is installed, false otherwise.

Note!
Before using functions and classes of any module, include it using the CModule::IncludeModule function.

Parameters

No parameters.

See Also

  • IsModuleInstalled
  • CModule::IncludeModule
  • Module ID's

Example

<?
// if "Install" or "Uninstall" is clicked...
if(strlen($uninstall)>0 || strlen($install)>0)
{
    // check if the required file exists in the module directory
    if(@file_exists($DOCUMENT_ROOT."/bitrix/modules/".$module_id."/install/index.php"))
    {
        include_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/".$module_id."/install/index.php");
        $obModule = new $module_id;
        if($obModule->IsInstalled() && strlen($uninstall)>0) $obModule->DoUninstall();
        elseif(!$obModule->IsInstalled() && strlen($install)>0) $obModule->DoInstall();
    }
}
?>


Remove

CModule::Remove()

The method Remove deletes a record with the module description from the database.

Parameters

No parameters.

See Also

  • UnRegisterModule
  • CModule::Add

Example

<?
function UnRegisterModule($id)
{
    $m = new CModule;
    $m->MODULE_ID = $id;
    $m->Remove();
    CAllMain::DelGroupRight($id);
}
?>


COption

COption is the class to handle module parameters stored in the database.

Usually, module settings can be customized in the administrative interface (in the settings of the corresponding modules).

Methods

Method | Description
GetOptionString | Returns string value of the parameter.
SetOptionString | Sets the string value of the parameter.
GetOptionInt | Returns numeric value of the parameter.
SetOptionInt | Sets numeric value of the parameter.
RemoveOption | Removes the parameter from the database.

See Also

  • Module parameters
  • CPageOption class


GetOptionInt

COption::GetOptionInt

int
COption::GetOptionInt(
 string module_id,
 string option_id,
 mixed default_value = false
)

The method GetOptionInt returns numeric value of the parameter option_id, belonging to module_id.

Parameters

Parameter | Description
module_id | Module ID.
option_id | Parameter ID.
default_value | Default value. If default_value is not specified, it will be taken from the array with name ${module_id."_default_option"} specified in file /bitrix/modules/module_id/default_option.php.

See Also

  • Module parameters
  • Kernel module settings
  • COption::GetOptionString

Example

<?
// obtain field "Default person in charge"
// from the "Techsupport" module
$RESPONSIBLE_USER_ID = COption::GetOptionInt("support", "DEFAULT_RESPONSIBLE_ID"));
?>


GetOptionString

COption::GetOptionString

string
COption::GetOptionString(
 string module_id,
 string option_id,
 mixed default_value = false
)

The method GetOptionString returns string value of the parameter option_id, belonging to module_id.

Parameters

Parameter | Description
module_id | Module ID.
option_id | Parameter ID.
default_value | Default value. If default_value is not specified, it will be taken from the array with name ${module_id."_default_option"} specified in file /bitrix/modules/module_id/default_option.php.

See Also

  • Module parameters
  • Kernel module settings
  • COption::GetOptionInt

Example

<?
// obtain field "Add to group upon registration"
// from the Kernel module settings
$default_group = COption::GetOptionString("main", "new_user_registration_def_group", "2");
if($default_group!="")
    $arrGroups = explode(",",$default_group);
?>


RemoveOption

COption::RemoveOption

bool
COption::RemoveOption(
 string module_id,
 string option_id = ""
)

The method RemoveOption removes one (option_id) or all parameters of the module_id from the database.

Parameters

Parameter | Description
module_id | Module ID.
option_id | Parameter ID. Optional. Empty by default which means to remove all the module parameters.

See Also

  • Module parameters
  • Kernel module settings

Example

<?
// remove parameter "Results per page"
// of the "Web forms" module from the database
COption::RemoveOption("form", "RESULTS_PAGEN");
?>


SetOptionInt

COption::SetOptionInt

bool
COption::SetOptionInt(
 string module_id,
 string option_id,
 mixed value = "",
 mixed description = false
)

The method SetOptionInt sets numeric value of the parameter option_id for the module_id. Returns true on success, or false otherwise.

Parameters

Parameter | Description
module_id | Module ID.
option_id | Parameter ID.
value | Parameter value. Optional. Empty by default.
description | Parameter description. Optional. False by default which means that the description is absent.

See Also

  • Module parameters
  • Kernel module settings
  • COption::SetOptionString

Example

<?
// set the value of the field
// "Additional menu parameters"
// in the "Site explorer" module settings
COption::SetOptionInt("fileman", "num_menu_param", 2);
?>


SetOptionString

COption::SetOptionString

bool
COption::SetOptionString(
 string module_id,
 string option_id,
 string value = "",
 mixed description = false
)

The method SetOptionString sets the string value of the parameter option_id for the module_id. Returns true on success, or false otherwise.

Parameters

Parameter | Description
module_id | Module ID.
option_id | Parameter ID.
value | Parameter value. Optional. Empty by default.
description | Parameter description. Optional. False by default which means that the description is absent.

See Also

  • Module parameters
  • Kernel module settings
  • COption::SetOptionInt

Example

<?
// set the value of the field
// "Site administrator E-Mail (default sender)"
// from the Kernel module settings
COption::SetOptionString("main","email_from","admin@site.com");
?>


CPageCache

CPageCache is the class used to cache the HTML result of the script execution.

Methods

Method | Description
StartDataCache | Initializes the caching mechanism and starts buffered HTML output, or outputs the cache content.
EndDataCache | Stores the buffered HTML in the cache file.
InitCache | Initializes the caching mechanism.
Output | Emits the HTML result stored in cache.
IsCacheExpired | Checks whether the cache is expired or not.

See Also

  • Caching
  • CPHPCache class
  • Special parameters


EndDataCache

CPageCache::EndDataCache

CPageCache::EndDataCache()

The method EndDataCache outputs the buffered HTML and stores it in the cache file on disc.

Parameters

No parameters.

See Also

  • Caching
  • CPageCache::StartDataCache

Example

<?
// create an object
$obCache = new CPageCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all parameters
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$IBLOCK_TYPE.$USER->GetUserGroupString();

// initialize buffered output
if($obCache->StartDataCache($life_time, $cache_id, "/")):
    // obtain the information block element parameters from the database
    if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
        echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
    endif;
    // write the buffered result to the cache file on disc
    $obCache->EndDataCache();
endif;
?>


InitCache

CPageCache::InitCache

bool
CPageCache::InitCache(
 int cache_life_time,
 string cache_id,
 mixed init_dir = false
)

The method InitCache initializes a number of properties of the CPageCache class instance. If the cache file is absent or expired, the function will return false, or true otherwise.

Parameters

Parameter | Description
cache_life_time | Cache time to live, in seconds.
cache_id | A unique cache ID. This ID must contain all the parameters which may affect the result of cached code execution.
init_dir | The name of directory for which the cache is valid. If "/", the cache is valid for all site directories. Optional. Current directory is used by default.

See Also

  • Caching
  • CPageCache::Output
  • CDBResult::NavStringForCache


IsCacheExpired

CPageCache::IsCacheExpired

bool
CPageCache::IsCacheExpired(
 string full_path
)

The method IsCacheExpired checks whether the cache is expired or not. Usually, the function is used to delete the expired cache files.

Note!
A cache file created by the CPageCache class functions has the ".html" extension.

Parameters

Parameter | Description
full_path | The full path to the cache file.

See Also

  • Caching
  • CPageCache::InitCache
  • BXClearCache

Example

<?
$path = $_SERVER["DOCUMENT_ROOT"]."/bitrix/cache/";
if($handle = @opendir($path))
{
    while(($file=readdir($handle))!==false)
    {
        if($file == "." || $file == "..") continue;
        if(!is_dir($path."/".$file))
        {
            if(substr($file, -5)==".html")
                $expired = CPageCache::IsCacheExpired($path."/".$file);
            elseif(substr($file, -4)==".php")
                $expired = CPHPCache::IsCacheExpired($path."/".$file);
        }
    }
}
?>


Output

CPageCache::Output

CPageCache::Output()

The method Output emits cache content. The HTML cache content is available if only the cache file exists and the CPageCache::InitCache or CPageCache::StartDataCache method is called beforehand.

Parameters

No parameters.

See Also

  • Caching
  • CPageCache::InitCache
  • CPageCache::StartDataCache


StartDataCache

CPageCache::StartDataCache

bool
CPageCache::StartDataCache(
 int cache_life_time,
 string cache_id,
 mixed init_dir = false
)

The method StartDataCache starts buffered HTML output, or outputs the cache content if it is not expired yet. If the cache file is expired, the function returns true, or false otherwise.

Parameters

Parameter | Description
cache_life_time | Cache time to live, in seconds.
cache_id | A unique cache ID. This ID must contain all the parameters which may affect the result of cached code execution.
init_dir | The name of directory for which the cache is valid. If "/", the cache is valid for all site directories. Optional. Current directory is used by default.

See Also

  • Caching
  • CPageCache::EndDataCache
  • CDBResult::NavStringForCache

Example

<?
// create an object
$obCache = new CPageCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all parameters
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$IBLOCK_TYPE.$USER->GetUserGroupString();

// initialize buffered output
if($obCache->StartDataCache($life_time, $cache_id, "/")):
    // obtain the information block element parameters from the database
    if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
        echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
    endif;
    // write the preliminary buffered output to the cache file
    $obCache->EndDataCache();
endif;
?>


CPageOption

CPageOption is the class to handle page parameters.

Methods

Method | Description
GetOptionString | Returns the string value of the page parameter.
SetOptionString | Sets the string value of the page parameter.
GetOptionInt | Returns the numeric value of the page parameter.
SetOptionInt | Sets the numeric value of the page parameter.
RemoveOption | Removes page parameter.

See Also

  • Page parameters
  • COption class


GetOptionInt

CPageOption::GetOptionInt

int
CPageOption::GetOptionInt(
 string module_id,
 string page_option_id,
 mixed default_value = false
)

The GetOptionInt method returns the numeric value of the parameter page_option_id, belonging to module_id.

Parameters

Parameter | Description
module_id | Module ID.
page_option_id | A page parameter ID.
default_value | Default value.

See Also

  • Page parameters
  • CPageOption::GetOptionString

Example

<?
$my_parameter = CPageOption::GetOptionInt("main", "MY_PARAMETER", 21);
?>


GetOptionString

CPageOption::GetOptionString

string
CPageOption::GetOptionString(
 string module_id,
 string page_option_id,
 mixed default_value = false
)

The GetOptionString method returns the string value of the parameter page_option_id, belonging to module_id.

Parameters

Parameter | Description
module_id | Module ID.
page_option_id | A page parameter ID.
default_value | Default value.

See Also

  • Page parameters
  • CPageOption::GetOptionInt

Example

<?
$my_parameter = CPageOption::GetOptionString("main", "MY_PARAMETER", "Y");
?>


RemoveOption

CPageOption::RemoveOption

bool
CPageOption::RemoveOption(
 string module_id,
 string page_option_id = ""
)

The RemoveOption method removes one (page_option_id) or all parameters of the module_id for this page.

Parameters

Parameter | Description
module_id | Module ID.
page_option_id | A page parameter ID. Optional. Empty by default which means to remove all parameters of the module_id for this page.

See Also

  • Page parameters

Example

<?
// remove parameter MY_PARAMETER for the current page
CPageOption::RemoveOption("main", "MY_PARAMETER");
?>


SetOptionInt

CPageOption::SetOptionInt

bool
CPageOption::SetOptionInt(
 string module_id,
 string page_option_id,
 mixed value = ""
)

The SetOptionInt method sets the numeric value of the parameter page_option_id for the module_id. Returns true on success, or false otherwise.

Parameters

Parameter | Description
module_id | Module ID.
page_option_id | A page parameter ID.
value | Parameter value. Optional. Empty by default.

See Also

  • Page parameters
  • CPageOption::SetOptionString

Example

<?
CPageOption::SetOptionInt("main", "MY_PARAMETER", 2);
?>


SetOptionString

CPageOption::SetOptionString

bool
CPageOption::SetOptionString(
 string module_id,
 string page_option_id,
 string value = ""
)

The SetOptionString method sets the string value of the parameter page_option_id for the module_id. Returns true on success, or false otherwise.

Parameters

Parameter | Description
module_id | Module ID.
page_option_id | A page parameter ID.
value | Parameter value. Optional. Empty by default.

See Also

  • Page parameters
  • CPageOption::SetOptionInt

Example

<?
// The example shows how to prohibit storing the number of the last page in session,
// with standard pagewise navigation.
// The last open page of pagewise navigation is remembered in session by default.
// If you want to change this behavior for the current page,
// use the following code before CDBResult::NavPrint:
CPageOption::SetOptionString("main", "nav_page_in_session", "N")

// To restore the default mode:
CPageOption::SetOptionString("main", "nav_page_in_session", "Y");
?>


CPHPCache

CPHPCache is the class used to cache PHP variables and HTML results of script execution.

Methods

Method | Description
StartDataCache | Initializes the caching mechanism and starts the buffered HTML output, or emits the cache content.
EndDataCache | Stores the buffered HTML output and PHP variables to the cache file.
InitCache | Initializes the caching mechanism.
GetVars | Returns PHP variables stored in cache.
Output | Emits the cached HTML result.
IsCacheExpired | Checks whether the cache is expired or not.

See also

  • Caching
  • CPageCache class
  • Special parameters
    • © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


EndDataCache

che::EndDataCache

che::EndDataCache(
 mixed vars = false
)

The method EndDataCache outputs the buffered HTML and stores it to cache file on disc together with the specified array of variables.

Parameters

Parameter Description
vars The array of variables whose values are to be written to the cache file. Array should be in the following format:
array(
 "VARIABLE NAME  1" => "VARIABLE VALUE 1",
 "VARIABLE NAME 2" => "VARIABLE VALUE 2",
 ...)
Optional. An array of variables specified in the function CPHPCache::StartDataCache is used by default.

See Also

  • Caching
  • CPHPCache::StartDataCache

Example

<?
// create an object
$obCache = new CPHPCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all parameters
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$SECTION_ID.$USER->GetUserGroupString();

// if the cache exists and is not expired...
if($obCache->InitCache($life_time, $cache_id, "/") :
    // obtain cached variables
    $vars = $obCache->GetVars();
    $SECTION_TITLE = $vars["SECTION_TITLE"];
else :
    // otherwise call database
    $arSection = GetIBlockSection($SECTION_ID);
    $SECTION_TITLE = $arSection["NAME"];
endif;

// add a menu item to the navigation chain
$APPLICATION->AddChainItem($SECTION_TITLE, $SECTION_URL."SECTION_ID=".$SECTION_ID);

// start buffered output
if($obCache->StartDataCache()):

    // obtain the information block element parameters from the database
    if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
        echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
    endif;

    // write the preliminary buffered output to the cache file
    // together with an additional variable
    $obCache->EndDataCache(array(
        "SECTION_TITLE"    => $SECTION_TITLE
        ));
endif;
?>


GetVars

CPHPCache::GetVars

array
CPHPCache::GetVars()

The method GetVars returns PHP variables stored in cache.

Parameters

No parameters.

See Also

  • Caching
  • CPHPCache::InitCache
  • CPHPCache::StartDataCache

Example

<?
// create an object
$obCache = new CPHPCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all parameters
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$SECTION_ID.$USER->GetUserGroupString();

// if the cache exists and is not expired...
if($obCache->InitCache($life_time, $cache_id, "/") :
    // obtain cached variables
    $vars = $obCache->GetVars();
    $SECTION_TITLE = $vars["SECTION_TITLE"];
else :
    // otherwise call database
    $arSection = GetIBlockSection($SECTION_ID);
    $SECTION_TITLE = $arSection["NAME"];
endif;

// add a menu item to the navigation chain
$APPLICATION->AddChainItem($SECTION_TITLE, $SECTION_URL."SECTION_ID=".$SECTION_ID);

// start buffered output
if($obCache->StartDataCache()):

    // obtain the information block element parameters from the database
    if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
        echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
    endif;

    // write the preliminary buffered output to the cache file
    // together with an additional variable
    $obCache->EndDataCache(array(
        "SECTION_TITLE"    => $SECTION_TITLE
        ));
endif;
?>


InitCache

CPHPCache::InitCache

bool
CPHPCache::InitCache(
 int cache_life_time,
 string cache_id,
 mixed init_dir = false
)

The method InitCache initializes a number of properties of the CPHPCache class instance. If the cache file is absent or expired, the function will return false, or true otherwise.

Parameters

Parameter | Description
cache_life_time | Cache time to live, in seconds.
cache_id | A unique cache ID. This ID must contain all the parameters which may affect the result of cached code execution.
init_dir | The name of directory for which the cache is valid. If "/", the cache is valid for all site directories. Optional. Current directory is used by default.

See Also

  • Caching
  • CPHPCache::Output
  • CDBResult::NavStringForCache

Example

<?
// create an object
$obCache = new CPHPCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all parameters
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$SECTION_ID.$USER->GetUserGroupString();

// if the cache exists and is not expired...
if($obCache->InitCache($life_time, $cache_id, "/") :
    // obtain cached variables
    $vars = $obCache->GetVars();
    $SECTION_TITLE = $vars["SECTION_TITLE"];
else :
    // otherwise call the database
    $arSection = GetIBlockSection($SECTION_ID);
    $SECTION_TITLE = $arSection["NAME"];
endif;

// add a menu item to the navigation chain
$APPLICATION->AddChainItem($SECTION_TITLE, $SECTION_URL."SECTION_ID=".$SECTION_ID);

// start buffered output
if($obCache->StartDataCache()):

    // obtain the information block element parameters from the database
    if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
        echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
    endif;

    // write the preliminary buffered output to the cache file
    // together with an additional variable
    $obCache->EndDataCache(array(
        "SECTION_TITLE"    => $SECTION_TITLE
        ));
endif;
?>


IsCacheExpired

CPHPCache::IsCacheExpired

bool
CPHPCache::IsCacheExpired(
 string full_path
)

The method IsCacheExpired checks whether the cache is expired or not. Usually, the function is used to delete the expired cache files.

Note!
A cache file created by the CPHPCache class functions has the ".php" extention.

Parameters

Parameter | Description
full_path | The full path to the cache file.

See Also

  • Caching
  • CPHPCache::InitCache
  • BXClearCache

Example

<?
$path = $_SERVER["DOCUMENT_ROOT"]."/bitrix/cache/";
if($handle = @opendir($path))
{
    while(($file=readdir($handle))!==false)
    {
        if($file == "." || $file == "..") continue;
        if(!is_dir($path."/".$file))
        {
            if(substr($file, -5)==".html")
                $expired = CPageCache::IsCacheExpired($path."/".$file);
            elseif(substr($file, -4)==".php")
                $expired = CPHPCache::IsCacheExpired($path."/".$file);
        }
    }
}
?>


Output

CPHPCache::Output

CPHPCache::Output()

The method Output emits the cached HTML content.

Parameters

No parameters.

See Also

  • Caching
  • CPHPCache::InitCache
  • CPHPCache::StartDataCache

Example

<?
// create an object
$obCache = new CPHPCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all parameters
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$SECTION_ID.$USER->GetUserGroupString();

// if the cache exists and is not expired...
if($obCache->InitCache($life_time, $cache_id, "/") :

    // obtain cached variables
    $vars = $obCache->GetVars();
    $SECTION_TITLE = $vars["SECTION_TITLE"];

    // add a menu item to the navigation chain
    $APPLICATION->AddChainItem($SECTION_TITLE, $SECTION_URL."SECTION_ID=".$SECTION_ID);

    // display the cache contents
    $obCache->Output();

else :

    // otherwise call the database
    $arSection = GetIBlockSection($SECTION_ID);
    $SECTION_TITLE = $arSection["NAME"];

    // add a menu item to the navigation chain
    $APPLICATION->AddChainItem($SECTION_TITLE, $SECTION_URL."SECTION_ID=".$SECTION_ID);

    // start buffered output
    if($obCache->StartDataCache()):

        // obtain the information block element parameters from the database
        if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
            echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
        endif;

        // write the preliminary buffered output to the cache file
        // together with an additional variable
        $obCache->EndDataCache(array(
            "SECTION_TITLE"        => $SECTION_TITLE
            ));
    endif;
endif;
?>


StartDataCache

CPHPCache::StartDataCache

bool
CPHPCache::StartDataCache(
 int cache_life_time = false,
 string cache_id = false,
 mixed init_dir = false,
 array vars = array()
)

The method StartDataCache starts the buffered HTML output, or emits the cache content if it is not expired yet. If the cache file is expired the function returns true, or false otherwise.

Parameters

Parameter Description
cache_life_time Cache time to live, in seconds.
Optional. Cache lifetime specified in the InitCache function is used by default.
cache_id A unique cache ID. This ID must contain all the parameters which may affect the result of cached code execution.
Optional. The unique cache ID specified in the CPHPCache::InitCache function is used by default.
init_dir The name of directory for which the cache is valid. If "/", the cache is valid for all site directories.
Optional. The name of directory specified in the CPHPCache::InitCache function is used by default.
vars An array of variables which are to be cached. Array should be in the following format:
array(
 "VARIABLE NAME 1" => "VARIABLE VALUE 1",
 "VARIABLE NAME 2" => "VARIABLE VALUE 2",
 ...)
The variables to be written to the cache file are flushed to disc by the CPHPCache::EndDataCache function.
Optional. The default value is an empty array.

See Also

  • Caching
  • CPHPCache::EndDataCache
  • CDBResult::NavStringForCache

Example

<?
// create an object
$obCache = new CPHPCache;

// caching time - 30 minutes
$life_time = 30*60;

// form the cache ID according to all parameters
// which may affect the resulting HTML
$cache_id = $ELEMENT_ID.$SECTION_ID.$USER->GetUserGroupString();

// if the cache exists and is not expired...
if($obCache->InitCache($life_time, $cache_id, "/") :
    // obtain cached variables
    $vars = $obCache->GetVars();
    $SECTION_TITLE = $vars["SECTION_TITLE"];
else :
    // otherwise call the database
    $arSection = GetIBlockSection($SECTION_ID);
    $SECTION_TITLE = $arSection["NAME"];
endif;

// add a menu item to the navigation chain
$APPLICATION->AddChainItem($SECTION_TITLE, $SECTION_URL."SECTION_ID=".$SECTION_ID);

// start buffered output
if($obCache->StartDataCache()):

    // obtain the information block element parameters from the database
    if($arIBlockElement = GetIBlockElement($ELEMENT_ID, $IBLOCK_TYPE)):
        echo "<pre>"; print_r($arIBlockElement); echo "</pre>";
    endif;

    // write the preliminary buffered output to the cache file
    // together with an additional variable
    $obCache->EndDataCache(array(
        "SECTION_TITLE"    => $SECTION_TITLE
        ));
endif;
?>


CSite

CSite is the class used to manage sites.

Fields

Field | Type | Description
LID | char (2) | The site ID.
SORT | int | Sort order.
DEF | char | The default site (Y|N).
ACTIVE | char | Active state (Y|N).
NAME | varchar (50) | The site short name.
DIR | varchar (50) | Root directory of the site content.
FORMAT_DATE | varchar (50) | Date format.
FORMAT_DATETIME | varchar (50) | Date and time format.
CHARSET | varchar (255) | Encoding of site pages.
LANGUAGE_ID | char (2) | Site language ID.
DOC_ROOT | varchar (255) | Full path to the root directory of the site web server content (if sites have different DOCUMENT_ROOT).
SERVER_NAME | varchar (255) | The site URL.
SITE_NAME | varchar (255) | The site full name.
EMAIL | varchar (255) | The default e-mail address.

Methods

Method | Description
GetList | Returns the list of sites.
GetByID | Retrieves information about the specified site .
GetDateFormat | Returns date format for the site language.
Add | Adds a new site.
Update | Changes the existing site.
Delete | Deletes a site.

See Also

  • Sites


Add

CSite::Add

mixed
CSite::Add(
 array fields
)

The method Add adds a new site. Returns the ID of the added site. In case of an error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter | Description
fields | An array of the field values in the form of array("field"=>"value" [, ...]).

See Also

  • CSite fields
  • CSite::Update
  • CSite::Delete

Example

<?
$arFields = Array(
  "LID"              => "ru",
  "ACTIVE"           => "Y",
  "SORT"             => 200,
  "DEF"              => "N",
  "NAME"             => "www.site.com",
  "DIR"              => "/en/",
  "FORMAT_DATE"      => "DD.MM.YYYY",
  "FORMAT_DATETIME"  => "DD.MM.YYYY HH:MI:SS",
  "CHARSET"          => "windows-1251",
  "SITE_NAME"        => "My site",
  "SERVER_NAME"      => "www.site.com",
  "EMAIL"            => "admin@site.com",
  "LANGUAGE_ID"      => "ru",
  "DOC_ROOT"         => "",
  "DOMAINS"          => "www.site.com \n site.com"
  );
$obSite = new CSite;
$obSite->Add($arFields);
if (strlen($obSite->LAST_ERROR)>0) $strError .= $obSite->LAST_ERROR;
?>


Delete

CSite::Delete

mixed
CSite::Delete(
 string id
)

The method Delete deletes a site. The function returns an instance of CDBResult on success, or false otherwise.

Parameters

Parameter | Description
id | The ID of the site to be deleted.

See Also

  • CSite::Add
  • CSite::Update
  • OnBeforeSiteDelete event
  • OnSiteDelete event

Example

<?
if (CSite::Delete("ru")===false)
  echo "The site cannot be deleted as bound records are found.";
?>


GetByID

CSite::GetByID

CDBResult
CSite::GetByID(
 string id
)

The method GetByID returns the site information as an instance of the CDBResult class.

Parameters

Parameter | Description
id | The site ID.

See Also

  • CSite fields
  • CDBResult class
  • CSite::GetList

Example

<?
$rsSites = CSite::GetByID("ru");
$arSite = $rsSites->Fetch();
echo "<pre>"; print_r($arSite); echo "</pre>";
?>


GetDateFormat

CSite::GetDateFormat

string
CSite::GetDateFormat(
  string format_type = "FULL",
  mixed site_id = false
)

The method GetDateFormat returns the site date (time) format.

Parameters

Parameter Description
format_type Format type. The following values are possible:
  • FULL - both date and time;
  • SHORT - date only.
Optional. "FULL" by default.
site_id The site ID.
Optional. The current site ID is used by default.

See Also

  • Date and time handling methods
  • Date and time functions

Example

<?
// displays the current date in the format of the current site
echo date($DB->DateFormatToPHP(CSite::GetDateFormat("SHORT")), time());
?>


GetList

CSite::GetList

CDBResult
CSite::GetList(
 string &by = "sort",
 string &order = "asc",
 array filter = array()
)

The method GetList returns the list of sites as an instance of CDBResult.

Parameters

Parameter Description
by Field by which the sorting is to be performed. The following values are possible:
  • id - by the site ID;
  • active - active state flag;
  • name - site short name;
  • dir - root directory of the site content;
  • lendir - length of the name of the site content root directory;
  • def - flag "Default site";
  • sort - sort weight.
Optional. "Sort" by default.
order Sort order. The following values are possible:
  • asc - ascending
  • desc - descending
Optional. "Asc" by default.
filter An array of the format Array("filtered field"=>"value" [, ...]). "Filtered field" can have the following values:
  • ID - the site ID;
  • NAME - the field "Name" of the site settings;
  • DOMAIN - the field "Domain" of the site settings;
  • IN_DIR - the field "Site folder" prefix of the site settings;
  • LANGUAGE_ID - double character ID of the site language;
  • ACTIVE - active state flag (Y|N)

See Also

  • CSite fields
  • CSite::GetByID
  • CDBResult class

Example

<?
$rsSites = CSite::GetList($by="sort", $order="desc", Array("NAME" => "www.mysite.com"));
while ($arSite = $rsSites->Fetch())
{
  echo "<pre>"; print_r($arSite); echo "</pre>";
}
?>


Update

CSite::Update

bool
CSite::Update(
 int id,
 array fields
)

The method Update changes site parameters. Returns true on success, in case of an error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter | Description
id | The site ID.
fields | An array of the field values in the form of array("field"=>"value" [, ...]).

See Also

  • CSite fields
  • CSite::Add
  • CSite::Delete

Example

<?
$arFields = Array(
  "ACTIVE"           => "Y",
  "SORT"             => 200,
  "DEF"              => "N",
  "NAME"             => "www.site.com",
  "DIR"              => "/en/",
  "FORMAT_DATE"      => "DD.MM.YYYY",
  "FORMAT_DATETIME"  => "DD.MM.YYYY HH:MI:SS",
  "CHARSET"          => "windows-1251",
  "SITE_NAME"        => "My site",
  "SERVER_NAME"      => "www.site.com",
  "EMAIL"            => "admin@site.com",
  "LANGUAGE_ID"      => "ru",
  "DOC_ROOT"         => "",
  "DOMAINS"          => "www.site.com \n site.com"
  );
$obSite = new CSite;
$obSite->Update("ru", $arFields);
if (strlen($obSite->LAST_ERROR)>0) $strError .= $obSite->LAST_ERROR;
?>


CUser

CUser is the class to deal with the user-specific information.

An instance of this class ($USER) is created automatically at run of every page.

Fields

Field | Type | Description
ID | int | User ID.
XML_ID | int | User ID for binding to external sources (e.g. the ID of a user in an external database).
TIMESTAMP_X | datetime | Date and time of the last modification.
LOGIN | varchar (50) | Login name.
PASSWORD | varchar (50) | Password hash.
STORED_HASH | varchar (32) | Password hash stored in the user cookie.
CHECKWORD | varchar (50) | Check string used for the password change.
ACTIVE | char | Flag indicating the user is active (Y|N).
NAME | varchar (50) | First name.
LAST_NAME | varchar (50) | Last name.
EMAIL | varchar (255) | E-mail address.
LAST_LOGIN | datetime | Date of the last authorization.
DATE_REGISTER | datetime | Date the user has been registered.
LID | char (2) | The ID of the default site used for notifications.
ADMIN_NOTES | varchar (2000) | Administrator comments.
EXTERNAL_AUTH_ID | varchar (255) | The ID of the external authorization source.
Personal data
PERSONAL_PROFESSION | varchar (255) | Position/job.
PERSONAL_WWW | varchar (255) | Web page.
PERSONAL_ICQ | varchar (255) | ICQ number.
PERSONAL_GENDER | char (1) | Sex.
PERSONAL_BIRTHDAY | date | Date of birth.
PERSONAL_PHOTO | int | Photo.
PERSONAL_PHONE | varchar (255) | Phone number.
PERSONAL_FAX | varchar (255) | Fax number.
PERSONAL_MOBILE | varchar (255) | Mobile number.
PERSONAL_PAGER | varchar (255) | Pager.
PERSONAL_STREET | varchar (2000) | Street address.
PERSONAL_MAILBOX | varchar (255) | Mailbox number.
PERSONAL_CITY | varchar (255) | City.
PERSONAL_STATE | varchar (255) | State or region.
PERSONAL_ZIP | varchar (255) | Zip code.
PERSONAL_COUNTRY | varchar (255) | Country.
PERSONAL_NOTES | varchar (2000) | Additional notes.
Job information
WORK_COMPANY | varchar (255) | Company name.
WORK_DEPARTMENT | varchar (255) | Web page.
WORK_POSITION | varchar (255) | Department.
WORK_WWW | varchar (255) | Position.
WORK_PHONE | varchar (255) | Phone.
WORK_FAX | varchar (255) | Fax.
WORK_PAGER | varchar (255) | Pager.
WORK_STREET | varchar (2000) | Street address.
WORK_MAILBOX | varchar (255) | Mailbox number.
WORK_CITY | varchar (255) | City.
WORK_STATE | varchar (255) | State or region.
WORK_ZIP | varchar (255) | Zip code.
WORK_COUNTRY | varchar (255) | Country.
WORK_PROFILE | varchar (2000) | Company profile.
WORK_LOGO | int | Company logo.
WORK_NOTES | varchar (2000) | Additional notes.

Class methods

Method | Description
GetList | Returns a list of users.
GetByID | Returns a user by its ID.
GetByLogin | Returns a user by the login.
GetUserGroup | Returns an array of ID's of groups containing the specified user.
Add | Adds a new user.
Update | Modifies parameters of the user.
Delete | Deletes a user.
GetID | Returns the authorized user ID.
GetLogin | Returns the login of the currently authorized user.
GetEmail | Returns the e-mail address of the currently authorized user.
GetFullName | Returns the first and last names of the authorized user.
GetFirstName | Returns the authorized user name.
GetLastName | Returns the last name of the authorized user.
GetParam | Returns one of the user parameters stored in the authorization session.
GetUserGroupArray | Returns the ID's of groups containing the current authorized user.
GetUserGroupString | Returns a string with comma-separated ID's of all groups containing the current authorized user.
IsAdmin | Checks if the current authorized user belongs to the Administrators group.
IsAuthorized | Checks if the site visitor has been authorized.
Login | Verifies the login and password and performs or declines the user authorization.
LoginByHash | Verifies the login and a password hash string performs or declines the user authorization.
SavePasswordHash | Stores the special hash string in the user cookie for future automatic authorization.
GetPasswordHash | Returns a hash string on the user password that can be used with functions LoginByHash and SavePasswordHash.
Authorize | Implements the user authorization procedure. Initialises both session and CUser variables.
Logout | Ends the user authorized session.
Register | Registers and authorizes a new user.
SimpleRegister | Creates a new user by generating the random login and password.
ChangePassword | Modifies the user password.
SendPassword | Sends a message with the control string used for password change.
SendUserInfo | Sends an e-mail message with the user preferences.
GetCount | Returns the number of users registered with the site.


Add

CUser::Add

mixed
CUser::Add(
 array fields
)

The method Add adds a new user. Returns the ID of the added user on success, or false otherwise. In the latter case, the LAST_ERROR property contains the error description.

Parameters

fields Array of field values in the format array("field"=>"value" [, ...]). The field names may include all the CUser class fields as well as GROUP_ID - an array of user group ID's to which the user belongs.

See Also

  • CUser fields
  • CUser::Update
  • CUser::Delete

Example

<?
$user = new CUser;
$arFields = Array(
  "NAME"              => "John",
  "LAST_NAME"         => "Smith",
  "EMAIL"             => "ivanov@microsoft.com",
  "LOGIN"             => "ivan",
  "LID"               => "ru",
  "ACTIVE"            => "Y",
  "GROUP_ID"          => array(1,2),
  "PASSWORD"          => "123456",
  "CONFIRM_PASSWORD"  => "123456",
  );
$ID = $user->Add($arFields);
$strError .= $user->LAST_ERROR;
?>


Authorize

CUser::Authorize

bool
CUser::Authorize(
 int user_id
)

The method Authorize implements the user authorization procedure. Initialises both session and CUser variables. Returns true on successful authorization, or false otherwise.

Parameters

Parameter | Description
user_id | User ID.

See Also

  • CUser::Login
  • CUser::LoginByHash
  • CUser::IsAuthorized
  • OnAfterUserAuthorize event

Example

<?
// add a user to a group
// and re-authorize
global $USER; $arrGroups_new = array(3,4); // groups to add to
$arrGroups_old = $USER->GetUserGroupArray(); // obtain current groups

// join arrays and remove duplicates
$arrGroups = array_unique(array_merge($arrGroups_old,
                                      $arrGroups_new));

// update user profile in the database
$USER->Update($USER->GetID(), array("GROUP_ID" => $arrGroups));
$USER->Authorize($USER->GetID()); // authorize
?>


ChangePassword

CUser::ChangePassword

array
CUser::ChangePassword(
 string login,
 string checkword,
 string new_password,
 string new_password_confirmation,
 string site_id = SITE_ID
)

The method ChangePassword modifies the user password and then calls CUser::SendUserInfo, which in its turn sends the e-mail message using the template USER_INFO. Returns an array containing the result message information. The array returned may be processed by ShowMessage further.

Parameters

Parameter | Description
login | User login.
checkword | Check string used to change the password.
new_password | New password.
new_password_confirmation | Password confirmation. For successful password change, it must be equal to new_password.
site_id | The ID of the site containing the template USER_INFO used to send notification. Optional. The current site is used by default.

See Also

  • CUser::SendPassword
  • CUser::SendUserInfo
  • CUser::Update

Example

<?
global $USER;
$arResult = $USER->ChangePassword("admin", "WRD45GT", "123456", "123456");
if($arResult["TYPE"] == "OK") echo "Password successfully changed.";
else ShowMessage($arResult);
?>


Delete

CUser::Delete

CDBResult
CUser::Delete(
 int id
)

The method Delete deletes a user and returns an instance of the CDBResult class.

Parameters

Parameter | Description
id | The user ID.

See Also

  • CUser::Add
  • CUser::Update
  • OnBeforeUserDelete event
  • OnUserDelete event

Example

<?
if (CUser::Delete(1)) echo "User deleted.";
?>


GetByID

CUser::GetByID

CDBResult
CUser::GetByID(
 int id
)

The method GetByID returns a user by its ID as the CDBResult class instance.

Parameters

Parameter | Description
id | The user ID.

See Also

  • CUser fields
  • CUser::GetList
  • CUser::GetByLogin

Example

<?
$rsUser = CUser::GetByID(23);
$arUser = $rsUser->Fetch();
echo "<pre>"; print_r($arUser); echo "</pre>";
?>


GetByLogin

CUser::GetByLogin

CDBResult
CUser::GetByLogin(
 string login
)

The method GetByLogin returns a user by the login as the CDBResult class instance.

Parameters

Parameter | Description
login | User login.

See Also

  • CUser fields
  • CUser::GetList
  • CUser::GetByID

Example

<?
$rsUser = CUser::GetByLogin("admin");
$arUser = $rsUser->Fetch();
echo "<pre>"; print_r($arUser); echo "</pre>";
?>


GetCount

CUser::GetCount

int
CUser::GetCount()

The method GetCount returns the number of users registered with the site.

Parameters

No parameters.

Example

<?
echo "Registered users: ".CUser::GetCount();
?>


GetEmail

CUser::GetEmail

string
CUser::GetEmail()

The method GetEmail returns the e-mail address of the currently authorized user (usually called from the $USER object).

Parameters

No parameters.

See Also

  • CUser fields
  • CUser::GetID
  • CUser::GetFullName
  • CUser::GetFirstName
  • CUser::GetLastName
  • CUser::GetParam
  • CUser::GetUserGroup
  • CUser::GetUserGroupArray
  • CUser::GetUserGroupString

Example

<?
global $USER;
echo "Your E-Mail: ".$USER->GetEmail();
?>


GetExternalAuthList

CUser::GetExternalAuthList

CDBResult
CUser::GetExternalAuthList();

The method GetExternalAuthList returns a list of all external authorization sources. You can define your own external authorization source by setting the OnExternalAuthList event handler.

Return Values

Returns an instance of CDBResult, each record having two fields: ID - the external source ID and NAME - name of the external source.

See Also

  • External authorization
  • OnExternalAuthList
  • CDBResult class

Example

<?
$rExtAuth = CUser::GetExternalAuthList();
if($arExtAuth = $rExtAuth->GetNext()):
    ?><select name="EXTERNAL_AUTH_ID">
    <option value="">(internal auth)</option>
    <?do{?>
        <option value="<?=$arExtAuth['ID']?>"<?
            if($str_EXTERNAL_AUTH_ID==$arExtAuth['ID']) echo ' selected';
        ?>><?=$arExtAuth['NAME']?></option>
    <?}while($arExtAuth = $rExtAuth->GetNext());?>
    </select>
<?endif?>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetFirstName

CUser::GetFirstName

string
CUser::GetFirstName()

The method GetFirstName returns the authorized user name (usually called from the $USER object).

Parameters

No parameters.

See Also

  • CUser fields
  • CUser::GetID
  • CUser::GetLogin
  • CUser::GetEmail
  • CUser::GetFullName
  • CUser::GetLastName
  • CUser::GetParam
  • CUser::GetUserGroupArray
  • CUser::GetUserGroupString

Example

<?
global $USER;
echo "[".$USER->GetID()."] (".$USER->Login().") ".$USER->GetFirstName()." ".$USER->GetLastName();
?>


GetFullName

CUser::GetFullName

string
CUser::GetFullName()

The method GetFullName returns the first and last names of the authorized user separated with a space (usually called from the $USER object).

Parameters

No parameters.

See Also

  • CUser fields
  • CUser::GetID
  • CUser::GetLogin
  • CUser::GetEmail
  • CUser::GetFirstName
  • CUser::GetLastName
  • CUser::GetParam
  • CUser::GetUserGroupArray
  • CUser::GetUserGroupString

Example

<?
global $USER;
echo "[".$USER->GetID()."] (".$USER->Login().") ".$USER->GetFullName();
?>


GetID

CUser::GetID

int
CUser::GetID()

The method GetID returns the authorized user ID (usually called from the $USER object).

Parameters

No parameters.

See Also

  • CUser fields
  • CUser::GetLogin
  • CUser::GetEmail
  • CUser::GetFullName
  • CUser::GetFirstName
  • CUser::GetLastName
  • CUser::GetParam
  • CUser::GetUserGroupArray
  • CUser::GetUserGroupString

Example

<?
global $USER;
echo "[".$USER->GetID()."] (".$USER->GetLogin().") ".$USER->GetFullName();
?>


GetLastName

CUser::GetLastName

string
CUser::GetLastName()

The method GetLastName returns the last name of the authorized user (usually called from the $USER object).

Parameters

No parameters.

See Also

  • CUser fields
  • CUser::GetID
  • CUser::GetLogin
  • CUser::GetEmail
  • CUser::GetFullName
  • CUser::GetFirstName
  • CUser::GetParam
  • CUser::GetUserGroupArray
  • CUser::GetUserGroupString

Example

<?
global $USER;
echo "[".$USER->GetID()."] (".$USER->Login().") ".$USER->GetFirstName()." ".$USER->GetLastName();
?>


GetList

CUser::GetList

CDBResult
CUser::GetList(
 string &by = "timestamp_x",
 string &order = "desc",
 array filter
)

The method GetList returns a list of users as the CDBResult class instance.

Parameters

Parameter Description
by Reference to the variable with the name of the sorting field. Can have the following values:
  • id - user ID ;
  • active - the user is active;
  • last_login - last authorization date;
  • login - login name;
  • email - e-mail address;
  • name - first name;
  • last_name - last name;
  • timestamp_x - modification date;
  • date_register - registration date;
  • personal_profession - position;
  • personal_www - web page;
  • personal_icq - ICQ number;
  • personal_gender - sex ("M" - male; "F" - female);
  • personal_birthday - date of birth;
  • personal_photo - ID of the photo image;
  • personal_phone - phone number;
  • personal_fax - fax number;
  • personal_mobile - mobile number;
  • personal_pager - pager number;
  • personal_street - street;
  • personal_mailbox - mailbox;
  • personal_city - city;
  • personal_state - state or region;
  • personal_zip - zip code;
  • personal_country - country code;
  • personal_notes - additional comments ;
  • work_company - company name;
  • work_department - department;
  • work_position - position/job;
  • work_www - company web site;
  • work_phone - work phone;
  • work_fax - work fax;
  • work_pager - pager number;
  • work_street - company street;
  • work_mailbox - company mailbox;
  • work_city - company city;
  • work_state - company state or region;
  • work_zip - company zip code;
  • work_country - company country code;
  • work_profile - company profile;
  • work_notes - additional company comments;
  • admin_notes - administrator comments.
order Reference to the variable containing the sort order; can have the following values:
  • asc - ascending;
  • desc - descending.
filter An array used by the method to filter users. The following entry names are possible:
  • 1ID - by user ID;
  • TIMESTAMP_1 - lower bound of the modification date range ("from");
  • TIMESTAMP_2 - upper bound of the modification date range ("till");
  • LAST_LOGIN_1 - lower bound of the last login date range ("from");
  • LAST_LOGIN_2 - upper bound of the last login date range ("till");
  • ACTIVE - active state flag (Y|N);
  • 1LOGIN_EQUAL - login (strict match);
  • 1LOGIN - login (loose match - substring);
  • 1NAME - first and last names;
  • 1EMAIL - e-mail address;
  • 1COUNTRY_ID - country ID;
  • GROUPS_ID - by groups (array of user group ID's);
  • PERSONAL_BIRTHDAY_1 - lower bound of the birth date range ("from");
  • PERSONAL_BIRTHDAY_1 - upper bound of the birth date range ("till");
  • 1KEYWORDS - by the following fields (marked with *);
  • 1* PERSONAL_PROFESSION - position;
  • 1* PERSONAL_WWW - web site;
  • 1* PERSONAL_ICQ - ICQ number;
  • 1* PERSONAL_GENDER - sex ("M" - male; "F" - female);
  • 1* PERSONAL_PHOTO - ID of the photo image (table b_file);
  • 1* PERSONAL_PHONE - phone number;
  • 1* PERSONAL_FAX - fax number;
  • 1* PERSONAL_MOBILE - mobile number;
  • 1* PERSONAL_PAGER - pager;
  • 1* PERSONAL_STREET - street;
  • 1* PERSONAL_MAILBOX - mailbox;
  • 1* PERSONAL_CITY - city;
  • 1* PERSONAL_STATE - state or region;
  • 1* PERSONAL_ZIP - zip code;
  • 1* PERSONAL_COUNTRY - country code (stored in files \bitrix\modules\main\lang/en\tools.php, \bitrix\modules\main\lang\en\tools.php);
  • 1* PERSONAL_NOTES - additional notes;
  • 1* WORK_COMPANY - company name;
  • 1* WORK_DEPARTMENT - department;
  • 1* WORK_POSITION - position;
  • 1* WORK_WWW - company web site;
  • 1* WORK_PHONE - work phone;
  • 1* WORK_FAX - work fax;
  • 1* WORK_PAGER - work pager;
  • 1* WORK_STREET - company street;
  • 1* WORK_MAILBOX - company mailbox;
  • 1* WORK_CITY - company city;
  • 1* WORK_STATE - company state or region;
  • 1* WORK_ZIP - company zip code;
  • 1* WORK_COUNTRY - company country code (stored in files \bitrix\modules\main\lang/en\tools.php, \bitrix\modules\main\lang\en\tools.php);
  • 1* WORK_PROFILE - company profile;
  • 1* WORK_NOTES - additional comments on company;
  • 1* ADMIN_NOTES - administrator comments (available for viewing and editing for the site administrator only).
1 - allows complex logic
* - search by "KEYWORDS" is in fact search by fields marked with "*".

See Also

  • CUser fields
  • CUser::GetByID
  • CUser::GetByLogin

Example

<?
$filter = Array
(
    "ID"                  => "1 | 2",
    // in the format of the current site
    "TIMESTAMP_1"         => "04.02.2004",
    "TIMESTAMP_2"         => "04.02.2005",
    "LAST_LOGIN_1"        => "01.02.2004",
    "ACTIVE"              => "Y",
    "LOGIN"               => "nessy | admin",
    "NAME                 => "John & Smith",
    "EMAIL"               => "nessy@bitrix.com | admin@bitrix.com",
    "KEYWORDS"            => "www.bitrix.com",
    "PERSONAL_PROFESSION" => "system engineer",
    "PERSONAL_GENDER"     => "M",
    "PERSONAL_COUNTRY"    => "4 | 1", // Belorussia or Russia
    "ADMIN_NOTES"         => "\"UID = 145\"",
    "GROUPS_ID"           => Array(1,4,10)
);
$rsUsers = CUser::GetList(($by="personal_country"),
                          ($order="desc"),
                          $filter); // select users
$is_filtered = $rsUsers->is_filtered; // selection filtered ?
$rsUsers->NavStart(50); // paginate by 50 records

// display paginated output
echo $rsUsers->NavPrint(GetMessage("PAGES"));
while($rsUsers->NavNext(true, "f_")) :
    echo "[".$f_ID."] (".$f_LOGIN.") ".$f_NAME." ".$f_LAST_NAME."<br>";
endwhile;
?>


GetLogin

CUser::GetLogin

string
CUser::GetLogin()

The method GetLogin returns the login of the currently authorized user (usually called from the $USER object).

Parameters

No parameters.

See Also

  • CUser fields
  • CUser::GetID
  • CUser::GetEmail
  • CUser::GetFullName
  • CUser::GetFirstName
  • CUser::GetLastName
  • CUser::GetParam
  • CUser::GetUserGroupArray
  • CUser::GetUserGroupString

Example

<?
global $USER;
echo "[".$USER->GetID()."] (".$USER->GetLogin().") ".$USER->GetFullName();
?>


GetParam

CUser::GetParam

mixed
CUser::GetParam(
 string param_name
)

The method GetParam returns one of the user parameters stored in the authorization session (usually called from the $USER object).

Parameters

Parameter Description
param_name Parameter name. The following values are possible:
  • AUTHORIZED - returns "Y" if the user is authorized;
  • USER_ID - user ID;
  • LOGIN - login;
  • EMAIL - e-mail;
  • NAME - full name;
  • GROUPS - array of groups to which the user belongs;
  • ADMIN - returns true if the user is in the Administrators group;
  • PASSWORD_HASH - user password hash (md5);
  • FIRST_NAME - user first name;
  • LAST_NAME - user last name.

See Also

  • CUser fields
  • CUser::IsAdmin
  • CUser::IsAuthorized
  • CUser::GetID
  • CUser::GetLogin
  • CUser::GetEmail
  • CUser::GetFullName
  • CUser::GetFirstName
  • CUser::GetLastName
  • CUser::GetUserGroupArray
  • CUser::GetUserGroupString

Example

<?
global $USER;
echo "E-Mail: ".$USER->GetParam("EMAIL");
?>


GetPasswordHash

CUser::GetPasswordHash

string
CUser::GetPasswordHash(
 string password_md5
)

The method GetPasswordHash returns a hash string on the user password that can be used with functions LoginByHash and SavePasswordHash.

Parameters

Parameter | Description
password_md5 | Hash (MD5) on the real password of a user. You can obtain the MD5 hash on the current user password by calling $USER->GetParam("PASSWORD_HASH"). For an arbitrary user, the MD5 hash can be obtained by calling the method CUser::GetByID (field "PASSWORD").

See Also

  • CUser::LoginByHash
  • CUser::SavePasswordHash

Example

<?
function SetCurrentUserAuthCookie()
{
  global $USER;
  $hash = CUser::GetPasswordHash($USER->GetParam("PASSWORD_HASH"));
  $name = COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_UIDH";
  @setcookie($name, $hash, time()+60*60*24*30*60, "/");
}
?>


GetUserGroup

CUser::GetUserGroup

array
CUser::GetUserGroup(
 int id
)

The method GetUserGroup returns an array of ID's of groups containing the user with the id.

Parameters

Parameter | Description
id | User ID.

See Also

  • CGroup class
  • CUser::GetUserGroupArray
  • CUser::GetUserGroupString

Example

<?
// obtain array of groups for user with ID=12
$arGroups = CUser::GetUserGroup(12);
echo "<pre>"; print_r($arGroups); echo "</pre>";
?>


GetUserGroupArray

CUser::GetUserGroupArray

array
CUser::GetUserGroupArray()

The method GetUserGroupArray returns the ID's of groups containing the current authorized user (usually called from the $USER object).

Parameters

No parameters.

See Also

  • CGroup class
  • CUser::GetUserGroupString
  • CUser::GetUserGroup

Example

<?
// obtain an array of groups for current user
global $USER;
$arGroups = $USER->GetUserGroupArray();
echo "<pre>"; print_r($arGroups); echo "</pre>";
?>


GetUserGroupString

CUser::GetUserGroupString

string
CUser::GetUserGroupString()

The method GetUserGroupString returns a string with comma-separated ID's of all groups containing the current authorized user (usually called from the $USER object).

Parameters

No parameters.

See Also

  • CGroup class
  • CUser::GetUserGroupArray
  • CUser::GetUserGroup

Example

<?
// obtain an array of groups for current user
global $USER;
$strGroups = $USER->GetUserGroupString();
echo $strGroups; // "1,2,3"
?>


IsAdmin

CUser::IsAdmin

bool
CUser::IsAdmin()

The method IsAdmin checks if the current authorized user belongs to the Administrators group (usually called from the $USER object). Returns true if the user is of the Administrators group, or false otherwise.

Parameters

No parameters.

See Also

  • CUser::IsAuthorized
  • CUser::GetParam

Example

<?
global $USER;
if ($USER->IsAdmin()) echo "You are the Administrator!";
?>


IsAuthorized

CUser::IsAuthorized

bool
CUser::IsAuthorized()

The method IsAuthorized checks if the site visitor has been authorized (usually called from the $USER object). Returns true if the user is authorized, or false otherwise.

Parameters

No parameters.

See Also

  • CUser::Authorize
  • CUser::Login
  • CUser::LoginByHash
  • CUser::IsAdmin

Example

<?
global $USER;
if ($USER->IsAuthorized()) echo "You are authorized!";
?>


Login

CUser::Login

mixed
CUser::Login(
 string login,
 string password,
 string set_auth_cookie = "N",
 string convert_password_to_md5 = "Y"
)

The method Login verifies the login and password and performs or declines the user authorization depending on the verification result. Returns true on successful authorization. In case the authorization failed (login and/or password are incorrect), the method returns the error description array that can be passed to ShowMessage.

Parameters

Parameter | Description
login | User login.
password | User password. If the parameter convert_password_to_md5 is "Y", this parameter must contain the original password string. Otherwise, it must contain the MD5 hash on the original password.
set_auth_cookie | If "Y", the authorization is to be stored in cookie (the visitor will be authorized automatically next time); otherwise, the authorization is not preserved. The information stored in cookie is a special hash obtained by a call to method CUser::GetPasswordHash. The system automatically authorizes the visitor next time by using the method CUser::LoginByHash. Optional; "N" by default.
convert_password_to_md5 | A value of "Y" means that the password contains a real password as typed by a visitor (not converted to MD5). If "N", the password has been previously converted to MD5. You can obtain the MD5 for the current authorized user by calling $USER->GetParam("PASSWORD_HASH"). To get the MD5 for an arbitrary user, call CUser::GetByID (field "PASSWORD"). Optional; "Y" by default.

See Also

  • CUser::Authorize
  • CUser::IsAuthorized
  • CUser::LoginByHash
  • CUser::Logout
  • OnBeforeUserLogin event
  • OnAfterUserLogin event

Example

<?
global $USER;
if (!is_object($USER)) $USER = new CUser;
$arAuthResult = $USER->Login("admin", "123456", "Y");
$APPLICATION->arAuthResult = $arAuthResult;
?>
<?
global $USER;
if (!is_object($USER)) $USER = new CUser;
$arAuthResult = $USER->Login("admin", md5("123456"), "Y", "N");
$APPLICATION->arAuthResult = $arAuthResult;
?>


LoginByHash

CUser::LoginByHash

mixed
CUser::LoginByHash(
 string login,
 string cookie_hash
)

The method LoginByHash verifies the login and a password hash string that CUser::GetPasswordHash and performs or declines the user authorization depending on the verification result. Returns true on successful authorization. In case the authorization failed, the method returns the error description array that can be passed to ShowMessage.

Parameters

Parameter | Description
login | User login.
cookie_hash | Special password hash string obtained by a call to CUser::GetPasswordHash. This hash string is stored in the user cookie.

See Also

  • CUser::SavePasswordHash
  • CUser::GetPasswordHash
  • OnBeforeUserLoginByHash event
  • OnAfterUserLoginByHash event

Example

<?
global $USER;
if (!is_object($USER)) $USER = new CUser;
$cookie_login = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_LOGIN"};
$cookie_md5pass = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_UIDH"};
$USER->LoginByHash($cookie_login, $cookie_md5pass);
?>


Logout

CUser::Logout

CUser::Logout()

The method Logout ends the user authorized session and erases user cookie used for automatic authorization.

Parameters

No parameters.

See Also

  • CUser::Login
  • CUser::Authorize
  • OnBeforeUserLoginByHash event
  • OnAfterUserLoginByHash event

Example

<?
$USER->Logout();
?>


Register

CUser::Register

array
CUser::Register(
 string login,
 string first_name,
 string last_name,
 string password,
 string password_confirmation,
 string email,
 string site_id = SITE_ID
)

The method Register registers and authorizes a new user and sends a message using the template NEW_USER. Returns an array with the report on processing which can be passed to ShowMessage.

Note!
The method can only be used in the public section of the site!

Parameters

Parameter | Description
login | Login of a new user (at least 3 symbols).
first_name | First name of a new user (can be empty).
last_name | Last name of a new user (can be empty).
password | Password (at least 3 symbols).
password_confirmation | Password confirmation (must be equal to password for the registration to succeed).
email | E-mail of a new user (at least 3 symbols). E-mail is the subject of verification by the function check_email.
site_id | ID of the site whose e-mail template is to be used for the notification dispatch (NEW_USER, USER_INFO etc.). Optional. The current site is used by default.

See Also

  • CUser::SimpleRegister
  • CUser::Login
  • CUser::Add
  • CUser::Authorize
  • OnBeforeUserLoginByHash event
  • OnAfterUserLoginByHash event

Example

<?
global $USER;
$arResult = $USER->Register("admin", "", "", "123456", "123456", "admin@mysite.com");
ShowMessage($arResult); // display result as a message
echo $USER->GetID(); // ID of a new user
?>


SavePasswordHash

CUser::SavePasswordHash

CUser::SavePasswordHash()

The method SavePasswordHash stores the special hash string in the user cookie for future automatic authorization. Different sites built on the Bitrix Site Manager always store unique hash value for the same password. This allows to avoid password hash collisions for different sites.

Parameters

No parameters.

See Also

  • CUser::LoginByHash
  • CUser::GetPasswordHash

Example

<?
global $USER;
if ($USER->IsAuthorized()) $USER->SavePasswordHash();
?>


SendPassword

CUser::SendPassword

array
CUser::SendPassword(
 string login,
 string email,
 string site_id = SITE_ID
)

The method SendPassword sends a message with the control string used for password change. The message is sent using the template USER_INFO. The user can be identified by either login or e-mail address.

The method returns an array containing the execution report message which can be passed to ShowMessage.

Parameters

Parameter | Description
login | User login.
email | User e-mail address.
site_id | The site ID whose e-mail template USER_INFO is to be used. Optional. The current site is used by default.

See Also

  • CUser::SendUserInfo
  • CUser::ChangePassword

Example

<?
global $USER;
$arResult = $USER->SendPassword($USER->GetLogin(),
                                $USER->GetParam("EMAIL"));
if ($arResult["TYPE"] == "OK")
    echo "Control string for the password change has been sent.";
else
    echo "The login (or e-mail) cannot be found.";
?>


SendUserInfo

CUser::SendUserInfo

CUser::SendUserInfo(
 int user_id,
 string site_id,
 string message
)

The method SendUserInfo sends an e-mail message with the user preferences using the template USER_INFO.

Parameters

Parameter | Description
user_id | User ID.
site_id | he site ID whose e-mail template is to be used.
message | Message text (#MESSAGE#).

See Also

  • SendPassword

Example

<?
$USER_ID = 1;
// send message to a user with ID=1,
// using current site template
CUser::SendUserInfo($USER_ID,
                    SITE_ID,
                    "You have successfully registered!");
?>


SetParam

CUser::SetParam

CUser::SetParam(
 string param_name,
 mixed param_value
)

The method SetParam sets the value of the user-defined parameter param_name to be stored in the authorization session (usually called on the $USER object). You can get the parameter value later by calling CUser::GetParam.

Parameters

Parameter | Description
param_name | Parameter name.
param_value | Parameter value.

See Also

  • CUser::GetParam

Example

<?
global $USER;
$USER->SetParam("IP_LOGIN", $_SERVER['REMOTE_ADDR']);
?>


SetUserGroup

CUser::SetUserGroup

CUser::SetUserGroup(
   int user_id,
   array groups
);

The method SetUserGroup assigns a user to a number of groups. The assignment is stored in the database but does not affect the already authorized user state.

Parameters

Parameter | Description
user_id | User ID.
groups | Array containing the ID's of the user groups.

See Also

  • CUser::GetUserGroup

Example

<?
// assign a user ID=10 to a group with ID=5
$arGroups = CUser::GetUserGroup(10);
$arGroups[] = 5;
CUser::SetUserGroup(10, $arGroups);
?>


SetUserGroupArray

CUser::SetUserGroupArray

CUser::SetUserGroupArray(
   array groups
);

The method SetUserGroupArray assigns a user to a number of groups (usually called on the $USER object). The assignment is not stored in the database and will not be restored upon further authorizations. To store the assignment in the database, use the method CUser::SetUserGroup.

Parameters

Parameter | Description
groups | Array containing the ID's of the user groups.

See Also

  • CUser::GetUserGroupArray

Example

<?
// assign the current user to a group with ID=5
global $USER;
$arGroups = $USER->GetUserGroupArray();
$arGroups[] = 5;
$USER->SetUserGroupArray($arGroups);
?>


SimpleRegister

CUser::SimpleRegister

array
CUser::SimpleRegister(
 string email,
 string site_id = SITE_ID
)

The method SimpleRegister creates a new user by generating the random login and password. The method returns an array containing the execution report message which can be passed to ShowMessage.

Note!
This method can only be used in the public section of the site!

Parameters

Parameter | Description
email | E-mail of a new user (at least 3 symbols). E-mail is the subject of verification by the function check_email.
site_id | ID of the site whose e-mail template is to be used for the notification dispatch (NEW_USER, USER_INFO etc.). Optional. The current site is used by default.

See Also

  • CUser::Register
  • CUser::Login
  • CUser::Add
  • CUser::Authorize
  • OnBeforeUserLoginByHash event
  • OnAfterUserLoginByHash event

Example

<?
global $USER;
$arResult = $USER->SimpleRegister("admin@mysite.com");
ShowMessage($arResult); // display result as a message
echo $USER->GetID(); // ID of a new user
?>


Update

CUser::Update

bool
CUser::Update(
 int id,
 array fields
)

The method Update modifies parameters of the user. Returns true on success. In case of an error the method will return false, and the LAST_ERROR property will contain the error description.

Parameters

Parameter | Description
id | User ID.
fields | An array of values in the format array("field"=>"value" [, ...]). The field names may include all the CUser class fields as well as GROUP_ID - an array of user group ID's to which the user belongs.

See Also

  • CUser fields
  • CUser::Add
  • CUser::Delete

Example

<?
$user = new CUser;
$fields = Array(
  "NAME"              => "Duncan",
  "LAST_NAME"         => "McCleod",
  "EMAIL"             => "dc@eternity.com",
  "LOGIN"             => "duncan",
  "LID"               => "en",
  "ACTIVE"            => "Y",
  "GROUP_ID"          => array(1,2),
  "PASSWORD"          => "123456",
  "CONFIRM_PASSWORD"  => "123456",
  );
$user->Update($ID, $fields);
$strError .= $user->LAST_ERROR;
?>


Events

This section outlines the Kernel module events. To register an event handler, pass "main" as the module identifier.

  • Page execution events
  • User and authorization events
  • User group events
  • Files and permissions events
  • e-mail templates events
  • Sites events
  • Language events
  • Control toolbar events
    •

    See Also

    • Event handlers
    • Module interrelationship

    Page execution events

    Event | Description
OnPageStart | Fires at the start of the executable section of the site prologue after the inclusion of all libraries and running all agents.
OnBeforeProlog | Fires in the executable section of a site prologue (after OnPageStart).
OnEpilog | Fires at the end of processing the visual aspect of the site epilogue.
OnProlog | Fires at the beginning of processing the visual aspect of the site prologue.
OnAfterEpilog | Fires at the end of the executable section of a site epilogue (after OnEpilog).

    See Also

    • Page execution stages

    User and authorization events

    Event | Description
OnBeforeUserRegister | Fires before an attempt of a new user registration by calling the method CUser::Register.
OnAfterUserRegister | Fires after an attempt of a new user registration by calling the method CUser::Register.
OnBeforeUserSimpleRegister | Fires before an attempt of user simplified registration performed by CUser::SimpleRegister.
OnAfterUserSimpleRegister | Fires after an attempt of user simplified registration performed by CUser::SimpleRegister.
OnBeforeUserLogin | Fired in the method CUser::Login before a user authorization attempt.
OnUserLoginExternal | Used to check user login and password in an external authorization source.
OnAfterUserLogin | Called from the method CUser::Login after a user authorization attempt.
OnBeforeUserLoginByHash | Fires in the method CUser::LoginByHash() before the authorization attempt.
OnAfterUserLoginByHash | Called from the method CUser::LoginByHash() after the verification of login, after the authorization attempt.
OnAfterUserAuthorize | Called from the CUser::Authorize method after a user authorization.
OnBeforeUserLogout | Fires before the user authorization completes from within the method CUser::Logout.
OnAfterUserLogout | Fires after the user authorization completes.
OnBeforeUserAdd | Fires before a new user is added.
OnAfterUserAdd | Fires after a new user is added.
OnBeforeUserUpdate | Fires before the user parameters become modified.
OnAfterUserUpdate | Fires after the user parameters become modified.
OnBeforeUserDelete | Fires before a user is deleted.
OnUserDelete | Fires at the time of a user deletion.
OnExternalAuthList | Called to obtain a list of external authorization sources .

    See Also

    • External authorization

    User group events

    Event | Description
OnBeforeGroupDelete | Fires before the user group deletion.
OnGroupDelete | Fired when a user group is deleted.

    Files and permissions events

    Event | Description
OnChangeFile | Fired right after a file is saved by a call to method SaveFileContent.
OnChangePermissions | Fires when the file or folder access permission is modified by a call to SetFileAccessPermission.

    e-mail templates events

    Event | Description
OnBeforeEventMessageDelete | Fires before the mail template is deleted.
OnEventMessageDelete | Fires at the time of deleting a mail template.

    Sites events

    Event | Description
OnBeforeSiteDelete | Fires before the site is deleted.
OnSiteDelete | Fires when a site is deleted.

    Language events

    Event | Description
OnBeforeLanguageDelete | Fires before the language deletion.
OnLanguageDelete | Fires when a language is deleted.

    Control toolbar events

    Event | Description
OnPanelCreate | Called when the system collects information for building the control toolbar in the public section of the site.

    See Also

    • Event handlers
    • Module interrelationships


OnAfterEpilog event

event_handler();

The OnAfterEpilog event fires at the end of the executable section of a site epilogue (after OnEpilog).

Parameters

No parameters.

See Also

  • OnEpilog event
  • Page execution stages. Variables and constants available at each stage
  • Event handlers

Example

<?
RegisterModuleDependences("main",
                          "OnAfterEpilog",
                          "compression",
                          "CCompress",
                          "OnAfterEpilog");
?>


OnAfterUserAuthorize event

event_handler(
 array user_fields
)
The event handler is called from the CUser::Authorize method after a user authorization. The handler receives an array of all user fields in the user_fields parameter.

Parameters

Parameter | Description
user_fields | Array of user fields.

See Also

  • CUser::Authorize
  • Event handlers
  • External authorization

Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main",
                "OnAfterUserAuthorize",
                Array("MyClass",
                      "OnAfterUserAuthorizeHandler"));

class MyClass
{
    // create the OnAfterUserAuthorize handler
    function OnAfterUserAuthorizeHandler($arUser)
    {
        // perform actions on the authorized user

    }
}
?>


OnAfterUserLogin event

event_handler(
 array &arParams
);

The OnAfterUserLogin event is called from the method CUser::Login after a user authorization attempt (after the login arParams['LOGIN'] and password arParams['PASSWORD'] are both verified).

Parameters

Parameter Description
arParams Array of fields used for user login and password verification, the following keys available:
  • USER_ID - contains a valid user ID on successful authorization;
  • RESULT_MESSAGE - array containing the verification result description (can be passed to ShowMessage to display a message);
  • LOGIN - user login;
  • PASSWORD - user password. If the value of PASSWORD_ORIGINAL is "Y", this parameter contains the original password. Otherwise, this parameter contains the MD5 hash value of the original password.
  • REMEMBER - if "Y", the user authorization information is to be stored in cookie.
  • PASSWORD_ORIGINAL - if "Y", the value of the PASSWORD field contains the original password typed by a user (not converted to MD5). If "N", the value of the PASSWORD field is converted to MD5.

Note
All parameters passed to this handler function are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

For example, this allows to modify the RESULT_MESSAGE, which will change message returned by the method CUser::Login.

See Also

  • OnBeforeUserLogin event
  • CUser::Login
  • Event handlers
  • External authorization

Example

<?
AddEventHandler("main", "OnAfterUserLogin", Array("MyClass", "OnAfterUserLoginHandler"));

class MyClass
{
    // create the OnAfterUserLogin handler
    function OnAfterUserLoginHandler(&$fields)
    {
        // if the login failed...
        if($fields['USER_ID']<=0)
        {
            // increment the login failure counter
            $_SESSION["AUTHORIZE_FAILURE_COUNTER"]++;

            // if the number of unsuccessful login attempts exceeds 10...
            if ($_SESSION["AUTHORIZE_FAILURE_COUNTER"]>10)
            {
                // lookup a user by login
                $rsUser = CUser::GetByLogin($fields['LOGIN']);
                // if found...
                if ($arUser = $rsUser->Fetch())
                {
                    // lock the user profile
                    $user = new CUser;
                    $user->Update($arUser["ID"],array("ACTIVE" => "N"));

                    // assign message
                    $fields['RESULT_MESSAGE'] = array("TYPE" => "ERROR", "MESSAGE" => "Your account is disabled.");
                }
            }
        }
    }
}
?>


OnAfterUserLoginByHash event

event_handler(
 array &arParams
);

The OnAfterUserLoginByHash event is called from the method CUser::LoginByHash() after the verification of login arParams['LOGIN'] and a password hash arParams['HASH'], after the authorization attempt.

The field arParams['USER_ID'] contains the ID of a successfully authorized user. The array arParams['RESULT_MESSAGE']. contains the error description.

Parameters

Parameter Description
arParams Array of fields used for user login and password verification, the following keys available:
  • USER_ID - contains a valid user ID on successful authorization;
  • RESULT_MESSAGE - array containing the verification result description (can be passed to ShowMessage to display a message);
  • LOGIN - user login;
  • HASH - special hash calculated on password string. This value is usually stored in a user cookie.

Note
All parameters passed to this handler function are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

For example, this allows to modify the RESULT_MESSAGE, which will change message returned by the method CUser::Login.

See Also

  • OnBeforeUserLoginByHash event
  • CUser::LoginByHash
  • Event handlers
  • External authorization

Example

// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main",
                "OnAfterUserLoginByHash",
                Array("MyClass",
                      "OnAfterUserLoginByHashHandler"));

class MyClass
{
    // create OnAfterUserLoginByHash handler
    function OnAfterUserLoginByHashHandler(&$arParams)
    {
        if ($arParams['USER_ID']<=0)
        {
            // redefine the error message.
            $arParams['RESULT_MESSAGE'] =
                Array("MESSAGE" => "New error.",
                      "TYPE" => "ERROR");
        }
    }
}
?>


OnAfterUserLogout event

event_handler(
 array &arParams
);

The OnAfterUserLogout event fires after the user authorization completes.

Parameters

Parameter Description
arParams Array of parameters:
  • ID - user ID;
  • SUCCESS - operation result. If true, the authorization completed successfully. If false, an error occurred or the authorization has been canceled from the OnBeforeUserLogout handler.

See Also

  • OnBeforeUserLogout event
  • CUser::Logout
  • Event handlers

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create the OnAfterUserLogout handler
    function OnAfterUserLogoutHandler($arParams)
    {
        // perform actions related to authorization
        ...
    }
}
?>

Example of handler registration

<?
// register handler OnAfterUserLogout
RegisterModuleDependences("main", "OnAfterUserLogout",
                          "my_module_id", "MyClass",
                          "OnAfterUserLogoutHandler");
?>


OnAfterUserRegister event

event_handler(
 array &arFields
);

The OnAfterUserRegister event fires after an attempt of a new user registration by calling the method CUser::Register.

Parameters

Parameter Description
arFields Array of new user registration fields:
  • USER_ID - if the registration succeeds, contains the user ID;
  • RESULT_MESSAGE - array containing the verification result description (can be passed to ShowMessage to display a message);
  • LOGIN - user login;
  • NAME - user first name;
  • LAST_NAME - user last name;
  • PASSWORD - password;
  • CONFIRM_PASSWORD - password confirmation;
  • CHECKWORD - new check word for password change;
  • EMAIL - user e-mail;
  • ACTIVE - active state flag [Y|N];
  • SITE_ID - the ID of default site used for notifications;
  • GROUP_ID - array of user group ID's;
  • USER_IP - user IP address;
  • USER_HOST - user host name.

Note
All parameters passed to this handler function are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

For example, this allows to modify the RESULT_MESSAGE, which will change message returned by the method CUser::Login.

See Also

  • OnBeforeUserRegister event
  • Event handlers
  • CUser::Register

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // OnAfterUserRegister handler
    function OnAfterUserRegisterHandler(&$arFields)
    {
        // if auth succeeds...
        if($arFields["USER_ID"]>0)
        {
            // if the current site is r1...
            if(SITE_ID=="r1")
            {
                // set the message which confirms
                // the registration within site r1
                $arFields["RESULT_MESSAGE"]["MESSAGE"] =
                "You have successfully registered "
                "with site \"My site 1\"";
            }
            elseif(SITE_ID=="r2")
            {
                // set the message which confirms
                // the registration within site r1
                $arFields["RESULT_MESSAGE"]["MESSAGE"] =
                "You have successfully registered "
                "with site \"My site 2\"";
            }
        }
    }
}
?>

Example of handler registration

<?
// register the OnAfterUserRegister handler
RegisterModuleDependences("main",
                          "OnAfterUserRegister",
                          "my_module_id",
                          "MyClass",
                          "OnAfterUserRegisterHandler");
?>


OnAfterUserSimpleRegister event

event_handler(
 array &arFields,
);

The OnAfterUserSimpleRegister event fires after a attempt of user simplified registration performed by CUser::SimpleRegister.

Parameters

Parameter Description
arFields Array of user registration fields:
  • USER_ID - if the registration succeeds, contains the user ID;
  • RESULT_MESSAGE - array containing the verification result description (can be passed to ShowMessage to display a message);
  • PASSWORD - password;
  • CONFIRM_PASSWORD - password confirmation;
  • CHECKWORD - new check word for password change;
  • EMAIL - user e-mail;
  • ACTIVE - active state flag [Y|N]
  • SITE_ID - the ID of default site used for notifications;
  • GROUP_ID - array of user group ID's;
  • USER_IP - user IP address;
  • USER_HOST - user host name.

Note
All parameters passed to this handler function are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

For example, this allows to modify the RESULT_MESSAGE, which will change message returned by the method CUser::Login.

See Also

  • OnBeforeUserSimpleRegister event
  • Event handlers
  • CUser::Register

Example of handler registration

<?
// register handler OnAfterUserSimpleRegister
RegisterModuleDependences("main",
                          "OnAfterUserSimpleRegister",
                          "my_module_id",
                          "MyClass",
                          "OnAfterUserSimpleRegisterHandler");
?>

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnAfterUserSimpleRegister"
    function OnAfterUserSimpleRegisterHandler(&$fields)
    {
        // if the registration succeeds...
        if($fields["USER_ID"]>0)
        {
            // set the registration confirmation message
            $fields["RESULT_MESSAGE"]["MESSAGE"] =
            "Registration successful."
            "Your login: ".$fields["LOGIN"];
        }
    }
}
?>


OnBeforeEventMessageDelete

bool
event_handler(
 int template_id
);

The OnBeforeEventMessageDelete event fires before the mail template is deleted. A common use of this module is to allow or disallow the template deletion.

Parameters

Parameter | Description
template_id | The ID of the template which is to be deleted.

Return Values

To cancel the template deletion and terminate the CEventMessage::Delete method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnEventMessageDelete event
  • CEventMessage::Delete
  • Event handlers

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnBeforeEventMessageDelete"
    function OnBeforeEventMessageDeleteHandler($template_id)
    {
        // check if any records exist bound to the deleted template
        $strSql = "SELECT * FROM my_table WHERE EMAIL_TEMPLATE_ID=".intval($template_id);
        $rs = $DB->Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);

        // if found...
        if ($ar = $rs->Fetch())
        {
            // cancel deletion.
            global $APPLICATION;
            $APPLICATION->throwException("My table has bound records.");
            return false;
        }
    }
}
?>

Example of handler registration

<?
// register handler "OnBeforeEventMessageDelete"
RegisterModuleDependences("main",
                          "OnBeforeEventMessageDelete",
                          "my_module_id",
                          "MyClass",
                          "OnBeforeEventMessageDeleteHandler");
?>


OnBeforeGroupDelete

bool
event_handler(
 int group_id
);

The OnBeforeGroupDelete event fires before the user group deletion. A common use of this module is to allow or disallow the user group deletion.

Parameters

Parameter | Description
group_id | The ID of the user group which is to be deleted.

Return Values

To cancel the user deletion and terminate the CGroup::Delete method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnGroupDelete event
  • CGroup::Delete
  • Event handlers

Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main",
                "OnBeforeGroupDelete",
                Array("MyClass",
                      "OnBeforeGroupDeleteHandler"));

class MyClass
{
    // create handler "OnBeforeGroupDelete"
    function OnBeforeGroupDeleteHandler($group_id)
    {
        // check if any records exist bound to the deleted group
        $strSql = "SELECT * FROM my_table WHERE GROUP_ID=".intval($group_id);
        $rs = $DB->Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);

        // if found...
        if ($ar = $rs->Fetch())
        {
            // cancel deletion.
            global $APPLICATION;
            $APPLICATION->throwException("My table has bound records.");
            return false;
        }
    }
}
?>

Example of handler registration

<?
// register handler "OnBeforeGroupDelete" for module my_module_id
RegisterModuleDependences("main",
                          "OnBeforeGroupDelete",
                          "my_module_id",
                          "MyClass",
                          "OnBeforeGroupDeleteHandler");
?>


OnBeforeLanguageDelete

bool
event_handler(
 string language_id
);

The OnBeforeLanguageDelete event fires before the language deletion. A common use of this module is to allow or disallow the language deletion.

Parameters

Parameter | Description
language_id | The ID of the language which is to be deleted.

Return Values

To cancel the language deletion and terminate the CLanguage::Delete method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnLanguageDelete event
  • CLanguage::Delete
  • Event handlers

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnBeforeLanguageDelete"
    function OnBeforeLanguageDeleteHandler($language_id)
    {
        // check if any records exist bound to the deleted language
        $strSql = "SELECT * FROM my_table WHERE LANGUAGE_ID=".$DB->ForSql($language_id);
        $rs = $DB->Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);

        // if found...
        if ($ar = $rs->Fetch())
        {
            // cancel deletion.
            global $APPLICATION;
            $APPLICATION->throwException("My table has bound records.");
            return false;
        }
    }
}
?>

Example of handler registration

<?
// register handler "OnBeforeLanguageDelete"
RegisterModuleDependences("main",
                          "OnBeforeLanguageDelete",
                          "my_module_id",
                          "MyClass",
                          "OnBeforeLanguageDeleteHandler");
?>


OnBeforeProlog event

event_handler();

The OnBeforeProlog event fires in the executable section of a site prologue (after OnPageStart).

Parameters

No parameters.

See Also

  • OnPageStart event
  • Page execution stages. Variables and constants available at each stage
  • Event handlers

Example

<?
// file /bitrix/php_interface/init.php
AddEventHandler("main",
                "OnBeforeProlog",
                "MyOnBeforePrologHandler",
                50);

function MyOnBeforePrologHandler()
{
    global $USER;
    if (SITE_TEMPLATE_ID=='mynewtemplate' &&
        $_SERVER['REMOTE_ADDR']!='127.0.0.1' &&
        !$USER->IsAdmin())
    {
        die('This template is temporary unavailable.');
    }
}
?>


OnBeforeSiteDelete

bool
event_handler(
 string site_id
);

The OnBeforeSiteDelete event fires before a site is deleted. A common use of this module is to allow or disallow the site deletion.

Parameters

Parameter | Description
site_id | The ID of the site which is to be deleted.

Return Values

To cancel the site deletion and terminate the CSite::Delete method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnSiteDelete event
  • CSite::Delete
  • Event handlers

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnBeforeSiteDelete"
    function OnBeforeSiteDeleteHandler($site_id)
    {
        // check if any records exist bound to the deleted language
        $strSql = "SELECT * FROM my_table WHERE SITE_ID=".$DB->ForSql($site_id);
        $rs = $DB->Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);

        // if found...
        if ($ar = $rs->Fetch())
        {
            // cancel deletion.
            global $APPLICATION;
            $APPLICATION->throwException("My table has bound records.");
            return false;
        }
    }
}
?>

Example of handler registration

<?
// register handler "OnBeforeSiteDelete"
RegisterModuleDependences("main",
                          "OnBeforeSiteDelete",
                          "my_module_id",
                          "MyClass",
                          "OnBeforeSiteDeleteHandler");
?>


OnBeforeUserDelete

bool
event_handler(
 int user_id
);

The OnBeforeUserDelete event fires before the user is deleted. A common use of this module is to allow or disallow the user deletion.

Parameters

Parameter | Description
user_id | The ID of the user which is to be deleted.

Return Values

To cancel the site deletion and terminate the CUser::Delete method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnUserDelete event
  • CUser::Delete
  • Event handlers

Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main",
                "OnBeforeUserDelete",
                Array("MyClass",
                      "OnBeforeUserDeleteHandler"));
class MyClass
{
    // create handler "OnBeforeUserDelete"
    function OnBeforeUserDeleteHandler($user_id)
    {
        // check if any records exist bound to the deleted language
        $strSql = "SELECT * FROM my_table WHERE USER_ID=".intval($user_id);
        $rs = $DB->Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);

        // if found...
        if ($ar = $rs->Fetch())
        {
            // cancel deletion.
            global $APPLICATION;
            $APPLICATION->throwException("My table has bound records.");
            return false;
        }
    }
}
?>


OnBeforeUserLogin event

bool
event_handler(
 array &arParams
);

The OnBeforeUserLogin event is fired in the method CUser::Login before a user authorization attempt (before the login arParams['LOGIN'] and password arParams['PASSWORD'] are both verified). This can be used to cancel the process of fields checking or redefining.

Parameters

Parameter Description
arParams Array of fields used for user login and password verification, the following keys available:
  • LOGIN - user login;
  • PASSWORD - user password. If the value of PASSWORD_ORIGINAL is "Y", this parameter contains the original password. Otherwise, this parameter contains the MD5 hash value of the original password.
  • REMEMBER - if "Y", the user authorization information is to be stored in cookie.
  • PASSWORD_ORIGINAL - if "Y", the value of the PASSWORD field contains the original password typed by a user (not converted to MD5). If "N", the value of the PASSWORD field is converted to MD5.

Note
All parameters passed to this handler function are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

Return Values

To cancel the user authorization and terminate the CUser::Login method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterUserLogin event
  • CUser::Login
  • Event handlers
  • External authorization

Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main",
                "OnBeforeUserLogin",
                Array("MyClass",
                      "OnBeforeUserLoginHandler"));

class MyClass
{
    // create handler "OnBeforeUserLogin"
    function OnBeforeUserLoginHandler(&$arFields)
    {
        // perform any actions here
        if (strtolower($arFields["LOGIN"]) == "guest")
        {
            global $APPLICATION;
            $APPLICATION->throwException("User named Guest cannot be authorized.");
            return false;
        }
    }
}
?>


OnBeforeUserLoginByHash event

bool
event_handler(
 array &arParams
)

The OnBeforeUserLoginByHash event fires in the method CUser::LoginByHash() before the verification of login arParams['LOGIN'] and a password hash arParams['HASH'], before the authorization attempt.

Parameters

Parameter Description
arParams Array of fields used for user login and password verification, the following keys available:
  • LOGIN - user login;
  • HASH - special hash calculated on password string. This value is usually stored in a user cookie.

Note
All parameters passed to this handler function are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

Return Values

To cancel the user authorization and terminate the CUser::LoginByHash method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterUserLoginByHash event
  • CUser::LoginByHash
  • Event handlers
  • External authorization

Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main",
                "OnBeforeUserLoginByHash",
                Array("MyClass",
                      "OnBeforeUserLoginByHashHandler"));

class MyClass
{
    // create handler "OnBeforeUserLoginByHash"
    function OnBeforeUserLoginByHashHandler(&$arParams)
    {
        // perform any actions here
        if(strtolower($arParams['LOGIN'])=="guest")
        {
            global $APPLICATION;
            $APPLICATION->throwException("User named Guest cannot be authorized using password hash.");
            return false;
        }
    }
}
?>


OnBeforeUserLogout event

bool
event_handler(
 array &arParams
);

The OnBeforeUserLogout event fires before the user authorization completes from within the method CUser::Logout and can be used to cancel the log-out.

Parameters

Parameter Description
arParams Array of parameters:
  • ID - user ID.

See Also

  • OnAfterUserLogout event
  • CUser::Logout
  • Event handlers

Example

<?
// file /bitrix/php_interface/init.php
// register event handler
AddEventHandler("main",
                "OnBeforeUserLogout",
                Array("MyClass",
                      "OnBeforeUserLogoutHandler"));

class MyClass
{
    function OnBeforeUserLogoutHandler($arParams)
    {
        if ($arParams['ID']==10)
            return false;
    }
}
?>

Example of handler registration

<?
// register handler "OnBeforeUserLogout"
RegisterModuleDependences("main", "OnBeforeUserLogout",
"my_module_id", "MyClass", "OnBeforeUserLogoutHandler");?>


OnBeforeUserRegister event

bool
event_handler(
 array &arArgs
);

The OnBeforeUserRegister event fires before an attempt of a new user registration by calling the method CUser::Register. This can be used to cancel the registration process or redefine fields.

Parameters

Parameter Description
arArgs Array of new user registration fields:
  • LOGIN - user login;
  • NAME - user first name;
  • LAST_NAME - user last name;
  • PASSWORD - password;
  • CONFIRM_PASSWORD - password confirmation;
  • CHECKWORD - new check word for password change;
  • EMAIL - user e-mail;
  • ACTIVE - active state flag [Y|N];
  • SITE_ID - the ID of default site used for notifications;
  • GROUP_ID - array of user group ID's;
  • USER_IP - user IP address;
  • USER_HOST - user host name.
Using this array, the system adds a user and sends an e-mail message NEW_USER.

Note
All parameters passed to this handler function are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables. This allows to add additional user registration fields or a NEW_USER e-mail event fields to the array arArgs.

Return Values

To cancel the user registration and terminate the CUser::Register method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterUserRegister event
  • Event handlers
  • CUser::Register

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnBeforeUserRegister"
    function OnBeforeUserRegisterHandler(&$arFields)
    {
        // if a user came under the adv campaign #34...
        if ($_SESSION["SESS_LAST_ADV_ID"]==34)
        {
            // add him to group #3
            $arFields["GROUP_ID"][] = 3;

            // add admin comment
            if (intval($_SESSION["SESS_ADV_ID"])>0)
                $arFields["ADMIN_NOTES"] = "Adv. campaign #34 - direct hit";
            else
                $arFields["ADMIN_NOTES"] = "Adv. campaign #34 - return";

            $arFields["SITE_ID"] = "ru";
        }
    }
}
?>

Example of handler registration

<?
// register handler "OnBeforeUserRegister"
RegisterModuleDependences("main",
                          "OnBeforeUserRegister",
                          "my_module_id",
                          "MyClass",
                          "OnBeforeUserRegisterHandler");
?>


OnBeforeUserSimpleRegister event

bool
event_handler(
 array &arFields,
);

The OnBeforeUserSimpleRegister event fires before a attempt of user simplified registration performed by CUser::SimpleRegister. This can be used to cancel the registration process or redefine fields.

Parameters

Parameter Description
arFields Array of new user registration fields:
  • PASSWORD - password;
  • CONFIRM_PASSWORD - password confirmation;
  • CHECKWORD - new check word for password change;
  • EMAIL - user e-mail;
  • ACTIVE - active state flag [Y|N];
  • SITE_ID - the ID of default site used for notifications;
  • GROUP_ID - array of user group ID's;
  • USER_IP - user IP address;
  • USER_HOST - user host name.
Using this array, the system adds a user and sends an e-mail message NEW_USER.

Note
All parameters passed to this handler function are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables. This allows to add additional user registration fields or define add a LOGIN field (sensible user name - by default, the logis is set to user<new user ID>" after the registration) .

Return Values

To cancel the user registration and terminate the CUser::SimpleRegister method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterUserSimpleRegister event
  • Event handlers
  • CUser::Register

Example

<?
// file /bitrix/php_interface/init.php
AddEventHandler(
    "main",
    "OnBeforeUserSimpleRegister",
    Array("MyClass",
          "OnBeforeUserSimpleRegisterHandler"),
    100,
    $_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/scripts/onbeforeusersimplereg.php"
);
?>

<?
// file /bitrix/php_interface/scripts/onbeforeusersimplereg.php
class MyClass
{
    // create handler "OnBeforeUserSimpleRegister"
    function OnBeforeUserSimpleRegisterHandler(&$arFields)
    {
        if (strpos($arFields["EMAIL"], "@mysite.com")===false)
        {
            global $APPLICATION;
            $APPLICATION->ThrowException("The registration is only possible "
                                         "for e-mail addresses of the domain mysite.com");
            return false;
        }
    }
}
?>


OnChangeFile

event_handler(
 string path,
 string site_id
);

The OnChangeFile event is fired right after a file is saved by a call to method $APPLICATION->SaveFileContent.

Parameters

Parameter | Description
path | File path relative to the site root.
site_id | The ID of the site whose file has changed.

See Also

  • OnChangePermissions event
  • CMain::SaveFileContent
  • Event handlers

Example

<?
// file /bitrix/php_interface/init.php
AddEventHandler("main",
                "OnChangeFile",
                Array("MyClass",
                      "OnChangeFileHandler"));

class MyClass
{
    // create handler "OnChangeFile"
    function OnChangeFileHandler($path, $site)
    {
        // get DOCUMENT_ROOT to the specified site
        $DOC_ROOT = CSite::GetSiteDocRoot($site);

        // obtain the file contents using absolute path
        $filesrc = $APPLICATION->GetFileContent($DOC_ROOT.$path);

        // parse file
        $arContent = ParseFileContent($filesrc);
        $TITLE = $arContent["TITLE"];
        $BODY = $arContent["CONTENT"];

        // insert a record on the file change in the table
        $arFields = array(
            "MODIFIED_BY" => $USER->GetID(), // who changed
            "TITLE"       => $TITLE,         // file title
            "FILENAME"    => $path,          // path relative to root
            "SITE_ID"     => $site,          // site ID
            "BODY"        => $BODY,          // file contents
            );
        $arInsert = $DB->PrepareInsert("b_workflow_log",
                                       $arFields, "workflow");
        $strSql = "INSERT INTO b_workflow_log (TIMESTAMP_X,  ".
                  $arInsert[0].") VALUES(now(), ".$arInsert[1].")";
        $DB->Query($strSql, false,
                   "FILE: ".__FILE__."<br>LINE: ".__LINE__);
    }
}
?>


OnChangePermissions

event_handler(
 array site_path,
 array permissions
);
The OnChangePermissions event fires when the file or folder access permission is modified by a call to $APPLICATION->SetFileAccessPermission.

Parameters

Parameter | Description
site_path | Array in the format array("site ID", "file path relative to the site root").
permissions | Array of access permissions.

See Also

  • OnChangeFile event
  • CMain::SetFileAccessPermission
  • Access permissions
  • Event handlers

Example

<?
// file /bitrix/modules/search/classes/mysql/search.php
class CSearch extends CAllSearch
{
    // create handler "OnChangePermissions"
    function OnChangeFilePermissions($path, $permission)
    {
        CMain::InitPathVars($site, $path);
        $DOC_ROOT = CSite::GetSiteDocRoot($site);

        // trim / in the end
        while(strlen($path)>0 && $path[strlen($path)-1]=="/")
            $path=substr($path, 0, strlen($path)-1);

        global $APPLICATION, $DB;
        if(file_exists($DOC_ROOT.$path))
        {
            @set_time_limit(300);
            $arGroups = CSearch::GetGroupCached();
            if(is_dir($DOC_ROOT.$path))
            {
                $handle  = @opendir($DOC_ROOT.$path);
                while($file = @readdir($handle))
                {
                    if($file == "." || $file == "..") continue;
                    if(is_dir($DOC_ROOT.$path."/".$file))
                    {
                        if($path."/".$file=="/bitrix")
                            continue;
                    }
                    CSearch::OnChangeFilePermissions(Array($site,
                                                           $path."/".$file),
                                                     Array());
                }
            }
            else //if(is_dir($DOCUMENT_ROOT.$path))
            {
                $strGPerm = "0";
                for ($i=0; $i<count($arGroups); $i++)
                {
                    if ($arGroups[$i]>1)
                    {
                        $p =
                            $APPLICATION->GetFileAccessPermission(Array($site,
                                                                        $path),
                                                                  Array($arGroups[$i]));
                        if ($p>="R")
                        {
                            $strGPerm .= ",".$arGroups[$i];
                            if($arGroups[$i]==2) break;
                        }
                    }
                }

                $r = $DB->Query("SELECT ID FROM b_search_content WHERE ".
                                "MODULE_ID='main' AND ITEM_ID='".$site."|".$path."'");
                while ($arR = $r->Fetch())
                    $DB->Query("DELETE FROM b_search_content_group "
                               "WHERE SEARCH_CONTENT_ID=".$arR["ID"]);

                $strSql =
                    "INSERT INTO b_search_content_group(SEARCH_CONTENT_ID, GROUP_ID) ".
                    "SELECT S.ID, G.ID ".
                    "FROM b_search_content S, b_group G ".
                    "WHERE MODULE_ID='main' ".
                    "    AND ITEM_ID='".$site."|".$path."' ".
                    "    AND G.ID IN (".$strGPerm.") ";

                $DB->Query($strSql);
            } //if(is_dir($DOCUMENT_ROOT.$path))
        }//if(file_exists($DOCUMENT_ROOT.$path))
    }
}
?>

Example of handler registration

<?
// register handler "OnChangePermissions"
RegisterModuleDependences("main",
                          "OnChangePermissions",
                          "search", "CSearch",
                          "OnChangeFilePermissions");
?>


OnEpilog event

event_handler();

The OnEpilog event fires at the end of processing the visual aspect of the site epilogue.

Parameters

No parameters.

See Also

  • OnAfterEpilog event
  • Page execution stages. Variables and constants available at each stage
  • Event handlers

Example

<?
RegisterModuleDependences("main",
                          "OnEpilog",
                          "statistic",
                          "CStatistic",
                          "Set404", "100");
?>


OnEventMessageDelete

event_handler(
 int template_id
);

The OnEventMessageDelete event fires at the time of deleting a mail template. A common task of this handler is to clean the database of records related to the deleted mail template.

Parameters

Parameter | Description
template_id | The ID of the template which is to be deleted.

See Also

  • OnBeforeEventMessageDelete event
  • CEventMessage::Delete
  • Event handlers

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnEventMessageDelete"
    function OnEventMessageDeleteHandler($template_id)
    {
        // delete related records
        $strSql = "DELETE FROM my_table WHERE TEMPLATE_ID=".
                  intval($template_id);
        $rs = $DB->Query($strSql, false,
                         "FILE: ".__FILE__."<br>LINE: ".__LINE__);
    }
}
?>

Example of handler registration

<?
// register handler "OnEventMessageDelete"
RegisterModuleDependences("main", "OnEventMessageDelete",
                          "my_module_id", "MyClass",
                          "OnEventMessageDeleteHandler");
?>


OnExternalAuthList

array
event_handler();

The OnExternalAuthList event handler is called to obtain a list of external authorization sources by the method CUser::GetExternalAuthList.

Parameters

No parameters.

Return Values

Array in the format Array(Array("ID"=>"Sorce ID 1", "NAME"=>"Source name 1"), ...) .

See Also

  • Event handlers
  • CUser::GetExternalAuthList
  • External authorization

Example

<?
AddEventHandler("main",
                "OnExternalAuthList",
                Array("__IPBAuth",
                      "OnExternalAuthList"));

class __IPBAuth
{
  function OnExternalAuthList()
  {
     return Array(
      Array("ID"=>"IPB",
            "NAME"=>"Invision Power Board")
      );
 }
}
?>


OnGroupDelete

event_handler(
 int group_id
);

The OnGroupDelete event is fired when a user group is deleted. A common task of this handler is to clean the database of records related to the deleted user group.

Parameters

Parameter | Description
group_id | The ID of the user group which is to be deleted.

See Also

  • OnBeforeGroupDelete event
  • CGroup::Delete
  • Event handlers

Example

<?
// file /bitrix/php_interface/init.php
AddEventHandler("main", "OnGroupDelete",
                Array("MyClass", "OnGroupDeleteHandler"));
class MyClass
{
    // create handler "OnGroupDelete"
    function OnGroupDeleteHandler($group_id)
    {
        // delete related records
        $strSql = "DELETE FROM my_table WHERE GROUP_ID=".
                  intval($group_id);
        $rs = $DB->Query($strSql, false,
                         "FILE: ".__FILE__."<br>LINE: ".__LINE__);
    }
}
?>


OnLanguageDelete

event_handler(
 int language_id
);

The OnLanguageDelete event fires when a language is deleted. A common task of this handler is to clean the database of records related to the deleted language.

Parameters

Parameter | Description
language_id | The ID of the language which is to be deleted.

See Also

  • OnBeforeLanguageDelete event
  • CLanguage::Delete
  • Event handlers

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnLanguageDelete"
    function OnLanguageDeleteHandler($language_id)
    {
        // delete related records
        $strSql = "DELETE FROM my_table WHERE LANGUAGE_ID=".
                  $DB->ForSql($language_id);
        $rs = $DB->Query($strSql, false,
                         "FILE: ".__FILE__."<br>LINE: ".__LINE__);
    }
}
?>

Example of handler registration

<?
// register handler "OnLanguageDelete"
RegisterModuleDependences("main", "OnLanguageDelete",
                          "my_module_id", "MyClass",
                          "OnLanguageDeleteHandler");
?>


OnPageStart event

event_handler();

The OnPageStart event fires at the start of the executable section of the site prologue after the inclusion of all libraries and running all agents.

Parameters

No parameters.

See Also

  • OnBeforeProlog event
  • Page execution stages. Variables and constants available at each stage
  • Event handlers

Example of handler registration

<?
RegisterModuleDependences("main", "OnPageStart",
                          "statistic", "CStatistic",
                          "Stoplist", "100");
?>


OnPanelCreate

event_handler();

The OnPanelCreate event handler is called when the system collects information for building the control toolbar in the public section of the site. Handler function thus can add custom buttons to the toolbar.

Parameters

No parameters.

See Also

  • Control toolbar
  • CMain::AddPanelButton
  • CMain::ShowPanel
  • Event handlers

Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main", "OnPanelCreate",
                Array("MyClass", "OnPanelCreateHandler"));
class MyClass
{
    // add a button
    function OnPanelCreateHandler()
    {
        global $APPLICATION;
        $APPLICATION->AddPanelButton(array(
            // hyperlink
            "HREF"      => "/bitrix/admin/my_page.php",
            // button image
            "SRC"       => "/bitrix/images/my_module_id/button_image.gif",
            "ALT"       => "Cool function",
            "MAIN_SORT" => 300,
            "SORT"      => 10
            ));
    }
    /*
    Now the toolbar display our button
    */
}
?>


OnProlog

event_handler();
The OnProlog event is fired at the beginning of processing the visual aspect of the site prologue.

Parameters

No parameters.

See Also

  • OnBeforeProlog event
  • Page execution order
  • Event handlers

Example

<?
    RegisterModuleDependences("main",
                              "OnProlog",
                              "statistic",
                              "CStatistic",
                              "StartBuffer", "100");
?>


OnSendUserInfo event

event_handler(
  array &arParams
);

The OnSendUserInfo event handler is called from the method CUser::SendUserInfo. Handler function can redefine parameters of sending an e-mail message USER_INFO.

Parameters

Parameter Description
arParams Array of fields for checking login and password:
  • FIELDS - array containing fields in the format Array("field 1"=>"value 1", ...). All these fields are passed to the template USER_INFO. By default, contains the following fields:
    • "USER_ID" - user ID;
    • "STATUS" - active state text;
    • "MESSAGE" - message body text;
    • "LOGIN" - login;
    • "CHECKWORD" - check word;
    • "NAME" - user first name;
    • "LAST_NAME" - user last name;
    • "EMAIL" - e-mail address.
  • USER_FIELDS - fields of user whose information is to be sent;
  • SITE_ID - ID of the site. Used to determine the USER_INFO template.

Note
All parameters passed to this handler function and the arParams array are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

See Also

  • CUser::SendUserInfo
  • Mail events
  • Event handlers

Example

<?
// file /bitrix/php_interface/init.php
AddEventHandler("main",
                "OnSendUserInfo",
                "MyOnSendUserInfoHandler");

function MyOnSendUserInfoHandler(&$arParams)
{
    if (strlen($arParams['USER_FIELDS']['LAST_NAME']) <= 0)
        $arParams['CUSTOM_NAME'] =
            $arParams['USER_FIELDS']['LAST_NAME'];
    else
        $arParams['CUSTOM_NAME'] =
            $arParams['USER_FIELDS']['LOGIN'];
    //
    // now macro #CUSTOM_NAME# can be used
    // with template USER_INFO
    //
}
?>


OnSiteDelete

event_handler(
 int site_id
);

The OnSiteDelete event fires when a site is deleted. A common task of this handler is to clean the database of records related to the deleted site.

Parameters

Parameter | Description
site_id | The ID of the site which is to be deleted.

See Also

  • OnBeforeSiteDelete event
  • CSite::Delete
  • Event handlers

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnSiteDelete"
    function OnSiteDeleteHandler($site_id)
    {
        // delete related records
        $strSql = "DELETE FROM my_table WHERE SITE_ID=".
                  $DB->ForSql($site_id);
        $rs = $DB->Query($strSql, false,
                         "FILE: ".__FILE__."<br>LINE: ".__LINE__);
    }
}
?>

Example of handler registration

<?
// register handler "OnSiteDelete"
RegisterModuleDependences("main", "OnSiteDelete",
                          "my_module_id", "MyClass",
                          "OnSiteDeleteHandler");
?>


OnUserDelete

event_handler(
 int user_id
)

The OnUserDelete event fires when a user is deleted. A common task of this handler is to clean the database of records related to the deleted user.

Parameters

Parameter | Description
user_id | The ID of the user which is to be deleted.

See Also

  • OnBeforeUserDelete event
  • CUser::Delete
  • Event handlers

Example

<?
// file /bitrix/modules/my_module_id/include.php
class MyClass
{
    // create handler "OnUserDelete"
    function OnUserDeleteHandler($user_id)
    {
        // delete related records
        $strSql = "DELETE FROM my_table WHERE USER_ID=".
                  intval($user_id);
        $rs = $DB->Query($strSql, false,
                         "FILE: ".__FILE__."<br>LINE: ".__LINE__);
    }
}
?>

Example of handler registration

<?
// register handler "OnUserDelete"
RegisterModuleDependences("main", "OnUserDelete",
                          "my_module_id", "MyClass",
                          "OnUserDeleteHandler");
?>


OnUserLoginExternal event

mixed
event_handler(
  array &arParams
);

The OnUserLoginExternal event is used to check user login and password in an external authorization source. Handlers of this event are called from within the method CUser::Login if none of the OnBegoreUserLogin handlers return false, before a user authorization attempt and before the login arParams['LOGIN'] and password arParams['PASSWORD'] are both verified.

Parameters

Parameter Description
arParams Array of fields used for user login and password verification, the following keys available:
  • LOGIN - user login;
  • PASSWORD - user password. If the value of PASSWORD_ORIGINAL is "Y", this parameter contains the original password. Otherwise, this parameter contains the MD5 hash value of the original password.
  • REMEMBER - if "Y", the user authorization information is to be stored in cookie.
  • PASSWORD_ORIGINAL - if "Y", the value of the PASSWORD field contains the original password typed by a user (not converted to MD5). If "N", the value of the PASSWORD field is converted to MD5.

Note
All parameters passed to this handler function and the arParams array are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

Return Values

If a user is to be authorized, the handler should return the ID of this user.

See Also

  • OnBeforeUserLogin event
  • OnAfterUserLogin event
  • CUser::Login
  • Event handlers
  • External authorization

Example

<?
// example of user authorization
// based on tables of Innovision Power Board

// file /bitrix/php_interface/init.php
AddEventHandler("main", "OnUserLoginExternal",
                Array("__IPBAuth", "OnUserLoginExternal"));
AddEventHandler("main", "OnExternalAuthList",
                Array("__IPBAuth", "OnExternalAuthList"));

define("IPB_TABLE_PREFIX", "ibf_");
define("IPB_VERSION", "2");

class __IPBAuth
{
    function OnUserLoginExternal(&$arArgs)
    {
        $groups_map = Array(
            /*'IPB Group ID' => 'Local Group ID',*/
            '4' => '1'
            );
        $table_user = IPB_TABLE_PREFIX."members";
        $table_converge = IPB_TABLE_PREFIX."members_converge";

        global $DB, $USER, $APPLICATION;
     extract($arArgs);

        if(IPB_VERSION == '1')
        {
            $strSql = "SELECT * FROM ".$table_user.
                      " WHERE name='".$DB->ForSql($LOGIN).
                      "' AND password='".md5($PASSWORD)."'";
        }
        else
        {
            $strSql =
                "SELECT t1.* ".
                "FROM ".$table_user." t1, ".$table_converge." t2 ".
                "WHERE t1.name='".$DB->ForSql($LOGIN)."' ".
                "    AND t1.email = t2.converge_email ".
                "    AND t2.converge_pass_hash =
                     MD5(CONCAT(MD5(t2.converge_pass_salt),
                                '".md5($PASSWORD)."'))";
        }

        $dbAuthRes = $DB->Query($strSql);
        if($arAuthRes = $dbAuthRes->Fetch())
        {
            $arFields = Array(
                "LOGIN" => $LOGIN,
                "NAME" => $arAuthRes['title'],
                "PASSWORD" => $PASSWORD,
                "EMAIL" => $arAuthRes['email'],
                "ACTIVE" => "Y",
                "EXTERNAL_AUTH_ID"=>"IPB",
                "LID" => SITE_ID
                );

            $oUser = new CUser;
            $res = CUser::GetList($O, $B,
                                  Array("LOGIN_EQUAL_EXACT"=>$LOGIN,
                                        "EXTERNAL_AUTH_ID"=>"IPB"));
            if(!($ar_res = $res->Fetch()))
                $ID = $oUser->Add($arFields);
            else
            {
                $ID = $ar_res["ID"];
                $oUser->Update($ID, $arFields);
            }

            if($ID>0)
            {
                $USER->SetParam("IPB_USER_ID", $arAuthRes['id']);

                $user_group = $arAuthRes['mgroup'];
                $arUserGroups = CUser::GetUserGroup($ID);
                foreach($groups_map as $ext_group_id => $group_id)
                {
                    if($ext_group_id==$user_group)
                        $arUserGroups[] = $group_id;
                    else
                    {
                        $arUserGroupsTmp = Array();
                        foreach($arUserGroups as $grid)
                            if($grid != $group_id)
                                $arUserGroupsTmp[] = $grid;
                        $arUserGroups = $arUserGroupsTmp;
                    }
                }
                CUser::SetUserGroup($ID, $arUserGroups);
                $arParams["STORE_PASSWORD"] = "N";

                return $ID;
            }
        }
    }

    function OnExternalAuthList()
    {
        return Array(
            Array("ID"=>"IPB", "NAME"=>"Invision Power Board")
            );
    }
}
?>


OnAfterUserUpdate

OnAfterUserUpdate event

event_handler(
 array &arFields
);
The OnAfterUserUpdate event fires upon an attempt to modify a user properties by calling CUser::Update.

Parameters

Parameter | Description
arFields | An array of fields describing the user whose information is to be updated. Additionally, the RESULT field contains the return value of CUser::Update. If the latter failed, the RESULT_MESSAGE field will contain the error description.

Note
All parameters passed to this handler function and the arParams array are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

See Also

  • OnBeforeUserUpdate event
  • CUser::Update
  • Event handlers

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main", "OnAfterUserUpdate", Array("MyClass", "OnAfterUserUpdateHandler"));

class MyClass
{
    // create the OnAfterUserUpdate event handler
    function OnAfterUserUpdateHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Record with ID=".$arFields["ID"]." has been modified.");
        else
            AddMessage2Log("Error updating record ".$arFields["ID"]." (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnBeforeUserUpdate

bool
event_handler(
 array &arParams
);
The OnBeforeUserUpdate event is fired from the CUser::Update method before a user parameter changes, which can be used to cancel update or modify the user record fields.

Parameters

Parameter | Description
arParams | An array of fields describing the user whose information is to be updated.

Note
All parameters passed to this handler function and the arParams array are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

Return Values

To cancel update and terminate the CUser::Update method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterUserUpdate event
  • CUser::Update
  • Event handlers

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main", "OnBeforeUserUpdate", Array("MyClass", "OnBeforeUserUpdateHandler"));

class MyClass
{
    // create the "OnBeforeUserUpdate" event handler
    function OnBeforeUserUpdateHandler(&$arFields)
    {
        if(is_set($arFields, "LAST_NAME") && strlen($arFields["LAST_NAME"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Please type in the last name. (ID:".$arFields["ID"].")");
            return false;
        }
    }
}
?>


OnBeforeUserAdd

bool
event_handler(
   array &arParams
);

The OnBeforeUserAdd event is fired from the CUser::Add method before a new user is enrolled (added to the database), which can be used to cancel enrollment or modify the user record fields.

Parameters

Parameter | Description
arParams | An array of fields describing the user to be added.

Note
All parameters passed to this handler function and the arParams array are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

Return Values

To cancel enrollment and terminate the CUser::Add method, raise an exception from within the handler using the method $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterUserAdd event
  • CUser::Add
  • Event handlers

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main", "OnBeforeUserAdd", Array("MyClass", "OnBeforeUserAddHandler"));

class MyClass
{
    // create the "OnBeforeUserAdd" event handler
    function OnBeforeUserAddHandler(&$arFields)
    {
        if(strlen($arFields["LAST_NAME"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Please type in the last name.");
            return false;
        }
    }
}
?>


OnAfterUserAdd

OnAfterUserAdd event

event_handler(
 array &arFields
);
The OnAfterUserAdd event is fired upon an attempt to add a new user by calling CUser::Add.

Parameters

Parameter | Description
arFields | An array of fields describing the user whose information is to be updated. Additionally, the RESULT field contains the return value of CUser::Add. If the latter failed, the RESULT_MESSAGE field will contain the error description.

Note
All parameters passed to this handler function and the arParams array are references to original variables. Therefore, all changes to parameters made within the handler affect values of the original variables.

See Also

  • OnBeforeUserAdd event
  • CUser::Add
  • Event handlers

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("main", "OnAfterUserAdd", Array("MyClass", "OnAfterUserAddHandler"));

class MyClass
{
    // create the "OnAfterUserAdd" event handler
    function OnAfterUserAddHandler(&$arFields)
    {
        if($arFields["ID"]>0)
            AddMessage2Log("Redord with ID=".$arFields["ID"]." has been added.");
        else
            AddMessage2Log("Error adding record (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


Functions Overview

The Bitrix Site Manager provides various functions that developers can use in their code.

  • Strings and text - used with strings and text.
  • Array functions - array helper functions.
  • Date and time - used with date, time and calendar.
  • Files and directories - used with the site file system.
  • HTML Elements - used with HTML forms.
  • Persistent filter and sorting - used to build and manage filters and sorting schemas.
  • Modules functions - used with the system modules.
  • Language files functions - used for localization of scripts.
  • Debugging functions - used for debugging.
  • Other functions.


Array functions

The system exposes the following array helper functions.

Function | Description
TrimArr | Deletes elements with empty values from the specified array.
is_set | Checks whether a variable or array key exists.


is_set

bool
is_set(
 mixed &var,
 string key = false
)

The function is_set checks whether a variable or array key exists. If a variable var is set or a key can be found in the array var, the function returns true. Otherwise, false is returned.

Note
When checking for array key existence, note that the function returns true even if the array key has a value of "null" unlike the standard function isset (see Example below).

Parameters

Parameter | Description
var | A variable of arbitrary type can be passed in this parameter. If the var parameter is an array, the key needs to contain the name of the key whose existence is to be checked. If it is not an array, the function check whether a variable with the passed name is initialised or not (identical to the PHP function isset).
key | If the var parameter is an array, this parameter should contain the name of the key in array defined by var.

Example

<?

/********************************************
            Example with array
********************************************/

$ar = array("a" => "", "b" => null);

if (is_set($ar, "a"))
    echo 'The key "a" is found in array $ar.';
else
    echo 'The key "a" is not found in array $ar.';
//
// output: "The key "a" is found in array $ar."
//

if (isset($ar["a"]))
    echo 'The key "a" of array $ar is initialised.';
else
    echo 'The key "a" of array $ar is not initialised.';
//
// output: "The key "a" of array $ar is initialised."
//

if (is_set($ar, "b"))
    echo 'The key "b" is found in array $ar.';
else
    echo 'The key "b" is not found in array $ar.';
//
// output: "The key "b" is found in array $ar."
//

// BUT!
if (isset($ar["b"]))
    echo 'The key "b" of array $ar is initialised.';
else
    echo 'The key "b" of array $ar is not initialised.';
// (!) output: "The key "b" of array $ar is not initialised."

if (is_set($ar, "c"))
    echo 'The key "c" is found in array $ar.';
else
    echo 'The key "c" is not found in array $ar.';
//
// output: "The key "c" is not found in array $ar."

/********************************************
  Example with variable (not array)
********************************************/

$init_var = "A";
if (is_set($init_var))
    echo 'Variable $init_var is initialised.';
else
    echo 'Variable $init_var is not initialised.';
//
// output: "Variable $init_var is initialised."
//

if (is_set($not_init_var))
    echo 'Variable $not_init_var is initialised.';
else
    echo 'Variable $not_init_var is not initialised.';
//
// output: "Variable $not_init_var is not initialised."
//
?>


TrimArr

bool
TrimArr(
 array &arr
)

The function TrimArr deletes elements with empty values from the specified array. If at least one element is deleted, the function returns true. Otherwise, false is returned.

Parameters

Parameter | Description
arr | Array to be processed. This parameters is specified as a reference to the source array.

Example

<?
$ar = array(
  "a" => "1",
  "b" => " ",
  "c" => "",
  "d" => "2"
);
TrimArr($ar);
// array $ar now looks as follows:
//  array("a" => "1", "d" => "2")
?>


Strings and text

The following functions are used with strings and text.

Function | Description
TxtToHTML | Converts plain text to HTML formatted text.
HTMLToTxt | Converts the original HTML code to plain text by deleting tags or replacing them with the equivalent text format.
TruncateText | Truncates the specified string to the maximum length of max_length. If a string is truncated, ellipsis are added.
InsertSpaces | Splits long words in a text. Returns the text containing words of the specified length.
RandString | Returns a string of the specified length consisting of random symbols.
ToUpper | Converts symbols of the original string to uppercase.
ToLower | Converts the symbols of the original string to lowercase.
htmlspecialcharsEx | Converts text to HTML safe format, replacing special symbols with the corresponding HTML entities.
htmlspecialcharsBack | Converts text from HTML safe format to the human-readable form.
utf8win1251 | Converts a string from UTF-8 to Windows-1251.


htmlspecialcharsBack

string
htmlspecialcharsBack(
 string text
)

The function htmlspecialcharsBack converts text from HTML safe format to the human-readable form, performing the following substitutions:
Original symbols | After replacement
&lt; | <
&gt; | >
&quot; | "
&amp; | &

Parameters

Parameter | Description
text | Text to be converted.

See Also

  • htmlspecialcharsEx

Example

<?
$text = '&quot;if a&gt;b and b&gt;c then a&gt;c&quot;'
$res = htmlspecialcharsBack($str);
// $res now contains:
// "if a>b and b>c then a>c"
?>


htmlspecialcharsEx

string
htmlspecialcharsEx(
 string text
)

The function htmlspecialcharsEx converts text to HTML safe format, replacing special symbols with the corresponding HTML entities:
Original symbols | After replacement
< | &lt;
> | &gt;
" | &quot;
&quot; | &amp;quot;
&amp; | &amp;amp;
&lt; | &amp;lt;
&gt; | &amp;gt;

Note
Unlike the standard PHP function htmlspecialchars, this function allows to specify symbols in the format &symbol_code;.

Parameters

Parameter | Description
text | Text to be converted.

See Also

  • htmlspecialcharsBack

Example

<?
$text = '"if a>b and b>c, then a>c"';

$res = htmlspecialcharsEx($text);
// $res now contains:
// &quot;if a&gt;b and b&gt;c then a&gt;c&quot;

echo $res;
// output:
// "if a>b and b>c then a>c"
?>


HTMLToTxt

string
HTMLToTxt(
 string text,
 string host = "",
 array delete = array()
)

The function HTMLToTxt converts the original HTML code to plain text by deleting tags or replacing them with the equivalent text format.

Parameters

Parameter | Description
text | The original text in the HTML format.
host | A site web address. If specified, it is inserted before each link in HTML to form the full link. Optional. Empty by default.
delete | An array of templates specified using the regular expressions describing patterns to be deleted from text. Optional. Empty by default.

See Also

  • TxtToHTML

Example

Call:

<?
$str = '
<table>
  <tr>
    <td valign=top><b><a href="/en/products/sitemanager/editions/business.php">Business</a>
  - </B>the full version to manage an e-store, dealer network support.<BR><FONT class=smalltext><b>$1699</B>
  (MySQL version)<br><b>$24500</b>
  (Oracle version)</font></td>
  </tr>
</table>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
';
echo HTMLToTxt($str, "http://www.bitrix.com");
?>

Result:

Business [ http://www.bitrix.com/en/products/sitemanager/editions/business.php ]
- the full version to manage an e-store, dealer network support.
$1699(MySQL version)
$24500 (Oracle version)

- Item 1
- Item 2
- Item 3
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


InsertSpaces

string
InsertSpaces(
 string text,
 int max_length = 80,
 string symbol = " "
)

The function InsertSpaces splits long words in a text. Returns the text containing words of the specified length.

Parameters

Parameter | Description
text | Original text.
max_length | The maximum number of symbols in a word. The longer words are split with the symbol specified in the parameter symbol.
symbol | Symbol used to split words whose length exceeds that specified in max_length.

See Also

  • TruncateText

Example

<?
$str = "1234567890 1234 123456";
echo InsertSpaces($str, 5);
// prints "12345 67890 1234 12345 6"
?>


RandString

string
RandString(
 int length = 10
)

The function RandString returns a string of the specified length consisting of random symbols. Random symbols can be Latin letters and digits. For example, the function can be used to generate passwords.

Parameters

Parameter | Description
length | Length of the resulting random string.

Example

<?
$new_password = RandString(7);
echo "New password: ".$new_password;
// prints the string "New password: fK4ftTP"
?>


ToLower

string
ToLower(
  string text
)

The function ToLower converts the symbols of the original string to lowercase. In addition to other alphabet symbols, this function correctly converts Cyrillic symbols to lowercase.

Note
This function can be used when the standard PHP function strtolower cannot convert Cyrillic symbols. Sometimes it takes place on some hostings.

Parameters

Parameter | Description
text | Source string.

See Also

  • ToUpper

Example

<?
$lower = ToLower("АБВГД ABCDEF");
echo "Lower case: ".$lower;
// prints "Lower case: абвгд abcdef"
?>


ToUpper

string
ToUpper(
  string text
)

The function ToUpper converts symbols of the original string to uppercase. In addition to symbols of other charsets , this function correctly converts Cyrillic symbols to uppercase.

Note
This function can be used when the standard PHP function strtoupper cannot convert Cyrillic symbols. Sometimes it takes place on some hostings.

Parameters

Parameter | Description
text | Source string.

See Also

  • ToLower

Example

<?
$upper = ToUpper("абвгд abcdef");
echo "Upper case: ".$upper;
// prints "Upper case: АБВГД ABCDEF"
?>


TruncateText

string
TruncateText(
 string text,
 int max_length
)

The function TruncateText truncates the specified string to the maximum length of max_length. If a string is truncated, ellipsis are added.

Parameters

Parameter | Description
text | Source string.
max_length | Maximum length of the target string.

See Also

  • InsertSpaces

Example

<?
$str = "1234567890";
echo TruncateText($str, 7);
// prints "1234567..."
?>


TxtToHTML

string
TxtToHTML(
 string text,
 bool make_url = true,
 int max_string = 0,
 string quote_tag_enabled = "N",
 string not_convert_amp = "Y",
 string code_tag_enabled = "N",
 string biu_tags_enabled = "N",
 string quote_table_class = "quotetable",
 string quote_head_class = "tdquotehead",
 string quote_body_class = "tdquote",
 string code_table_class = "codetable",
 string code_head_class = "tdcodehead",
 string code_body_class = "tdcodebody",
 string code_textarea_class = "codetextarea",
 string link_class = "txttohtmllink"
 array event = array()
);

The function TxtToHTML converts plain text to HTML formatted text.

Parameters

Parameter | Description
text | Original text to be converted.
make_url If true, strings containing web addresses (http://... or mailto:) will be converted to HTML links.
Optional; the default value is true.
max_string Maximum length of each word. All words whose length exceeds this value is split with spaces. A value of "0" disables splitting.
Optional; the default value is "0".
quote_tag_enabled If "Y", a special tag <QUOTE>...</QUOTE> will be converted to the HTML table (frames the quote in border).
Optional; the default value is "N".
not_convert_amp If "Y", ampersand symbols "&" will not be converted to "&amp;".
Optional; the default value is "Y".
code_tag_enabled If "Y", a special tag <CODE>...</CODE> will be converted to the HTML element "textarea" in table (frames the code in border and displays it in the "textarea" tag).
Optional; the default value is "N".
biu_tags_enabled | If "Y", special tags <b>...</b>, <i>...</i>, <u>...</u> are converted to corresponding HTML tags.
quote_table_class CSS class for the "quote" table (<quote>).
Optional; the default value is "quotetable".
quote_head_class CSS class for the first cell (TD) of the "quote" table (<quote>).
Optional; the default value is "tdquotehead".
quote_body_class CSS class for the second cell (TD) of the "quote" table (<quote>):
<table class="quote_table_class">
    <tr>
         <td class="quote_head_class"> ...
         </td>
    </tr>
    <tr>
         <td class="quote_body_class"> ...
         </td>
    </tr>
</table>
Optional; the default value is "tdquote".
code_table_class CSS class for the "code" table (<code>).
Optional; the default value is "codetable".
code_head_class CSS class for the first cell of the "code" table (<code>).
Optional; the default value is "tdcodehead".
code_body_class CSS class for the second cell of the "code" table (<code>).
Optional; the default value is "tdcodebody".
code_textarea_class CSS class for the "textarea" tag in the "code" table (<code>):
<table class="code_table_class">
    <tr>
         <td class="code_head_class"> ... </td>
    </tr>
    <tr>
         <td class="code_body_class">
             <textarea class="code_textarea_class"> ...
             </textarea>
         </td>
    </tr>
</table>
Optional; the default value is "codetextarea".
link_class CSS for links:
<a class="link_class"> ... </a>
Optional; the default value is "txttohtmllink".
event This array can be used to pass the event type identifiers to register when a link is clicked. This parameter is only effective if make_url is true. The following keys are possible:
  • EVENT1 - event type identifier - event1;
  • EVENT2 - event type identifier - event2;
  • EVENT3 - event type identifier - event3;
  • SCRIPT - path to the script file performing registration and redirect. The path is specified relative to the root.

See Also

  • HTMLToTxt

Example

Call

$text = "
text text text text
text text text text
longwordlongwordlongword
<code>code code code</code>
<quote>quote quote quote</quote>
<b>bold text</b>
<i>italic</i>
<u>underlined</u>
link:  http://www.bitrixsoft.com
email: support@bitrixsoft.com
";
echo TxtToHTML(
    $text,
    true,
    20,
    "Y",
    "N",
    "Y",
    "Y",
    "quotetable",
    "tdquotehead",
    "tdquote",
    "codetable",
    "tdcodehead",
    "tdcodebody",
    "codetextarea"
    );

Result

text text text text<br>
text text text text<br>
longwordlongwordlongwordlon gword<br>
<table class='codetable'>
  <tr>
    <td class='tdcodehead'>Code</td>
  </tr>
  <tr>
    <td class='tdcodebody'>
      <textarea class='codetextarea' contentEditable=false cols=60 rows=15 wrap=virtual>code code code</textarea></td>
    </tr>
</table><br>
<table class='quotetable' width='95%' border='0' cellpadding='3' cellspacing='1'>
  <tr>
    <td class='tdquotehead'>Quote</td>
  </tr>
  <tr>
    <td class='tdquote'>quote quote quote</td>
  </tr>
</table><br>
<b>bold text</b><br>
<i>italic</i><br>
<u>underlined</u><br>
link: <a class="txttohtmllink" href="http://www.bitrixsoft.com">http://www.bitrixsoft.com</a><br>
email: <a class="txttohtmllink" href="mailto:support@bitrixsoft.com">support@bitrixsoft.com</a>

CSS

The CSS is to be included prior to function call.

.quotetable, .codetable {width:90%}

.quotetable .tdquotehead,
.quotetable .tdquote,
.codetable  .tdcodehead,
.codetable  .tdcodebody,
.codetextarea {padding: 2px; font-family: Arial; font-size:12px; color:#000000}

.quotetable .tdquotehead,
.codetable  .tdcodehead {font-weight:bold}

.quotetable .tdquote,
.codetable  .tdcodebody {border: 1px solid Black}

.quotetable .tdquotehead,
.quotetable .tdquote,
.codetable  .tdcodehead,
.codetable  .tdcodebody,
.codetextarea {background-color: #FFFFFF}

.codetextarea {
  border: solid 0px;
  width: 100%;
  overflow: auto;
  scrollbar-shadow-color: #000000;
  scrollbar-arrow-color:  #000000;
  scrollbar-base-color:   #000000}

.codetextarea {
  scrollbar-face-color:       #FFFFFF;
  scrollbar-highlight-color:  #FFFFFF;
  scrollbar-track-color:      #FFFFFF;
  scrollbar-darkshadow-color: #FFFFFF}

Output result

text text text text
text text text text
longwordlongwordlongwordlon gword
Code

Quote
quote quote quote

bold text
italic
underlined
link: http://www.bitrixsoft.com
email: support@bitrixsoft.com


utf8win1251

string
utf8win1251(
  string text
)

The function utf8win1251 converts a string from UTF-8 to Windows 1251.

Parameters

Parameter | Description
text | Source string.

Example

<?
echo utf8win1251("битрикс");
// prints the string "bitrix"
?>


Date and time

The following functions are used with date, time and calendar.

Function | Description
Calendar | Returns HTML code of the icon that displays a standard calendar window if clicked.
CalendarDate | Returns HTML code of the icon that displays a standard calendar window if clicked. The date selected is then pasted in the specified form field.
CalendarPeriod | Returns the HTML code of two input fields with icons. Icons display a standard calendar window if clicked. The first field also has a drop-down list with values from 1 to 90. If a user selects a value in the list, the first input field is set to the current date less number of days selected.
ParseDateTime | Parses the specified date and time using the passed formatting rules.
ConvertDateTime | Takes the date and time specified in the format of the current site and converts it to an arbitrary format.
MakeTimeStamp | Converts the time passed in string to the Unix format.
ConvertTimeStamp | Converts time from the Unix format to string of the site format.
AddToTimeStamp | Adds the specified time span to a date in Unix format.
getmicrotime | Returns the current time in Unix format.

See Also

  • Using Date and Time
  • CDataBase date and time methods
  • CheckFilterDates


AddToTimeStamp

int
AddToTimeStamp(
 array add,
 int timestamp = false
)

The function AddToTimeStamp adds the specified time span to a date in Unix format.

Parameters

Parameter Description
add Array containing the time span. The following keys are possible:
  • DD - days;
  • MM - months;
  • YYYY - years;
  • HH - hours;
  • MI - minutes;
  • SS - seconds.
timestamp Time value in Unix format to which the time span is to be added.
Optional; the current time is used by default.

Return Values

Returns the resulting date in the Unix format.

See Also

  • MakeTimeStamp
  • ConvertTimeStamp

Example

$date = "07.04.2005 11:32:00";
echo "Original date: ".$date."<br>";

// obtain Unix timestamp from the source date
$stmp = MakeTimeStamp($date, "DD.MM.YYYY HH:MI:SS");

// add 1 day, 1 month, 1 year, 1 min and 1 sec
$arrAdd = array(
    "DD"	=> 1,
    "MM"	=> 1,
    "YYYY"	=> 1,
    "HH"	=> 1,
    "MI"	=> 1,
    "SS"	=> 1,
);
$stmp = AddToTimeStamp($arrAdd, $stmp);

// print the result
echo "Result: ".date("d.m.Y H:i:s", $stmp); // 07.03.2007 12:33:01
?>


Calendar

string
Calendar(
 string field,
 string form = "skform",
 string field_from = "",
 string field_to = ""
)

The function Calendar returns HTML code of the icon that displays a standard calendar window if clicked. The date selected is then pasted in the specified form field (or in two fields for intervals). Written in JavaScript.

Parameters

Parameter | Description
field | Name of the field that is to receive the selected date.
form | Name of the form containing the date field. Optional; a value of "skform" is used by default.
field_form | Name of the field that is to receive the first date of the selected date range. Optional; empty string by default.
field_to | Name of the field that is to receive the second date of the selected date range. Optional; empty string by default.

See Also

  • CalendarDate
  • CalendarPeriod

Example

<form action="<?=$APPLICATION->GetCurPage()?>" method="POST" name="curform">
<input type="text" class="typeinput" name="DATE" size="12">
<?=Calendar("DATE", "curform")?>
</form>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CalendarDate

string
CalendarDate(
 string field_name,
 string field_value,
 string form = "skform",
 string field_size = "10",
 string field_param = "class=\"typeinput\""
)

The function CalendarDate returns HTML code of the icon that displays a standard calendar window if clicked. The date selected is then pasted in the specified form field. Written in JavaScript.

Parameters

Parameter Description
field_name Name of the field:
<input type="text" name="field_name" ... >
field_value Input field initial value:
<input type="text" value="field_value" ... >
form Name of the form containing the date input field:
<form name="form">
Optional; the default value is "skform".
field_size Input field width:
<input type="text" size="field_size" ... >
Optional; the default value is "10".
field_param Additional attributes for the input field:
<input type="text" field_param ... >
Optional; the default value is class="typeinput".

See Also

  • Calendar
  • CalendarPeriod

Example

<form action="<?=$APPLICATION->GetCurPage()?>" method="POST" name="form1">
<?echo CalendarDate("birthdate", "25.11.1975", "form1", "15", "class=\"my_input\"")?>
</form>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CalendarPeriod

string
CalendarPeriod(
 string field_from_name,
 string field_from_value,
 string field_to_name,
 string field_to_value,
 string form = "skform",
 string select_enabled = "N",
 string select_param = "class=\"typeselect\"",
 string fields_param = "class=\"typeinput\"",
 string fields_size = "10"
)

The function CalendarPeriod returns the HTML code of two input fields with icons. Icons display a standard calendar window if clicked. The first field also has a drop-down list with values from 1 to 90. If a user selects a value in the list, the first input field is set to the current date less number of days selected. Written in JavaScript.

Parameters

Parameter Description
field_from_name Name of the field for the first date in range ("from"):
<input type="text" name="field_from_name" ... >
field_from_value Initial value of the first date in range ("from"):
<input type="text" value="field_from_value" ... >
field_to_name Name of the field for the second date in range ("till"):
<input type="text" name="field_to_name" ... >
field_to_value Initial value of the second date in range ("till"):
<input type="text" value="field_to_value" ... >
form Name of the form containing the input fields.
<form name="form">
Optional; a value of "skform" is used by default.
select_enabled If "Y", displays a list of days from 1 to 90, for quicker selection of the date.
Optional; the default value is "N" (hides the list).
select_param String with additional attributes of list of days:
<select name="field_from_name_DAYS_TO_BACK" select_param ... >
Optional; the default value is class="typeselect".
fields_param String with additional attributes of input fields:
<input type="text" fields_param ... >
Optional; the default value is class="typeinput".
fields_size Input field width:
<input type="text" size="fields_size" ... >
Optional; the default value is "10".

See Also

  • Calendar
  • CalendarDate

Example

<form action="<?=$APPLICATION->GetCurPage()?>" method="POST" name="form1">
<?echo CalendarPeriod("date_from", "25.10.2003", "date_to", "29.10.2003", "form1", "Y")?>
</form>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


ConvertDateTime

string
ConvertDateTime(
 string datetime,
 string format = FORMAT_DATETIME,
 mixed site_id = false
)

The function ConvertDateTime takes the date and time specified in the format of the current site and converts it to an arbitrary format.

Parameters

Parameter | Description
datetime | Date and time in the format of a site passed in site_id.
format Specifies the format to which the date and time are to be converted. The following specifies are possible:
  • YYYY - year;
  • MM - month;
  • DD - day;
  • HH - hours;
  • MI - minutes;
  • SS - seconds.
Optional. By default, the FORMAT_DATETIME constant value is used, which stores the time format of the site (or language for the administrative section).
site_id The site ID in whose format the datetime is specified.
Optional. The current site is used by default.

See Also

  • CSite::GetDateFormat
  • CDataBase::FormatDate

Example

<?
echo ConvertDateTime("25.12.2003", "YYYY-MM-DD", "ru"); // 2003-12-25
?>


ConvertTimeStamp

string
ConvertTimeStamp(
 int timestamp = false,
 string format_type = "SHORT",
 mixed site_id = false
)

The function ConvertTimeStamp converts time from the Unix format to a string in the site format.

Parameters

Parameter Description
timestamp Unix time.
Optional; current time is taken by default.
format_type Format type. The following values are possible:
  • FULL - full (date and time);
  • SHORT - short (date).
Optional; "SHORT" by default.
site_id The site ID in whose format the datetime is specified.
Optional. The current site is used by default.

See Also

  • MakeTimeStamp
  • AddToTimeStamp
  • CSite::GetDateFormat
  • CDataBase::DateFormatToPHP

Example

<?
echo "today:                ".ConvertTimeStamp();
echo "yesterday:            ".ConvertTimeStamp(time()-86400);
echo "day before yesterday: ".ConvertTimeStamp(time()-(86400*2));
?>
<?
echo ConvertTimeStamp(mktime(0, 0, 0, 10, 25, 2005), "SHORT", "com"); // 25.10.2005
?>


getmicrotime

float
getmicrotime()

The getmicrotime function returns the current time in Unix format.

Parameters

No parameters.

Example

<?
// Time benchmarking algorithm
$ptime = getmicrotime();

for ($i=0; $i<10000; $i++);

echo "Loop has taken ".round(getmicrotime()-$ptime, 3)." sec.";
?>


MakeTimeStamp

int
MakeTimeStamp(
 string datetime,
 string format = FORMAT_DATETIME
)

The function MakeTimeStamp converts the time to the Unix format.

Parameters

Parameter | Description
datetime | Time to convert.
format_type Format of the time in which the datetime is specified. The following specifies are possible:
  • YYYY - year;
  • MM - month;
  • DD - day;
  • HH - hours;
  • MI - minutes;
  • SS - seconds.
Optional. By default, the FORMAT_DATETIME constant value is used, which stores the time format of the site (or language for the administrative section).

See Also

  • ConvertTimeStamp
  • AddToTimeStamp
  • ParseDateTime

Example

<?
// set date
$date = "07.04.2005 11:32:00";

// convert to Unix-timestamp
if ($stmp = MakeTimeStamp($date, "DD.MM.YYYY HH:MI:SS"))
{
    // print the same date obtained
         // from Unix-timestamp
    echo date("d.m.Y H:i:s", $stmp);
}
else // if false returned...
{
    // print error msg
    echo "Date is incorrect!";
}
?>
<?
// print the date of information block activity
// in arbitrary format

// include the module
if (CModule::IncludeModule("iblock"))
{
    // select an element
    $rsElement = CIBlockElement::GetByID(32675);
    $arElement = $rsElement->Fetch();

    // obtain the activity date
    // in the current site format
    $date_active = $arElement["ACTIVE_FROM"]; // 28.01.2005

    // get the current site format
    $site_format = CSite::GetDateFormat(); // DD.MM.YYYY HH:MI:SS

    // convert to Unix format
    if ($stmp = MakeTimeStamp($date_active, $site_format))
    {
        // print the element activity date
        // in arbitrary format
        // using the PHP date function
        echo date("d F Y", $stmp); // 28 January 2005
    }
    else // failed
    {
        // print error msg
        ShowError("Date of element 32675 is incorrect!");
    }
}
?>


ParseDateTime

mixed
ParseDateTime(
 string datetime,
 string format = FORMAT_DATETIME
)

The function ParseDateTime parses the specified date and time using the passed formatting rules. Returns an array describing date and time according to the specified format, or false otherwise.

Parameters

Parameter | Description
datetime | Date and time in the format specified by format.
format Date and time format specifiers. Though the format is not strict, it is recommended to use system-wide specifiers:
  • YYYY - year;
  • MM - month;
  • DD - day;
  • HH - hours;
  • MI - minutes;
  • SS - seconds.
Optional. By default, the FORMAT_DATETIME constant value is used, which stores the time format of the site (or language for the administrative section).

See Also

  • CSite::GetDateFormat
  • CDatabase::DateFormatToPHP
  • CDatabase::FormatDate

Example

<?
$datetime = "21.01.2004 23:44:15";
$format = "DD.MM.YYYY HH:MI:SS";
echo "Source time: ".$datetime."<br>";
echo "Format:      ".$format."<hr>";
if ($arr = ParseDateTime($datetime, $format))
{
    echo "Day:     ".$arr["DD"]."<br>";
    echo "Month:   ".$arr["MM"]."<br>";
    echo "Year:    ".$arr["YYYY"]."<br>";
    echo "Hours:   ".$arr["HH"]."<br>";
    echo "Minutes: ".$arr["MI"]."<br>";
    echo "Seconds: ".$arr["SS"]."<br>";
}
else echo "Error!";
?>

<?
// display the date in the format "21 January, 2004"

// date in the format of the current site
$datetime = "21.01.2004";

// the constant FORMAT_DATETIME
// contains the time format of the current site
$arr = ParseDateTime($datetime, FORMAT_DATETIME);

// 21 January, 2004
echo $arr["DD"]." ".
     ToLower(GetMessage("MONTH_".intval($arr["MM"])."_S")).
     ", ".$arr["YYYY"];
?>

<?
// print the date of information block activity
// in arbitrary format

// include the module
if (CModule::IncludeModule("iblock"))
{
    // select an element
    $rsElement = CIBlockElement::GetByID(32675);
    $arElement = $rsElement->Fetch();

    // obtain the activity date
    // in the current site format
    $date_active = $arElement["ACTIVE_FROM"]; // 28.01.2005

    // get the current site format
    $site_format = CSite::GetDateFormat(); // DD.MM.YYYY HH:MI:SS

    // get an array with the activity date of the element
    if ($arr = ParseDateTime($date_active, $site_format))
    {
        /*
        $arr structure:
        Array
        (
            [DD] => 28
            [MM] => 1
            [YYYY] => 2005
            [HH] => 0
            [MI] => 0
            [SS] => 0
        )
        */

        // convert to Unix format
        $stmp = mktime(
            $arr["HH"], $arr["MI"], $arr["SS"],
            $arr["MM"], $arr["DD"], $arr["YYYY"]
            );

        // print the element activity date
        // in arbitrary format
        // using the PHP date function
        echo date("d F Y", $stmp); // 28 January 2005
    }
}
?>


Files and directories

The following functions are used with the site file system.

Function | Description
CheckDirPath | Checks if the path specified physically exists. Creates all directories of the path, if necessary.
CopyDirFiles | Copies files and directories.
DeleteDirFiles | Deletes duplicates of files from the directory which are also found in another.
DeleteDirFilesEx | Recursively deletes the directory or file specified.
RewriteFile | Writes a new content to file.
GetDirPath | Returns a parent directory of the specified file given the file path.
GetPagePath | Takes a file URL and converts it to a file path.
GetDirIndex | Returns the directory index file.

See Also

  • CFile class
  • Permissions distribution in Unix systems
  • New files and folders permissions


CheckDirPath

CheckDirPath(
 string abs_path,
 bool set_permissions = true
)

The function CheckDirPath checks if the path specified physically exists. Creates all directories of the path, if necessary.

Note!
The rights for directories which will be assigned by this function, must be preliminary defined in the BX_DIR_PERMISSIONS constant (in files /bitrix/php_interface/dbconn.php or /bitrix/php_interface/site ID/init.php). If the constant is not defined, it is automatically initialized with 0777, which will be further used for asigning Unix rights to files and directories.

Parameters

Parameter | Description
abs_path | Absolute path to the folder.
set_permissions | If set to "true" and the last directory of the path specified in parameter abs_path is not available for writing, the attempt to assign new rights to this directory will be made. The values of these rights will be taken from constant BX_DIR_PERMISSIONS. If the constant is not defined, a value of 0777 is used.

See Also

  • Permissions distribution in Unix systems
  • New files and folders permissions

Example

<?
// file /bitrix/php_interface/dbconn.php

// define constants for files and directories permissions
define("BX_FILE_PERMISSIONS", 0775);
define("BX_DIR_PERMISSIONS", 0775);
?>
<?
// Create a path "/temp/data/" starting from the root, if this path does not exist
CheckDirPath($_SERVER["DOCUMENT_ROOT"]."/temp/data");
?>


CopyDirFiles

bool
CopyDirFiles(
 string from,
 string to,
 bool rewrite = true,
 bool recursive = false,
 bool delete_after_copy = false,
 string exclude = ""
)

The function CopyDirFiles copies files and directories. Returns true on success, or false otherwise.

Parameters

Parameter | Description
from | Absolute path to a directory or file which is to be copied.
to | Absolute path to the destination directory. The path specified in this parameter will be checked by the function CheckDirPath.
rewrite | Determines whether to overwrite the existing files. Optional. True by default which means to overwrite.
recursive | Specifies to recursively copy all subdirectories and files of the path specified in the parameter from. Optional. False by default which means not to use recursion.
delete_after_copy | Specifies to delete the path passed in the parameter from after the copy (which in fact means moving directories and files). Optional. False by default which means not to delete.
exclude | If this parameter is not empty, files and folders having the name beginning with this parameter text are not to be copied.

See Also

  • CFile::CopyFile

Example

<?
// copy files from the folder /temp1/ to /temp2/
CopyDirFiles($_SERVER["DOCUMENT_ROOT"]."/temp1",
             $_SERVER["DOCUMENT_ROOT"]."/temp2");
?>


DeleteDirFiles

DeleteDirFiles(
 string check,
 string delete,
 array exclude = array()
)

The DeleteDirFiles function deletes duplicates of files from the directory delete which are also found in the directory check.

Parameters

Parameter | Description
check | Absolute path to the directory whose files are checked for existence.
delete | Absolute path to the directory in which duplicates of files found in the directory check are to be deleted.
exclude | An array of exclusions. Contains short names of files which are not to be deleted.

See Also

  • DeleteDirFilesEx
  • CFile::Delete

Example

<?
// delete all files from the folder /temp1/ which are also found in /temp2/,
// except index.php
DeleteDirFiles(
    $_SERVER["DOCUMENT_ROOT"]."/temp2",
    $_SERVER["DOCUMENT_ROOT"]."/temp1",
    array("index.php")
    );
?>


DeleteDirFilesEx

bool
DeleteDirFilesEx(
 string path
)

The function DeleteDirFilesEx recursively deletes the directory or file specified. Returns true on success.

Parameters

Parameter | Description
path | Path to the directory or file which is to be deleted, relative to the root.

See Also

  • DeleteDirFiles
  • CFile::Delete

Example

<?
// delete directory /temp1/ ant all its content
DeleteDirFilesEx("/temp1");
?>


GetDirIndex

string
GetDirIndex(
 string path,
 string index = false
)

The function GetDirIndex returns the name of a directory index file.

Parameters

Parameter | Description
path | Path to the directory relative to root to which an index file is to be returned.
index | Possible names of index files separated with spaces, in descending priority order. Important note If run under an Apache server, pass the DirectoryIndex field value of web server settings in this parameter. For IIS, this parameter can be found in the site properties, tab "Documents" -> "Enable default content page". Optional. False by default which means that the value is to be taken from the constant DIRECTORY_INDEX; if the constant is not defined the value "index.php index.html index.htm index.phtml default.html index.php3" is used by default.

The following algorithm is used to find a directory index file:

  1. A value from the parameter index is taken. If the parameter is not specified the value of the constant DIRECTORY_INDEX is taken. This constant can be defined in file /bitrix/php_interface/dbconn.php or in files /bitrix/php_interface/site ID/init.php. If the constant value is not specified the value "index.php index.html index.htm index.phtml default.html index.php3" is used by default.
  2. The obtained value is tokenized by spaces into separate file names.
  3. Each file is checked for existence in the directory.
  4. The first found file is considered the directory index page.

See Also

  • GetPagePath
  • CMain::GetCurPage
  • CMain::GetCurPageParam
  • CMain::GetCurUri


GetDirPath

string
GetDirPath(
 string path
)

The function GetDirPath returns a parent directory of the specified file given the file path.

Parameters

Parameter | Description
path | File path.

See Also

  • CMain::GetCurDir

Example

<?
echo GetDirPath("/temp1/data/file.php");
// prints the string "/temp1/data/"
?>


GetPagePath

string
GetPagePath(
 string page = false
)

The function GetPagePath returns path to the page relative to the root.

URL relative to root with parameters can be passed to the function. In this case, the function returns path to the page No parameters.

If a path without a file is passed to the function (for example: /en/about/), the function attempts to determine a directory index file. For example, if a directory index file is index.php, the return value is /en/about/index.php.

Note
The algorithm used to find an index file is outlined in the topic on the GetDirIndex function.

Parameters

Parameter | Description
page | Page whose path is to be returned. If false, the path to the current page is returned. Optional. False by default.

See Also

  • CMain::GetCurPage
  • CMain::GetCurPageParam
  • CMain::GetCurUri
  • GetDirIndex


RewriteFile

bool
RewriteFile(
 string abs_path,
 string content
)

The function RewriteFile writes a new content to file. Returns true on success, or false otherwise.

Parameters

Parameter | Description
abs_path | Absolute path to file which is to be overwritten.
content | New content of the file.

See Also

  • CFile::SaveFile
  • CMain::SaveFileContent

Example

<?
// overwrite file /en/index.php
$content = '
    <?
    require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
    $APPLICATION->SetTitle("Page header");
    ?>
    <?
    require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
    ?>
';
RewriteFile($_SERVER["DOCUMENT_ROOT"]."/en/index.php", $content);
?>


HTML Elements

The following functions are used with HTML.

Function | Description
InputType | Returns the HTML code of tags <input type="checkbox"> or <input type="radio">.
SelectBox | Returns the HTML code of tag <select> (drop-down single selection list) with options from the CDBResult object.
SelectBoxM | Returns the HTML code of the tag <select multiple> with options from the CDBResult object.
SelectBoxFromArray | Returns the HTML code of tag <select> built on the array data.
SelectBoxMFromArray | Returns the HTML code of the tag <select multiple> with options from the passed array.


InputType

string
InputType(
 string type,
 string name,
 string value,
 mixed checked,
 bool print_value = false,
 string title = "",
 string add_to_tag = ""
)

The function InputType returns the HTML code of tags <input type="checkbox"> or <input type="radio">.

Parameters

Parameter Description
type Type of the tag:
<input type="type" ... >

Possible values:
  • checkbox - non-exclusive multiple selection;
  • radio - exclusive single selection.
name Tag name:
<input name="name" ... >
value Tag values:
<input value="value" ... >
checked The value of this parameter is matched against the value of the parameter value. If the two values are equal, the control bocomes checked:
<input checked ... >
print_value If "true", the value of the parameter value is printed on the right of tag.
Optional; "false" by default.
title If print_value is not true and the title parameter is not empty, the title value is printed on the right of tag.
Optional. The default value is "".
add_to_tag Arbitrary HTML code to be added to tag:
<input add_to_tag ... >
Optional. The default value is "".

Example

<?
// Multiple selection

echo "Result:<pre>"; print_r($check); echo "</pre>";
echo "Select the desired options:<br>";
?>
<form action="" method="GET">
<?
echo "1:".InputType("checkbox", "check[]", "1", $check)."<br>";
echo "2:".InputType("checkbox", "check[]", "2", $check)."<br>";
echo "3:".InputType("checkbox", "check[]", "3", $check)."<br>";
?>
<br><input type="submit" value="OK">
</form>
<?
// Single selection

echo "Result: ".$radio."<br><br>";
echo "Select one of these:<br>";
?>
<form action="" method="GET">
<?
echo "1: ".InputType("radio", "radio", "1", $radio)."<br>";
echo "2: ".InputType("radio", "radio", "2", $radio)."<br>";
echo "3: ".InputType("radio", "radio", "3", $radio)."<br>";
echo "4: ".InputType("radio", "radio", "4", $radio)."<br>";
?>
<br><input type="submit" value="OK">
</form>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


SelectBox

string
SelectBox(
 string name,
 CDBResult values,
 string default = "",
 string selected = "",
 string add_to_tag = "class=\"typeselect\""
)

The function SelectBox returns the HTML code of tag <select> (drop-down single selection list) with options from the CDBResult object.

Parameters

Parameter | Description
name | Tag name: <select name="name" ... >
values | List items. An object of type CDBResult containing a set of records each having the following fields: "REFERENCE_ID" (list item value) and "REFERENCE" (list item text).
default | Title of the default item. This item has a value of "NOT_REF". Optional. The default value is "" (do not add this item).
selected | Selected item. The value of this parameter is matched against fields "REFERENCE_ID" of the values records. The field (list item) that is equal to selected becomes selected in the list. Optional. The default value is "".
add_to_tag | Arbitrary HTML code to be added to tag: <select add_to_tag ... > Optional. The default value is "class=\"typeselect\"".

See Also

  • SelectBoxFromArray

Example

<?
// create selection from the groups table
$strSql = "
    SELECT
        G.ID as REFERENCE_ID,
        G.NAME as REFERENCE
    FROM
        b_group G
    ";
$rs = $DB->Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);

// display the drop-down list
echo SelectBox("GROUP", $rs, "< select group >", $GROUP, "class =\"inputselect\"");
?>


SelectBoxFromArray

string
SelectBoxFromArray(
 string name,
 array values,
 string selected = "",
 string default = "",
 string add_to_tag = "class=\"typeselect\"",
 bool submit_form = false,
 string form_name = "form1"
)

The function SelectBoxFromArray returns the HTML code of tag <select> built on the array data.

Parameters

Parameter Description
name Tag name:
<select name="name" ... >
values List items. This array has the following format:
array(
    "REFERENCE" =>
        array(
            "Item title 1",
            "Item title 2",
            ...
            ),
    "REFERENCE_ID" =>
        array(
            "Item title 1",
            "Item title 2",
            ...
            )
    )
selected Selected item. The value of this parameter is matched against fields "REFERENCE_ID" of the values records. The field (list item) that is equal to selected becomes selected in the list.
Optional. The default value is "".
default Title of the default item. This item has a value of "NOT_REF".
Optional. The default value is "" (do not add this item).
add_to_tag Arbitrary HTML code to be added to tag:
<select add_to_tag ... >
Optional. The default value is "class=\"typeselect\"".
submit_form If "true", the form with name form_name submits data when selection changes (a user selects an item in the list).
Optional. The default value is false (do not submit).
form_name If submit_form == true, this parameter contains the name of the form containing the tag <select>.
Optional. The default value is "form1".

See Also

  • SelectBox

Example

<form name="form2" action="" method="GET">
<?
$arr = array(
    "REFERENCE" => // array of item titles
        array("Choice 1", "Choice 2", "Choice 3"),
    "REFERENCE_ID" => // array of item values
        array(1, 2, 3)
    );
echo SelectBoxFromArray("CHOICE", $arr, $CHOICE, "", "", true, "form2")
?>
</form>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


SelectBoxM

string
SelectBoxM(
 string name,
 CDBResult values,
 array selected,
 string top_element = "",
 bool select_top_element = false,
 int size = 5,
 string add_to_tag = "class=\"typeselect\""
)

The function SelectBoxM returns the HTML code of the tag <select multiple> with options from the CDBResult object.

Parameters

Parameter | Description
name | Tag name: <select name="name" ... >
values | List items. An object of type CDBResult containing a set of records each having the following fields: "REFERENCE_ID" (list item value) and "REFERENCE" (list item text).
selected | Selected items. The values of this array are matched against fields "REFERENCE_ID" of the values records. Fields (list items) that are equal to selected values becomes selected in the list. Optional. The default value is "".
top_element | Title of the top item in the list, optionally selectable (parameter select_top_element). This item has a value of "NOT_REF". Optional. The default value is "" (do not add).
select_top_element | If "true", the item top_element is always selected. Optional. The default value is false (do not select).
size | Value of the size tag: <select size="size" ... > This parameter contains the number of visible lines in the list. Optional. The default value is 5.
add_to_tag | Arbitrary HTML to add to the tag: <select add_to_tag ... > Optional. The default value is "class=\"typeselect\"".

See Also

  • SelectBoxMFromArray

Example

<?
// create selection from the groups table
$strSql = "
    SELECT
        G.ID as REFERENCE_ID,
        G.NAME as REFERENCE
    FROM
        b_group G
    WHERE
        G.ID<>2 -- group everybody containing all users by default
    ";
$rs = $DB->Query($strSql, false, "FILE: ".__FILE__."<br>LINE: ".__LINE__);

// display a list of groups
echo SelectBoxM("arrGROUP[]", $rs, $arrGROUP, "< group everybody >", true, 20,
"class =\"inputselect\"");
?>


SelectBoxMFromArray

string
SelectBoxMFromArray(
 string name,
 array values,
 array selected,
 string top_element = "",
 bool select_top_element = false,
 int size = 5,
 string add_to_tag = "class=\"typeselect\""
)

The function SelectBoxMFromArray returns the HTML code of the tag <select multiple> with options from the passed array.

Parameters

Parameter Description
name Tag name:
<select name="name" ... >
values List items. This array has the following format:
array(
    "REFERENCE" =>
        array(
            "Item title 1",
            "Item title 2",
            ...
            ),
    "REFERENCE_ID" =>
        array(
            "Item title 1",
            "Item title 2",
            ...
            )
    )
selected Selected item. The value of this parameter is matched against fields "REFERENCE_ID" of the values records. The field (list item) that is equal to selected becomes selected in the list.
Optional. The default value is "".
top_element Title of the top item in the list, optionally selectable (parameter select_top_element). This item has a value of "NOT_REF".

Optional. The default value is "" (do not add).
select_top_element If "true", the item top_element is always selected.

Optional. The default value is false (do not select).
size Value of the size tag:
<select size="size" ... >
This parameter contains the number of visible lines in the list.

Optional. The default value is 5.
add_to_tag Arbitrary HTML to add to the tag:
<select add_to_tag ... >

Optional. The default value is "class=\"typeselect\"".

See Also

  • SelectBoxM

Example

<?
$arr = array(
    "REFERENCE" => // array of item titles
        array("Choice 1", "Choice 2", "Choice 3"),
    "REFERENCE_ID" => // array of item values
        array(1, 2, 3)
    );
echo SelectBoxMFromArray("arrSEL[]", $arr, $arrSEL, "", false, 4,
"class =\"inputselect\"");
?>


Persistent filter and sorting

These functions are used to build and manage filters and sorting schemas.

Function | Description
InitFilterEx | Initialises the filter.
DelFilterEx | Deletes the filter.
GetFilterHiddens | Allows to create a number of hidden HTML form tags. The tags returned are built using variables whose names are passed in the array, or their prefix is specified in the mixed type parameter.
GetFilterParams | Returns the string containing the URL parameters from an array of variables or variables whose names start with the prefix specified.
CheckFilterDates | Checks if the two dates inputted in a filter are correct.
InitSorting | Initialises the sorting.
SortingEx | Generates sorting direction visual cues.


CheckFilterDates

CheckFilterDates(
 string date1,
 string date2,
 string &is_date1_wrong,
 string &is_date2_wrong,
 string &is_date2_less_date1
)

The function CheckFilterDates checks if the two dates are correct and compares them. Usually the function is used in filters to check if the inputted time interval is correct.

Parameters

Parameter | Description
date1 | The first date interval (from).
date2 | The second date interval (till).
is_date1_wrong | This parameter is a reference to an original variable. If it contains "Y" on return, the date specified in the parameter date1 is incorrect for the date format of the current site (language).
is_date2_wrong | This parameter is a reference to an original variable. If it contains "Y" on return, the date specified in the parameter date2 is incorrect for the date format of the current site (language).
is_date2_less_date1 | This parameter is a reference to an original variable. If it contains "Y" on return, the date specified in the parameter date1 is greater than that in date2, which is incorrect if a time interval is being specified.

See Also

  • CDataBase::IsDate
  • CDataBase::CompareDates

Example

<?
CheckFilterDates("10.01.2003", "15.02.2004", $date1_wrong, $date2_wrong, $date2_less);
if ($date1_wrong=="Y") echo "Incorrect format of the date1!!";
if ($date2_wrong=="Y") echo "Incorrect format of the date2!!";
if ($date2_less=="Y") echo "The date1 is greater than the date2!!";
?>


DelFilterEx

DelFilterEx(
 array vars,
 string id,
 bool session = true
)

The function DelFilterEx clears variables that contain filter values and clears corresponding session parameters.

Note
The function handles variables of the global scope. Take it into account when creating the main component files.

Parameters

Parameter | Description
vars | Array of filter variables names.
id | The filter ID identifying this filter in the session array: $_SESSION["SESS_ADMIN"][id].
session | Specifies to use the session. If true, the filter values will also be deleted from the session array $_SESSION["SESS_ADMIN"][id].

See Also

  • InitFilterEx

Example

<?
$FilterArr = Array(
    "find_id",
    "find_id_exact_match",
    );

// if "Set filter" is clicked...
if (strlen($set_filter)>0)
{
    // remember the filter values in the session
    InitFilterEx($FilterArr,"ADV_BANNER_LIST","set");
}
else
{
    // initialize the filter values from the session
    InitFilterEx($FilterArr,"ADV_BANNER_LIST","get");
}

// if "Reset filter" is clicked
if (strlen($del_filter)>0) DelFilterEx($FilterArr,"ADV_BANNER_LIST");

$arFilter = Array(
    "ID"                    => $find_id,
    "ID_EXACT_MATCH"        => $find_id_exact_match,
    );
$rsBanners = CAdvBanner::GetList($by, $order, $arFilter, $is_filtered);
?>


GetFilterHiddens

string
GetFilterHiddens(
 mixed var,
 array extra_vars = array("filter"=>"Y","set_filter"=>"Y")
)

The function GetFilterHiddens returns a number of hidden HTML form tags. The tags returned are built using variables whose names are passed in the array, or their prefix is specified in the mixed type parameter.

Parameters

Parameter | Description
var | Names of variables. This parameter allows either an array of variables names, or a string with prefix of the required variables.
extra_vars This parameter specifies an array of names and values of parameters to add to the result; array has the following format:
array("variable_name" => "variable_value")
This parameter is commonly used for passing the name and value of the button Set Filter.
Optional. The default value is array("filter" => "Y", "set_filter" => "Y").

See Also

  • GetFilterParams

Example

<form method="GET">
    <?
    // add a number of hidden tags whose names prefix is "filter_"
    // and values equal to the corresponding variables values
    echo GetFilterHiddens("filter_");
    ?>
    <input type="hidden" name="lang" value="<?echo LANGUAGE_ID?>">
    <input type="submit" name="Add" value="Add a new record&gt;">
</form>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetFilterParams

string
GetFilterParams(
 mixed var,
 bool safe_for_html = true,
 array extra_vars = array("filter"=>"Y","set_filter"=>"Y")
)

The function GetFilterParams returns the string containing the URL parameters from an array of variables or variables whose names begin with the prefix specified.

Parameters

Parameter | Description
var | Names of variables. This parameter allows either an array of variables names, or a string with prefix of the required variables.
safe_for_html | If set to "true", the result will be converted to the HTML safe format.
extra_vars This parameter specifies an array of names and values of parameters to add to the result; array has the following format:
array("variable_name" => "variable_value")
This parameter is commonly used for passing the name and value of the button Set Filter.
Optional. The default value is array("filter" => "Y", "set_filter" => "Y").

See Also

  • GetFilterHiddens

Example

<?
// This code builds a link allowing to
// open the page adv.php with the variables
// used to open the current page
// whose names have prefix "filter_"
?>
<a href="adv.php?id=<?echo $f_ID?>&<?echo GetFilterParams("filter_");?>">Modify</a>


InitFilterEx

InitFilterEx(
 array vars,
 string id,
 string action = "set",
 bool session = true
)

The function InitFilterEx initialises or stores the filter variables in the session.

Note
The function handles variables of the global scope. Take it into account when creating the main component files.

Parameters

Parameter | Description
vars | Array of filter variables names.
id | The filter ID identifying this filter in the session array: $_SESSION["SESS_ADMIN"][id].
action | Action to be performed: store or obtain filter values. If action is "set", the values of variables whose names were passed in the parameter vars will be copied to the session array $_SESSION["SESS_ADMIN"][id]. Otherwise, these variables will be initialised by the values stored in the session array $_SESSION["SESS_ADMIN"][id]. Optional. "set" by default.
session | Specifies to use the session. If set to true, the filter values will be stored in the session array $_SESSION["SESS_ADMIN"][id].

See Also

  • DelFilterEx

Example

<?
$FilterArr = Array(
    "find_id",
    "find_id_exact_match",
    );

// if "Set filter" is clicked...
if (strlen($set_filter)>0)
{
    // remember the filter values in the session
    InitFilterEx($FilterArr,"ADV_BANNER_LIST","set");
}
else
{
    // initialize the filter values from the session
    InitFilterEx($FilterArr,"ADV_BANNER_LIST","get");
}

// if "Reset filter" is clicked
if (strlen($del_filter)>0) DelFilterEx($FilterArr,"ADV_BANNER_LIST");

$arFilter = Array(
    "ID"                    => $find_id,
    "ID_EXACT_MATCH"        => $find_id_exact_match,
    );
$rsBanners = CAdvBanner::GetList($by, $order, $arFilter, $is_filtered);
?>


InitSorting

InitSorting(
 mixed page = false,
 string by_var = "by",
 string order_var = "order"
)

The function InitSorting initialises parameters of sorting stored in the session, if the sorting was not explicitly specified. If the sorting is explicitly specified the function stores parameters of sorting in the session.

Note
The function handles variables of the global scope. Take it into account when creating the main component files.

Parameters

Parameter | Description
page | A page for which the sorting is initialised. The false value initialises sorting for the current page. Optional. False by default.
by_var | The name of a variable in which the sorting field ID is passed. Optional. The default value is "by".
order_var | The name of a variable containing the sorting direction: "asc" (ascending) or "desc" (descending). Optional. "order" by default.

See Also

  • SortingEx

Example

<?
// if variables $by and $order are explicitly specified, their values are stored in the session
// otherwise they are initialised with values stored in the session
InitSorting();
$rsUsers = CUser::GetList($by, $order);
?>
<table>
    <tr>
        <td>ID<br><?=SortingEx("s_id")?></td>
        <td>Login<br><?=SortingEx("s_name")?></td>
    </tr>
    ...
</table>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


SortingEx

string
SortingEx(
 string by,
 mixed page = false,
 string by_var = "by",
 string order_var = "order",
 string anchor = "nav_start"
)

The function SortingEx returns HTML code used to display sorting direction visual cues. Usually, the function is used in a table header.

Parameters

Parameter | Description
by | Value which will be passed to the variable by_var. Usually, the sorting field ID is specified in this parameter.
page | A page URL (with all parameters) to which a link on a sorting direction arrow will be built. Optional. False by default which means that the current page is used.
by_var | Name of a variable to receive a value of the parameter by. Optional. The default value is "by".
order_var | The name of a variable containing the sorting direction: "asc" (ascending) or "desc" (descending). Optional. "order" by default.
anchor | An anchor to which a page will be scrolled in browser after setting the sorting. Optional. "nav_start" by default.

See Also

  • InitSorting

Example

<table>
    <tr>
        <td>ID<br><?=SortingEx("s_id")?></td>
        <td>Header<br><?=SortingEx("s_name")?></td>
    </tr>
    <tr>
        <td>1</td>
        <td>Element header</td>
    </tr>
</table>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Modules functions

The following are the modules functions.

Function | Description
AddEventHandler | Registers an event handler with a module.
CheckVersion | Compares versions.
ExecuteModuleEvent | Runs an event handler.
GetModuleEvents | Returns a list of event handlers for a module.
GetModuleID | Returns the ID of the module to which the specified file belongs.
IsModuleInstalled | Checks whether a module is installed or not.
RegisterModule | Registers the specified module in the system.
RegisterModuleDependences | Register an event handler.
UnRegisterModule | Deletes a registration entry and all the module settings from the database.
UnRegisterModuleDependences | Unregisters an event handler.

See Also

  • Modules explained
  • CModule class


AddEventHandler

AddEventHandler(
 string from_module_id,
 string event_id,
 mixed callback,
 int sort = 100,
 mixed full_path = false
);

The function AddEventHandler registers an event handler (callback) of an event event_id with the module from_module_id. If a full path to the file containing the handler is specified (full_path), the file will be included before calling the handler.

Parameters

Parameter | Description
from_module_id | The ID of the module whose event is to be processed.
event_id | The event ID.
callback | The user defined event handler function. If a class method is to be passed in this parameter, pass an array in the format Array(class(object), method name) here.
sort | Order in which the registered handler is to be called (more than one handler can be registered for an event). Optional, 100 by default.
full_path | Full path to the file which is to be included upon event before calling the handler callback.

See Also

  • Modules interrelationship
  • RegisterModuleDependences

Example

<?
// file /bitrix/php_interface/init.php
AddEventHandler("main", "OnBeforeUserLogin", Array("MyClass", "BeforeLogin"));
class MyClass
{
  function BeforeLogin(&$arFields)
  {
        if(strtolower($arFields["LOGIN"])=="guest")
        {
            global $APPLICATION;
            $APPLICATION->throwException("User with login "Guest" cannot be authorised.");
            return false;
        }
  }
}
?>


CheckVersion

bool
CheckVersion(
 string version1,
 string version2
)

The function CheckVersion compares versions in the format XX.XX.XX. Returns true, is the version number passed in version1 is greater or equal to the second version number passed version2, or false otherwise.

Parameters

Parameter | Description
version1 | First version to be compared in the format "XX.XX.XX"
version2 | Second version to be compared in the format "XX.XX.XX"

Example

<?
$ver1 = "3.0.15";
$ver2 = "4.0.0";

$res = CheckVersion($ver1, $ver2);

echo ($res) ? $ver1." >= ".$ver2 : $ver1." < ".$ver2;

// output: 3.0.15 < 4.0.0
?>


ExecuteModuleEvent

mixed
ExecuteModuleEvent(
 array event,
 mixed param1 = NULL,
 mixed param2 = NULL,
 mixed param3 = NULL,
 mixed param4 = NULL,
 mixed param5 = NULL,
 mixed param6 = NULL,
 mixed param7 = NULL,
 mixed param8 = NULL,
 mixed param9 = NULL,
 mixed param10 = NULL
)

The function ExecuteModuleEvent runs an event handler. Returns the return value of an event handler.

Parameters

Parameter Description
event Array describing one record containing a link between an event and an event handler. Such records are stored in table b_module_to_module. The following keys are possible.
  • ID - record ID;
  • TIMESTAMP_X - date of record modification;
  • SORT - sorting;
  • FROM_MODULE_ID - the module that initialises an event;
  • MESSAGE_ID - event ID;
  • TO_MODULE_ID - the module containing an event handler;
  • TO_CLASS - class with an event handler;
  • TO_METHOD - class method which is the handler itself.
param1,
param2,
... ,
param10 		Arbitrary values to be passed to an event handler.

See Also

  • GetModuleEvents

Example

<?
// check if the forum can be deleted

// the flag that allows or disallows deleting a forum
$bCanDelete = true;

// obtain data on all handlers of "OnBeforeForumDelete" event
// that belongs to the Forum module
$rsEvents = GetModuleEvents("forum", "OnBeforeForumDelete");
while ($arEvent = $rsEvents->Fetch())
{
    // run the scheduled handler of "OnBeforeForumDelete"
    // if false is returned...
    if (ExecuteModuleEvent($arEvent, $del_id)===false)
    {
        // cannot delete forum
        $bCanDelete = false;
        break;
    }
}
?>


GetModuleEvents

CDBResult
GetModuleEvents(
 string module_id,
 string event_id
)

The function GetModuleEvents returns a list of event_id handlers for the module_id as the CDBResult object.

Parameters

Parameter | Description
module_id | The module ID.
event_id | The event ID.

See Also

  • ExecuteModuleEvent

Example

<?
// check if the forum can be deleted

// the flag that allows or disallows deleting a forum
$bCanDelete = true;

// obtain data on all handlers of "OnBeforeForumDelete" event
// that belongs to the Forum module
$rsEvents = GetModuleEvents("forum", "OnBeforeForumDelete");
while ($arEvent = $rsEvents->Fetch())
{
    // run the scheduled handler of "OnBeforeForumDelete"
    // if false is returned...
    if (ExecuteModuleEvent($arEvent, $del_id)===false)
    {
        // cannot delete forum
        $bCanDelete = false;
        break;
    }
}
?>


GetModuleID

string
GetModuleID(
 string path
)

The function GetModuleID returns the identifier of the module to which the specified file belongs.

Parameters

Parameter | Description
path | Path to a file in /bitrix/modules/.

Example

<?
echo GetModuleID("/bitrix/modules/main/include.php"); // main
?>


IsModuleInstalled

bool
IsModuleInstalled(
 string module_id
)

The function IsModuleInstalled checks whether a module is installed or not. Returns true if the specified module is installed, or false otherwise.

Note
Before using a module functions and classes, include it by a call to CModule::IncludeModule.

Parameters

Parameter | Description
module_id | The module ID.

See Also

  • CModule::IsInstalled
  • CModule::IncludeModule

Example

<?
if (IsModuleInstalled("iblock")):

    echo "The Information Blocks module is installed";

endif;
?>


RegisterModule

RegisterModule(
 string module_id
)

The function RegisterModule registers the specified module in the system. Module registration is the essential part of a module installation.

Parameters

Parameter | Description
module_id | The module ID.

See Also

  • UnRegisterModule
  • CModule::DoInstall

Example

<?
// file /bitrix/modules/statistic/install/step2.php
RegisterModule("statistic");
?>


RegisterModuleDependences

RegisterModuleDependences(
 string from_module_id,
 string event_id,
 string to_module_id,
 string to_class = "",
 string to_method = "",
 int sort = 100
)

The function RegisterModuleDependences register an event handler.

Parameters

Parameter | Description
from_module_id | The ID of the module whose event is to be processed.
event_id | The event ID.
to_module_id | The ID of the module containing an event handler.
to_class | Name of a class from the module, whose method is the event handler. Optional. The default value is "" (which tells to include file /bitrix/modules/to_module_id/include.php).
to_method | Method of a class to_class which is the event handler itself. Optional. The default value is "" (which tells to include file /bitrix/modules/to_module_id/include.php).
sort | Order in which the registered handler is to be called (more than one handler can be registered for an event). Optional, 100 by default.

See Also

  • Modules interrelationship
  • RegisterModuleDependences

Example

<?
// To clean a forum data after the site deletion,
// register a handler of "OnUserDelete" event
// of the "main" (Kernel) module.
// The event handler if the method CForum::OnUserDelete
// of the Forum module.

RegisterModuleDependences("main", "OnUserDelete", "forum", "CForum", "OnUserDelete");
?>


UnRegisterModule

UnRegisterModule(
 string module_id
)

The function UnRegisterModule deletes a registration entry and all the module settings from the database. Module unregistration is the essential part of a module uninstallation.

Parameters

Parameter | Description
module_id | The module ID.

See Also

  • RegisterModule
  • CModule::DoUninstall

Example

<?
// file /bitrix/modules/statistic/install/unstep2.php
UnRegisterModule("statistic");
?>


UnRegisterModuleDependences

UnRegisterModuleDependences(
 string from_module_id,
 string event_id,
 string to_module_id,
 string to_class = "",
 string to_method = ""
)

The function UnRegisterModuleDependences unregisters an event handler.

Parameters

Parameter | Description
from_module_id | The ID of the module whose events are processed.
event_id | The event ID.
to_module_id | The ID of the module containing an event handler.
to_class | Name of a class from the module, whose method is the event handler. Optional. The default value is "".
to_method | Method of a class to_class which is the event handler itself. Optional. The default value is "".

See Also

  • Modules interrelationship
  • RegisterModuleDependences

Example

<?
UnRegisterModuleDependences("main",
                            "OnUserDelete",
                            "forum",
                            "CForum",
                            "OnUserDelete");
?>


Language files functions

The system API includes the following functions used to manage language files.

Function | Description
GetMessage | Retrieves a message text by the message ID. The message returned is in the current language.
IncludeModuleLangFile | Includes a language file into the calling script file.
IncludeTemplateLangFile | Includes a language file into script files of component.

See Also

  • Languages


GetMessage

string
GetMessage(
 string message_id
)

The function GetMessage retrieves a message text by the message ID. The message returned is in the current language. The language files are used to assign message ID's to message text. A corresponding language file should be included prior to calling this function.

Parameters

Parameter | Description
message_id | The message ID.

See Also

  • IncludeModuleLangFile
  • IncludeTemplateLangFile

Example

<?
IncludeTemplateLangFile(__FILE__);
echo GetMessage("SOME_MESSAGE_CODE");
?>


IncludeModuleLangFile

IncludeModuleLangFile(
 string abs_path,
 string lang = false
)

The function IncludeModuleLangFile includes a language file into the calling script file. This function is usually used to connect language files to modules.

The included language file must have the same name as the script file from which the function is called. The included language file must reside in the following directory: /bitrix/modules/module ID/lang/language ID/file path relative to the module root

Parameters

Parameter | Description
abs_path | Absolute path to file for which the language message file is to be included.
lang | The language ID. Optional. By default, the current language is used (false).

See Also

  • Language files explained
  • Module language files
  • IncludeTemplateLangFile

Example

<?
// Include language file into the current script
IncludeModuleLangFile(__FILE__);
?>


IncludeTemplateLangFile

IncludeTemplateLangFile(
 string abs_path,
 string lang = false
)

The function IncludeTemplateLangFile includes a language file into scripts which are located in the current site template folder. This function is usually used with components, or the site prologue or epilogue.

The function searches for the language file in the following locations.

  1. First, the language file is presumed to be stored in the folder:

    /bitrix/templates/current site template ID/lang/language ID/relative path to script

  2. If the file is not found, the function tries the following folder:

    /bitrix/templates/.default/lang/language ID/relative path to script

  3. If the file is still not found, the module installation folder is searched:

    /bitrix/modules/module ID/install/templates/lang/language ID/relative path to script

Commonly, a "relative path to script" is the path to file relative to folder /bitrix/templates/current site template ID/.

Particularly, when including components, "relative path to script" is the component inclusion path passed to the method CMain::IncludeFile as the first parameter.

Parameters

Parameter | Description
abs_path | Absolute path to file for which the language message file is to be included.
lang | The language ID. Optional. By default, the current language is used (false).

See Also

  • Language files explained
  • Module language files
  • IncludeModuleLangFile

Example

<?
// Include language file into the current component
// The language file is assumed to be stored in standard location
IncludeTemplateLangFile(__FILE__);
?>


Debugging functions

The Bitrix Site Manager system contains the following functions which can be used for debugging.
Function | Description
AddMessage2Log | Adds a new record to the log file.
SendError | Sends an error report via the e-mail.
mydump | Returns a string containing the variable or class instance dump.

See Also

  • Special debugging variables


AddMessage2Log

AddMessage2Log(
 string text,
 string module_id = ""
)

The function AddMessage2Log adds a new record to the log file.

The constant LOG_FILENAME containing the absolute path to the log file should be defined prior to calling this function. If you fail to define the constant, the function does not perform any operation. The constant LOG_FILENAME can be defined in the beginning of a page or in one of the following files:

  • /bitrix/php_interface/dbconn.php
  • /bitrix/php_interface/site ID/init.php

If an error occurs, the function AddMessage2Log is called by the following methods:

  • CDataBase::Query
  • CDataBase::QueryBind
  • CDataBase::QueryBindSelect

Note
The log file accumulates all records added to it. To clean the log file, simply delete it.

Note
You can dump all database queries for debugging purposes. To do so, initialise the variable $DBDebugToFile with true in the file /bitrix/php_interface/dbconn.php.

Parameters

Parameter | Description
text | Message text.
module_id | The module ID whose message is added. Optional, "" by default.

See Also

  • Special debugging variables

Example

<?
// file /bitrix/php_interface/dbconn.php

// define LOG_FILENAME, set it to the log file pathname
define("LOG_FILENAME", $_SERVER["DOCUMENT_ROOT"]."/log.txt");
?>
<?
// add message to log
AddMessage2Log("My message", "my_module_id");
?>
<?
// issue an incorrect SQL query
$DB->Query("SELECT");
// the script is halted and an error message is added to log
?>


mydump

string
mydump(
 mixed var,
 int max_depth = -1,
 int depth = 0
)

The function mydump returns a string containing the variable or class instance dump.

Parameters

Parameter | Description
var | Variable whose dump is to be obtained.
max_depth | Maximum number of recursive calls of the function. Useful when generating a dump of complex arrays or deeply nested objects. Optional. By default, the depth level is not limited (-1).
depth | Initial value of the nesting level counter (recursive calls counter) Optional. By default, the first level is implied (0).

Example

<?
// create a dumpf of a CUser instance
echo "<pre>";
echo mydump($USER);
echo "</pre>";
?>

Sample output

<?
 object(cuser) =>
  method(0) => Array[0]
  method(1) => Array[1]
  method(2) => Array[2]
  method(3) => Array[3]
  method(4) => Array[4]
  method(5) => Array[5]
  method(6) => Array[6]
  method(7) => Array[7]
  method(8) => Array[8]
  method(9) => Array[9]
  method(10) => Array[10]
  method(11) => Array[11]
  method(12) => Array[12]
  method(13) => Array[13]
  method(14) => Array[14]
  method(15) => Array[15]
  method(16) => Array[16]
  method(17) => Array[17]
  method(18) => Array[18]
  method(19) => Array[19]
  method(20) => Array[20]
  method(21) => Array[21]
  method(22) => Array[22]
  method(23) => Array[23]
  method(24) => Array[24]
  method(25) => Array[25]
  method(26) => Array[26]
  method(27) => Array[27]
  method(28) => Array[28]
  method(29) => Array[29]
  method(30) => Array[30]
  method(31) => Array[31]
  method(32) => Array[32]
  method(33) => Array[33]
  method(34) => Array[34]
  method(35) => Array[35]
  method(36) => Array[36]
  method(37) => Array[37]
  method(38) => Array[38]
  method(39) => Array[39]
  method(40) => Array[40]
  method(41) => Array[41]
  method(42) => Array[42]
  method(43) => Array[43]
  method(44) => Array[44]
  method(45) => Array[45]
  method(46) => Array[46]
  method(47) => Array[47]
  method(48) => Array[48]
  method(49) => Array[49]
  method(50) => Array[50]
  method(51) => Array[51]
  method(52) => Array[52]
  method(53) => Array[53]
  method(54) => Array[54]
  method(55) => Array[55]
  default => result =>
         NULL()  default => arResult =>
         NULL()  default => bNavStart =>
         boolean(true)  default => bShowAll =>
         boolean(true)  default => NavNum =>
         NULL()  default => NavPageCount =>
         NULL()  default => NavPageNomer =>
         NULL()  default => NavPageSize =>
         NULL()  default => NavShowAll =>
         NULL()  default => NavRecordCount =>
         NULL()  default => bFirstPrintNav =>
         boolean(true)  default => PAGEN =>
         NULL()  default => SIZEN =>
         NULL()  default => bFromArray =>
         boolean(true)  default => bFromLimited =>
         boolean(true)  default => sSessInitAdd =>
         string(0) =>
        ""
  default => nPageWindow =>
         integer(11)  default => nSelectedCount =>
         boolean(true)  default => SESS_AUTH =>
         NULL()  default => LAST_ERROR =>
         string(0) =>
        ""
  result =>
         NULL()  arResult =>
         NULL()  bNavStart =>
         boolean(true)  bShowAll =>
         boolean(true)  NavNum =>
         NULL()  NavPageCount =>
         NULL()  NavPageNomer =>
         NULL()  NavPageSize =>
         NULL()  NavShowAll =>
         NULL()  NavRecordCount =>
         NULL()  bFirstPrintNav =>
         boolean(true)  PAGEN =>
         NULL()  SIZEN =>
         NULL()  bFromArray =>
         boolean(true)  bFromLimited =>
         boolean(true)  sSessInitAdd =>
         string(0) =>
        ""
  nPageWindow =>
         integer(11)  nSelectedCount =>
         boolean(true)  SESS_AUTH =>
         array(10) =>
         [AUTHORIZED] =>
             string(1) =>
            "Y"
         [USER_ID] =>
             string(1) =>
            "2"
         [LOGIN] =>
             string(5) =>
            "nessy"
         [EMAIL] =>
             string(15) =>
            "nessy@bitrix.com"
         [PASSWORD_HASH] =>
             string(32) =>
            "fc0b9bd428702e477fb6a6fbc3da211c"
         [NAME] =>
             string(14) =>
            "Vitaly Kaplich"
         [FIRST_NAME] =>
             string(6) =>
            "Vitaliy"
         [LAST_NAME] =>
             string(7) =>
            "Kaplich"
         [GROUPS] =>
             array(3) =>
             [0] =>
                 integer(2)             [1] =>
                 integer(1)             [2] =>
                 integer(3)         [ADMIN] =>
             boolean(true)  LAST_ERROR =>
         string(0) =>
        ""
?>


SendError

SendError(
 string text,
 string module_id = ""
)

The function SendError sends an error report via the e-mail.

The constant ERROR_EMAIL containing the e-mail address of error message. If you fail to define the constant, the function does not perform any operation. The constant ERROR_EMAIL can be defined in the beginning of a page or in one of the following files:

  • /bitrix/php_interface/dbconn.php
  • /bitrix/php_interface/site ID/init.php

The sent message includes the following information in addition to error description:

  • HTTP_GET_VARS - array of variables found in the HTTP GET request;
  • HTTP_POST_VARS - array of variables found in the HTTP POST request;
  • HTTP_COOKIE_VARS - array of client variables (cookies);
  • HTTP_SERVER_VARS - array of common server variables.

If an error occurs, the function SendError is called by the following methods:

  • CDataBase::Connect
  • CDataBase::Query
  • CDataBase::QueryBind
  • CDataBase::QueryBindSelect
  • CDBResult::Fetch (Oracle version only).

Parameters

Parameter | Description
text | Message text.
module_id | The module ID whose message is to be sent. Optional, "" by default.

Example

<?
// file /bitrix/php_interface/dbconn.php

// define ERROR_EMAIL with the administrator e-mail
define("ERROR_EMAIL", "admin@site.com");
?>
<?
SendError("Message!");
?>


Other functions

Function | Description
check_email | Checks an e-mail address for syntax validity.
FindUserID | Emits the code of HTML elements allowing to enter a user ID and obtain details on a user.
LocalRedirect | Performs the client browser redirect to the specified page.
QueryGetData | Queries the specified web address using the HTTP protocol.
GetWhoisLink | Returns a link to one of the Whois servers used to obtain information on the specified IP address.
DeleteParam | Builds a parameter string from the $HTTP_GET_VARS array, deleting parameters with names specified.
InitURLParam | Initialises variables and arrays with parameters passed in an URL.
IsIE | Returns true if the current client browser is "MS Internet Explorer".
Rel2Abs | Returns path that is relative to the specified directory.
BXClearCache | Deletes all or expired cache files on the specified path.
GetCountryByID | Returns the name of the specified country in the specified language.
GetCountryArray | Returns a sorted array of countries whose names are returned in the specified language.
ShowError | Emits the error message.
ShowNote | Emits a message.
ShowMessage | Used to emit error descriptions and other messages.


BXClearCache

bool
BXClearCache(
 bool delete_all = false,
 string dir = ""
)

The function BXClearCache deletes all or expired cache files on the specified path. Returns true on success, or false otherwise.

Parameters

Parameter | Description
delete_all | If set to "true", the function deletes all cache files. A value of false tells to delete the expired files only.
dir | Starting directory for processing. Used for partial clean-up. Should be specified relative to the cache root folder: /bitrix/cache/.

Example

<?
// delete all cache files from folder /forum/
BXClearCache(true, "/forum/");
?>


check_email

bool
check_email(
  string email
)

The function check_email checks an e-mail address for syntax validity. Returns true if the address specified is valid, or false otherwise.

Parameters

Parameter | Description
email | e-mail address to be verified..

Example

<?
echo (check_email("Bitrix <admin@bitrix.com>")) ? "OK!" : "Error!"; // OK
echo (check_email("admin@bitrix.com")) ? "OK!" : "Error!"; // OK
echo (check_email("admin@bi$trix.com")) ? "OK!" : "Error!"; // ERROR
?>


DeleteParam

string
DeleteParam(
 array remove_params
)

The function DeleteParam builds a parameter string from the $HTTP_GET_VARS array, deleting parameters with names specified in remove_params.

Parameters

Parameter | Description
remove_params | Array of parameter names which are to be excluded from the result string.

Example

<?
// Make a link to a page
// with all current parameters GET,
// replace (or add if absent)
// parameters "page" and "order"
?>
<a href="page.php?page=1&order=asc&<?=DeleteParam(array("page","order"))?>">link</a>


FindUserID

bool
FindUserID(
 string tag_name,
 string tag_value
 string user_name = "",
 string form_name = "form1",
 string tag_size = "3",
 string tag_maxlength = "",
 string button_title = "...",
 string tag_class = "typeinput",
 string button_class = "tablebodybutton",
 string search_page = "/bitrix/admin/user_search.php"
)

The function FindUserID emits the code of HTML elements allowing to enter a user ID and obtain details on a user. A button linked to a user search page is also displayed.

Parameters

Parameter | Description
tag_name | Name of the field used to enter a user ID: <input type="text" name="tag_name" ...>
tag_value | Value of the field used to enter a user ID: <input type="text" value="tag_value" ...>
user_name | The ID, login, first and last names of a user which are displayed near the ID entry field when a page loads. Optional. The default value is "".
form_name | Name of the form containing the user ID entry field. Optional. The default value is "form1".
tag_size | Width of the field used to enter a user ID: <input type="text" size="tag_size" ...> Optional. The default value is "3".
tag_maxlength | Maximum number of symbols in the field used to enter a user ID: <input type="text" maxlength="tag_maxlength" ...> Optional. The default value is "" (unlimited).
button_title | Title of the button linked to the user search page: <input type="button" value="button_title" ...> Optional. The default value is "..." (unlimited).
tag_class | CSS class for the field used to enter a user ID: <input type="input" class="tag_class" ...> Optional. The default value is "typeinput".
button_class | CSS class of the user search page button: <input type="button" class="button_class" ...> Optional. The default value is "tablebodybutton".
search_page | Path relative to the root to the user search page. Optional. The default value is "/bitrix/admin/user_search.php" (administrative section).

Example

<form name="form1">
<?
$name = "[<a href=\"/bitrix/admin/user_edit.php?lang=".LANGUAGE_ID."&ID=".
$USER_ID."\">".$USER_ID."</a>] (".$LOGIN.") ".$NAME;

echo FindUserID("USER_ID", $USER_ID, $name,
"form1", "3", "", "...", "inputtext", "inputbodybutton");
?>
</form>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetCountryArray

array
GetCountryArray(
 string language_id = LANGUAGE_ID
)

The function GetCountryArray returns an array of countries whose names are returned in the specified language. The array is returned in format allowing to pass it to functions SelectBoxFromArray, SelectBoxMFromArray without additional processing.

Note
Array of countries is specified in files /bitrix/modules/main/lang/language_id/tools.php.

Parameters

Parameter | Description
language_id | The ID of the language in which the countries names are to be returned. Optional. The default value is LANGUAGE_ID (current).

Example of a returned array

Array
(
    [reference_id] => Array
        (
            [0] => 16
            [1] => 17
            [2] => 2
            [3] => 18
            ...
        ),
    [reference] => Array
        (
            [0] => Australia
            [1] => Austria
            [2] => Azerbaijan
            [3] => Albania
            ...
        )
)

Example:

<?
// display a drop-down list of countries
echo SelectBoxFromArray(
    "COUNTRY_ID",
    GetCountryArray(),
    $COUNTRY_ID,
    "< select country >"
    );
?>


GetCountryByID

string
GetCountryByID(
 int country_id,
 string language_id = LANGUAGE_ID
)

The function GetCountryByID returns the name of the specified country by its ID.

Note
You can view the country ID's in file /bitrix/modules/main/lang/language_id/tools.php.

Parameters

Parameter | Description
country_id | The country numeric ID.
language_id | The ID of the language in which the country name is to be returned. Optional. The default value is LANGUAGE_ID (current).

Example

<?
echo GetCountryByID(34, "en"); // Brazil
?>


GetWhoisLink

string
GetWhoisLink(
  string ip,
  string link_class = "tablebodylink"
)

The function GetWhoisLink returns a link to one of the Whois servers used to obtain information on the specified IP address.

The link format is as follows:
<a href="http://www.whois.sc/ip" class="link_class">ip</a>

Parameters

Parameter | Description
ip | The IP address in the format XXX.XXX.XXX.XXX for which the link is to be created.
link_class | CSS class of the link.

Example

<?
echo GetWhoisLink("210.49.16.111");
?>


InitURLParam

string
InitURLParam(
 mixed url = false
)

The function InitURLParam initialises variables and arrays $_GET, $HTTP_GET_VARS, $_REQUEST, $GLOBALS with parameters passed in url.

Note
This function is commonly used in the 404 error handler if variables passed on URL are required. Such handlers are used to develop the 404 services, allowing to create addressed which are more friendly to search engines.

Parameters

Parameter | Description
url | URL whose parameters are to be initialised. Optional; false by default (current page).

Example

<?
InitURLParam("/en/index.php?ID=2&A=123");
// initialise$ID=2 and $A=123
// and the corresponding keys of arrays $_GET, $HTTP_GET_VARS, $_REQUEST, $GLOBALS
?>


IsIE

bool
IsIE()

The IsIE function returns true if the current client browser is "MS Internet Explorer", or false otherwise.

Parameters

No parameters.

Example

<?
if (IsIE())
    echo "You are running MS Internet Explorer";
?>


LocalRedirect

LocalRedirect(
 string url
)

The function LocalRedirect performs the client browser redirect to the specified page.

Note
In the administrative section, redirects can only be used before any content is outputted (before inclusion of prolog_admin_after.php or prolog_admin.php). The public section does not apply restrictions on redirects .

Parameters

Parameter | Description
url | URL to which the browser is to be redirected. Both relative and absolute URL's are accepted in this parameter. Absolute URL's should be of one of the following protocols: "http://", "https://", "ftp://".

Example

<?
// fully qualified URL to another site
LocalRedirect("http://www.bitrixsoft.com/");

// relative to the current site roor
LocalRedirect("/en/index.php");

// relative path to a file in the current folder of the current site
LocalRedirect("index.php");
?>


QueryGetData

string
QueryGetData(
  string site,
  int port,
  string page,
  string query,
  int &error_number,
  string &error_text,
  string http_method = "GET",
  string site_prefix = ""
)

The function QueryGetData queries the specified web address using the HTTP protocol. Returns the server response body without header. If an error occurres, the function returns an empty string and set parameters error_number and error_text.

Parameters

Parameter | Description
site | Address of the site to query.
port | Port number. Usually 80.
page | Path to the requested page.
query | String with the query parameters in the common format.
error_number | Reference to a variable that receives the error number on failure.
error_text | Reference to a variable that receives the error description on failure.
http_method Method to use for querying the remote server. The following values are possible:
  • "GET"
  • "POST"
Optional; GET by default.
site_prefix Site address prefix for work through SSL or TLS. The following values are possible:
  • ""
  • "ssl://"
  • "tls://"
Optional, the default value is "" which means standard connection.

Note
Your hosting may not support non-standard connections.

Example

<?
// Query for currency exchange rates from www.cbr.ru on 18.01.2005
$strQueryText = QueryGetData(
    "www.cbr.ru",
    80,
    "/scripts/XML_daily.asp",
    "date_req=18.01.2005",
    $error_number,
    $error_text
    );
if (strlen($strQueryText)<=0)
{
   echo "Query error!";
   if (intval($error_number)>0 || strlen($error_text)>0)
      echo ": (".$error_number.") ".$error_text;
   echo ". ";
}
else
{
   echo htmlspecialchars($strQueryText);
}
?>


Rel2Abs

string
Rel2Abs(
 string cur_dir,
 string rel_path
)

The function Rel2Abs returns path that is relative to the specified directory cur_dir.

Parameters

Parameter | Description
cur_dir | Path to directory relative to which the rel_path is specified.
rel_path | Relative path.

Example

<?
echo Rel2Abs("/site/", "/temp/index.php");		// /temp/index.php
echo Rel2Abs("/site/", "temp/index.php");		// /site/temp/index.php
echo Rel2Abs("/site/temp/", "../index.php");		// /site/index.php
echo Rel2Abs("/site/temp/", "../../index.php");	// /index.php
?>


ShowError

ShowError(
 string message,
 string css_class = "errortext"
)

The function ShowError emits the error message.

Parameters

Parameter | Description
message | Error message.
css_class | CSS class to use for the message. Optional. The default value is "errortext" (which is usually in red).

Example

<?
ShowError("Error!");
?>


ShowMessage

ShowMessage(
  mixed message
)

The function ShowMessage is used to emit error descriptions and other messages.

Parameters

Parameter Description
message Error description text or an array with the following keys:
  • TYPE - message type; the following values are possible:
    • OK - common message using the CSS class "notetext";
    • ERROR - error message using the CSS class "errortext".
  • MESSAGE - message text.

Example

<?
// display common message
ShowMessage(Array("TYPE"=>"OK", "MESSAGE"=>"Data saved."));
?>
<?
// display error message
ShowMessage("Error! Please fill in the required fields!");
?>


ShowNote

ShowNote(
 string message,
 string css_class = "notetext"
)

The function ShowNote emits a message.

Parameters

Parameter | Description
message | Message text.
css_class | CSS class to use for the message. Optional. The default value is "notetext" (usually in green).

Example

<?
ShowNote("OK!");
?>


Kernel settings

This topic provide a summary of system settings available to site administrators.

List of settings

The following is the list of system-wide settings, in the order as displayed by the Kernel module settings form.

  • Allow the users to self-register
  • Upon registration, add to group
  • Allow authorization caching
  • Use secure storing of the authorization data in cookies
  • One or comma-separated list of E-mail addresses to receive copies of all the outcoming messages
  • Send email event and template identifiers in message
  • E-mail address in caption
  • E-mail of site administrator (default sender address)
  • Convert Unix new line symbols to Windows format during email sending
  • Convert 8-bit characters in the message header
  • Site name
  • Site URL (without http://). E.g., www.mysite.com
  • Name of system update server
  • Cookie name prefix
  • File upload default folder
  • Replace status 200 with 404 in header
  • Menu type for the top level of the site map
  • Menu type for other levels of the site map
  • Error report mode
  • Global authentication for all site domains
  • Keep the original names for uploaded files
  • Automatically replace invalid symbols in the names of uploaded files

Description of settings

Title: Allow the users to self-register
ID: new_user_registration
Description: If this parameter is set ("Y"), the Registration link will be avaulable ib the standard components:
  • /main/auth/authorize.php
  • /main/auth/authorize_registration.php
Default value: Y
Title: | Upon registration, add to group
ID: | new_user_registration_def_group
Description: | Specifies groups to which a user is automatically added after the registration (using methods CUser::Register, CUser::SimpleRegister).
Default value: | 2 (the Everyone group)
Title: Allow authorization caching
ID: store_password
Description: If this parameter is set ("Y"), and if a user selects Remember me at the time of authorization, the user authorization will be stored in his cookie. This parameter is also used to show or hide the Remember me check box in the standard components:
  • /main/auth/authorize.php
  • /main/auth/auth_form.php
  • /main/auth/authorize_registration.php
Default value: Y
Title: | Use secure storing of the authorization data in cookies
ID: | use_secure_password_cookies
Description: | If the parameter Allow authorization caching is set ("Y"), this parameter specifies the type of cookie in which the authorization is to be stored. If this parameter is checked ("Y"), the authorization cookie is created as secure, which implies automatic authorization for the secure connections (HTTPS) only.
Default value: | N
Title: | One or comma-separated list of E-mail addresses to receive copies of all the outcoming messages
ID: | all_bcc
Description: | E-mail address or a list of comma-separated addresses to which all the outcoming messages are duplicated.
Default value: |
Title: Send email event and template identifiers in message
ID: send_mid
Description: If this parameter is set ("Y"), the following line is appended to the message body:
MID: EVENT_ID.TEMPLATE_ID (DATE_EVENT)
where:
  • EVENT_ID - mail event ID;
  • TEMPLATE_ID - mail template ID;
  • DATE_EVENT - date of the mail event creation.
Default value: N
Title: | E-mail address in caption
ID: | fill_to_mail
Description: | If this parameter is set ("Y"), the "To" field is copied to the message header.
Default value: | N
Title: | E-mail of site administrator (default sender address)
ID: | email_from
Description: | This field usually contains the site administrator e-mail address. This address is available for mail templates as #DEFAULT_EMAIL_FROM#.
Default value: | "admin@".$_SERVER["SERVER_NAME"]
Title: | Convert Unix new line symbols to Windows format during email sending
ID: | CONVERT_UNIX_NEWLINE_2_WINDOWS
Description: | Setting this parameter to "Y" causes all new line symbols (aka carriage return, CR, \n) to be converted to the pair "line feed (LF)"+"new line" (\r\n). This may be needed in situations when a site has been originally developed for the Unix server (with the new line symbol set to \n), but later ported to the Windows server (with the new line symbol set to a pair of \r\n). But as the RFC 2822 standard forbids the use of single \n or \r in e-mail messages, the mail server may cause errors when parsing e-mail messages.
Default value: | N (do not convert)
Title: | Convert 8-bit characters in the message header
ID: | convert_mail_header
Description: | According to the RFC 2822 standard, the message header ("To", "From", "Subject", "CC", "BCC" and other fields) may only contain characters with codes from 33 (100001) to 126 (1111110) (Latin letters, digits, punctuation marks); these symbols use the lower 7 bits of a byte. Symbols that use the bit 8 (128 and greater), are called 8-bit symbols. The RFC 2822 standard forbids their use in the message header. Many mail servers do not support 8-bit symbols in the message header. Therefore, if you use 8-bit symbols (e.g. national) in the header, you have to set this parameter to "Y", which will convert 8-bit symbols to the "MIME base64" format used to transfer binary data in systems that do not support 8-bit symbols .
Default value: | Y (perform conversion)
Title: | Site name
ID: | site_name
Description: | Specifies the default site name (the field Site name in the site settings). Used in mail templates in the field #SITE_NAME#.
Default value: | the value of the standard PHP variable $_SERVER["SERVER_NAME"]
Title: | Site URL (without http://). E.g., www.mysite.com
ID: | server_name
Description: | This parameter specifies the default value of the site address (the field Server URL in the site settings). Used in mail templates in the field #SERVER_NAME#.
Default value: | the value of the standard PHP variable $_SERVER["SERVER_NAME"]
Title: | Name of system update server
ID: | update_site
Description: | URL of the update server.
Default value: | www.bitrixsoft.com
Title: | Cookie name prefix
ID: | cookie_name
Description: | Prefix of the cookie names set by this portal.
Default value: | BITRIX_SM
Title: | File upload default folder
ID: | upload_dir
Description: | Any subdirectory of the DocumentRoot directory in which the files uploaded using CFile::SaveFile are contained. This parameter is extensively used by the CFile class methods. Uploaded files are those uploaded through the HTML forms, except file that can be uploaded to any folder using Site Explorer -> Explore -> Upload File.
Default value: | upload
Title: | Replace status 200 with 404 in header
ID: | header_200
Description: | If this parameter is set ("Y"), the status 200 (OK) will be sent every time a "page not found" (404) error occurs. This parameter is generally used for search engine robots when building services on the 404 error. For example, it can be used to create "nice addresses" without parameters (e.g. /news/345.php).
Default value: | Y
Title: | Menu type for the top level of the site map
ID: | map_top_menu_type
Description: | This parameter is used by the standard component /main/map/default.php used to display a site map. Stores the type of menu to be taken as the starting level of the site map.
Default value: | top
Title: | Menu type for other levels of the site map
ID: | map_left_menu_type
Description: | This parameter is used by the standard component /main/map/default.php used to display a site map. Stores the type of menu whose items are used to build the site map (after the starting level).
Default value: | left
Title: | Error report mode
ID: | error_reporting
Description: | This parameter is used in the prologue service section to set the PHP error and warning levels.
Default value: | Errors only (E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR|E_PARSE)
Title: | Global authentication for all site domains
ID: | auth_multisite
Description: | If this parameter is set ("Y"), the user authorization (stored in cookie or session) will be spread among all domains of all sites of the portal.
Default value: | N
Title: | Keep the original names for uploaded files
ID: | save_original_file_name
Description: | Setting this parameter to "Y" causes the names of uploaded files to be left as is. Otherwise, their names will be replaced with the MD5 hash string.
Default value: | N
Title: | Automatically replace invalid symbols in the names of uploaded files
ID: | convert_original_file_name
Description: | If this parameter is set ("Y"), all invalid symbols which are not Latin letters, digits, dashes, underscores and dots will be replaced with random valid symbols.
Default value: | Y


Visual editor

In this section

The visual editor, which is the integral part of the Site Explorer module, offers API that can be used to enrich the editor with user-defined functions, and also customise and alter the editor behaviour. The explained methods can be called on pages where the editor is used, after it becomes initialised.

The API is written in JavaScript. hence all calls must be made inside <script>...</script>. Any error may cause the editor to function improperly.

  • Adding custom taskbars
  • Adding custom parsers
  • The global object oBXEditorUtils
© 2001-2007 Bitrix Bitrix Site Manager


Adding custom parsers

The visual editor API provides interfaces to add custom parsers. This allows developers to inject their custom handlers and gain control over parsing of the document source code performed when preparing the document for display in the visual editor (at the time of loading the document or switching from the source code to the visual mode).

The visual editor API functions enables you to install parsers of the following three types, with which you can efficiently handle documents before they are passed over to the visual editor:
  • Source code parser (Content Parser);
  • PHP inclusion parser (PHP Parser);
  • DOM visual aspect parser (DOM Handler).

Content Parser

Processes documents at the source code level. To add a content parser:

  1. declare the handler function;
  2. install handler by calling the addContentParser method of oBXEditorUtils.

Handler declaration

The handler function (which is essentially the parser itself) must be visible within the scope of addContentParser. The only argument that the function accepts is the document source code. The function processes the code and returns an altered version of it. Otherwise, false can be returned which indicates that no changes are made to the input code.

Parser installation

To install your parser, call oBXEditorUtils.addContentParser.

Example

<script>

function CustomContentParser(str)
{
    //... some changes here
    return str;
}

// Add the parser
oBXEditorUtils.addContentParser(CustomContentParser);

</script>

PHP Parser

Being installed, this parser allows to process PHP islands in the document source code.

When a document is processed, the system passes code portions to all the installed parsers subsequently, in the form of text string. If a parser returns the code unchanged (the system uses case-sensitive comparison) or returns false, the string is passed to the next registered parser. When installing the parser, you can specify its position in the parser queue. However, the built-in parsers of the visual editor have the highest priority and are called in the first turn. To add a content parser:

  1. declare the handler function;
  2. install handler by calling the addPHPParser method of oBXEditorUtils.

Handler declaration

The parser must be visible within the scope of addContentParser. The only argument that the function accepts is the source code. The function processes the code and returns an altered version of it. Otherwise, false can be returned which indicates that no changes are made to the input code.

You can use helper methods of oBXEditorUtils.PHPParser to create faster and more efficient parsers.

Parser installation

To install your parser, call oBXEditorUtils.addPHPParser.

Example

<script>

function CustomPHPParser(str)
{
    //... handle the document code
    return str;
}

//Add handler
oBXEditorUtils.addPHPParser(CustomPHPParser);

</script>

You must ensure that your content and PHP parsers perform correctly and do no damage to the source code. Otherwise, the visual editor may function improperly.

DOM Handler

Creating a document handler to trap code at the DOM level can simplify creation of the element property inspectors, after the element has already been created and rendered in the visual mode. In your DOM parser, you can use any available DOM functions.

To add a content parser:

  1. declare the handler function;
  2. install handler by calling the addDOMHandler method of oBXEditorUtils.

Handler declaration

The parser must be visible within the scope of addDOMHandler. The function accepts the document object on input. The function can inspect and alter the document DOM as required. Return values are ignored.

Parser installation

To install your parser, call oBXEditorUtils.addDOMHandler.

Example

<script>

function CustomDOMHandler(oDocument)
{
    //... handle the document
}

//Install parser
oBXEditorUtils.addDOMHandler(CustomDOMHandler);

</script>
© 2001-2007 Bitrix Bitrix Site Manager


Adding custom toolbars

The visual editor user interface can be easily enriched with custom user defined controls. Using the visual editor API, you can create and dock (or float) your own bars, and add controls to the bar that can perform virtually any function. Adding a custom bar requires that you:

  1. declare the custom bar class;
  2. add the bar by calling addTaskBar of the oBXEditorUtils global object.

Declaring the custom bar class

You have to strictly follow to JavaScript class declaration rules when developing the custom bar class. Bear in mind that JavaScript does not implement the concept of class; hence, you will have to use a special syntax of JavaScript functions to declare pseudo classes.

The simplest way to create classes in JavaScript is using the syntax of functional literals to declare class methods as properties of the prototype object.

To interact with the visual editor API, you can use the following approaches and features in your class:

  • standard event handlers;
  • parent class properties;
  • parent class methods.

A standard event handler is a method that is bound to an event which is raised when a user or system performs an action that can be processed by the class. With the concept of events, you can create interactive code that responds to environmental occurrences.

Standard event handlers

Handler | Description
OnTaskbarCreate | Called when the taskbar is being created. Override this method to prepare the taskbar for display and perform any needed initialization.
OnTaskbarRemove | Called to inform the object that it is being removed. Can be used to free memory, and to detect memory leaks.
OnElementDragEnd(object oElement) | Fires when a drag operation is ended. The operation may have been initiated from a list formed by the toolbar creation methods (parent class). The oElement parameter references an instance of BXNodeElement, which inherits properties of a DOM node and allows to uniquely identify it.
UnParseElement(object oElement) Called when the editor switches from the visual mode to the source code or split mode. The oElement parameter have the same meaning as with OnElementDragEnd.

The handler is to return a string containing the code with which the source element is to be replaced, or false if no replacement is required.

Important! This handler is called for every irregular visual element. You will have to verify the __bxtagname attribute to identify the required element. For example:

CustomTaskbar.prototype.UnParseElement = function(node)
{
    if (node.arAttributes["__bxtagname"] == '__customtag1')
        return '<?MyPHPFunction(0)?>'
    if (node.arAttributes["__bxtagname"] == '__customtag1')
        return '<?MyPHPFunction(1)?>'
    if (node.arAttributes["__bxtagname"] == '__customtag2')
        return '<?MyPHPFunction(2)?>'

    return false;
}

Properties and methods of the parent class

To use properties or call methods of the parent class in the custom bar class handler, define a function scope variable and set it to this. Make all further calls on the methods and access properties of the parent class on this variable.

Example

function CustomTaskbar()
{
    var oTaskbar = this;
    CustomTaskbar.prototype.OnTaskbarCreate = function ()
    {
        var pDataCell = oTaskbar.CreateScrollableArea(oTaskbar.pDataCell);
        //......
    }
    //....
}

Parent class properties

Property | Description
pDataCell | Area in the taskbar where the interface can be created.

Parent class methods

Method Description
object
CreateScrollableArea(
object nodeElement
); 		Creates a scrollable area inside the DOM node nodeElement, and returns a reference to the area (DOM node).
bool
DisplayElementList(
array arElements,
object oCont
); 		Takes an array of control description data, creates a common set of controls and attaches it to the container oCont, which is the DOM node object. Returns true on success or false otherwise. oCont must not contain elements other than the list.

arElements is an indexed array; each of its element is an associated array having the following structure:
Index | Description
string name | The element.
string title | The display name (title) of the element.
string tagname | Tag name. Used to display data in the property bar, as well as to handle the element when switching to the code view mode.
string icon | Path to the image to be displayed in the list.
bool isGroup | true if the element is a group; false otherwise;
array params | Array of parameters (associated and nested arrays supported).
array childElements | For group elements (isGroup). Each element is an array whose elements have the structure described in this table.

You will find an example of creation of elements below.

Currently, 2-level nesting (childElements) is supported for this structure.
bool
RemoveElementList(
object oCont
); 		Deletes elements from oCont. Returns true on success or false otherwise.
bool
AddElement(
 array oElement,
object oCont,
[string sPath],
[int orderInd]
); 		Adds an element to the list.
  • oElement - element descriptor array (see the description for DisplayElementList);
  • oCont - element container;
  • sPath - (optinal): defines the nesting level of the element. Contains names of parent groups separated with comma. If omitted, the top level is used;
  • orderInd - (optinal): defines the element order (z-index) within the level specified in sPath. -1 appends the element to the end.
    Returns true on success or false otherwise.
bool
RemoveElement(

string elName,
object oCont,
[string sPath]
); 		Deletes an element elName from oCont.

sPath - see AddElement for description.

Returns true on success or false otherwise.

Other API methods

In addition to the described parent class methods, you can use other methods of the visual editor API which cover common programming tasks.

Adding taskbar element handler

You can install a property bar handler if you need to display and edit properties of custom elements. To add a property bar handler, call addPropertyBarHandler.

Adding a taskbar

To install a previously declared taskbar, call addTaskBar on oBXEditorUtils. You will find the detailed description of its parameters in the addTaskBar topic.

Example of a custom taskbar

<script>

function CustomTaskbar()
{
    var pDataCell;
    var oTaskbar = this;

    CustomTaskbar.prototype.OnTaskbarCreate = function ()
    {
        // Create scrollable area
        pDataCell = oTaskbar.CreateScrollableArea(oTaskbar.pDataCell);
        // install taskbar handler for "_customtag2"
        oBXEditorUtils.addPropertyBarHandler('_customtag2',this.ShowProperties);
        // Display list of elements
        this.DisplayTree();
    }

    CustomTaskbar.prototype.DisplayTree = function()
    {
        // Define the array of elements
        var arElements = [];
        var _arElement = [];
        _arElement['name'] = 'group1';
        _arElement['title'] = 'Group 1';
        _arElement['tagname'] = '';
        _arElement['icon'] = '';
        _arElement['isGroup'] = true;
        _arElement['params'] = [];
        _arElement['childElements'] = [];
            var __arElement = [];
            __arElement['name'] = 'el_1_1';
            __arElement['title'] = 'Element 1.1';
            __arElement['tagname'] = '_customtag';
            __arElement['icon'] = '/images/icon1.gif';
            __arElement['isGroup'] = false;
            __arElement['params'] = [];
            __arElement['childElements'] = [];
            _arElement['childElements'].push(__arElement);

            __arElement = [];
            __arElement['name'] = 'el_1_2';
            __arElement['title'] = 'Element 1.2';
            __arElement['tagname'] = '_customtag2';
            __arElement['icon'] = '/images/icon2.gif';
            __arElement['isGroup'] = false;

                ___arPar = [];
                ___arPar[0] = {name:'param0',title:'Параметр0',value:'value0'};
                ___arPar[1] = {name:'param1',title:'Параметр1',value:'value1'};
                ___arPar[2] = {name:'param2',title:'Параметр2',value:'value2'};
            __arElement['params'] = ___arPar;
            __arElement['childElements'] = [];

            _arElement['childElements'].push(__arElement);

        arElements.push(_arElement);

        _arElement = [];
        _arElement['name'] = 'el_2';
        _arElement['title'] = 'Element 2';
        _arElement['tagname'] = '_customtag';
        _arElement['icon'] = '/images/icon3.gif';
        _arElement['params'] = [];
        _arElement['isGroup'] = false;
        _arElement['childElements'] = [];
        arElements.push(_arElement);

        // Add elements to the scrollable area
        oTaskbar.DisplayElementList(arElements,pDataCell);
    }

    // Property handler for _customtag2
    CustomTaskbar.prototype.ShowProperties = function(_bNew, _pTaskbar, _pElement)
    {
        // _pTaskbar.pCellProps - scrollable area
        var arParams = oBXEditorUtils.getCustomNodeParams(_pElement);
        var _input,_div;
        var __saveParams = function(e)
        {
            for (var _i=0; _i<arParams.length;_i++)
            {
                _input = document.getElementById('__param_'+arParams[_i].name);
                arParams[_i].value = _input.value;
            }

            //oBXEditorUtils.setCustomNodeParams(_pElement,arParams);
        }

        if (_bNew)
        {
            oBXEditorUtils.BXRemoveAllChild(_pTaskbar.pCellProps);
            for (var _i=0;_i<arParams.length;_i++)
            {
                _input = document.createElement('INPUT');
                _input.type = 'text';
                _input.id = '__param_'+arParams[_i].name;
                _input.value = arParams[_i].value;
                _input.onblur = __saveParams;

                _div = document.createElement('DIV');
                _div.id = '__vd_'+arParams[_i].name;
                _div.innerHTML = arParams[_i].title;
                _div.appendChild(_input);
                _pTaskbar.pCellProps.appendChild(_div);
            }
        }
        else
        {
            for (var _i=0;_i<arParams.length;_i++)
            {
                _input = document.createElement('INPUT');
                _input.type = 'text';
                _input.id = '__param_'+arParams[_i].name;
                _input.value = arParams[_i].value;
                _input.onblur = __saveParams;

                _div = document.getElementById('__vd_'+arParams[_i].name);
                _div.innerHTML = arParams[_i].title;
                _div.appendChild(_input);
            }
        }
    }

    CustomTaskbar.prototype.UnParseElement = function(node)
    {
        if (node.arAttributes["__bxtagname"] == '_customtag')
            return '<?SomeSuperFunction(3)?>'
        if (node.arAttributes["__bxtagname"] == '_customtag2')
            return '<?SomeSuperFunction(1)?>'

        return false;
    }

    CustomTaskbar.prototype.OnElementDragEnd = function(oEl)
    {
        if (oEl.getAttribute('__bxtagname') == '_customtag')
        {
            oEl.parentNode.removeChild(oEl);
            oTaskbar.insertHTML('snippet');
            alert('Element _customtag was added');
        }
        else if(oEl.getAttribute('__bxtagname') == '_customtag2')
            alert('Element _customtag2 was added');

    }
}

// Now, install the declared taskbar
oBXEditorUtils.addTaskBar('CustomTaskbar',2,"Help",[]);

</script>
© 2001-2007 Bitrix Bitrix Site Manager


BXNodeElement

BXNodeElement is passed as an argument to custom taskbar event handlers. This class is used to describe the layout of "fake" elements that are used to represent pieces of source code in the visual mode.

Properties

Method Description
arAttributes Array; contains the following elements.
Index | Description
__bxtagname | Contains the fictitious tag name used to create a fake element.
__bxcontainer | Element parameters in the serialized form.

Example

//....

//pNode is an instance of BXNodeElement
alert(pNode.arAttributes["__bxtagname"]);

//....

Information about BXNodeElement is to be supplied.

© 2001-2007 Bitrix Bitrix Site Manager


Глобальный объект oBXEditorUtils

oBXEditorUtils Global Object

The system provides the global object oBXEditorUtils enabling developers to build effective solutions using the system visual editor. This object and its nested objects have a number of properties and methods allowing to use the existing functions of the editor API. Tasks and parameters that are bound to certain editor objects can be implemented as methods and properties of a parent class, or as other visual editor global API objects of the.

Methods

Method | Description
addContentParser | Adds the specified handler to which the document content will be passed to be processed, in the HTML format.
addPHPParser | Adds the specified handler function to process PHP inclusions of the HTML document.
addDOMHandler | Adds the specified handler to which the document content will be passed to be processed as a DOM structure.
addPropertyBarHandler | Adds a new handler which will be called when the editor creates a property bar for a specified tag.
addTaskBar | Add a user's taskbar to the visual editor.
BXRemoveAllChild | Removes all child nodes of an element passed.
getCustomNodeParams | Returns parameters of custom elements that substitute code fragments in the visual mode.
setCustomNodeParams | Applies parameters in the array to a custom element that may substitute a code fragment in the document in the visual mode.

Nested objects

Nested object | Description
PHPParser | Implements methods for parsing PHP islands in source documents.
© 2001-2007 Bitrix Bitrix Site Manager


addContentParser

oBXEditorUtils.addContentParser

void
oBXEditorUtils.addContentParser(
   function handler
);

The oBXEditorUtils.addContentParser method adds a specified handler function to which the document content will be passed to be processed, in the HTML format.
A handler function added using this method will process the document content at the load time, and when switching from the HTML mode to WYSIWYG.

Parameters

Parameter | Description
handler | Globally declared handler function. A handler receives a string with the content. The handler function returns a string if any change took place, or false otherwise.
© 2001-2007 Bitrix Bitrix Site Manager


addDOMHandler

oBXEditorUtils.addDOMHandler

void
oBXEditorUtils.addDOMHandler(
   function handler[,
   int orderInd]
);

The oBXEditorUtils.addDOMHandler method adds a specified handler function to which the document content will be passed to be processed, as the DOM structure.

A handler function added using this method can address nodes of an edited document at the load time (in the visual mode), and when switching from the HTML mode to WYSIWYG.

The DOM handler receives a document after it has been processed by handlers installed using the addContentParser and addPHPParser methods.

Parameters

Parameter | Description
handler | A globally declared function. A handler receives a reference to the document object of an edited document. Returns nothing.

Example

function myDOMHandler(oDocument)
{
    //do some actions
    var arIMG = oDocument.getElementsByTagName('IMG');
    var iLen = arIMG.length;
    for (var i=0;i < iLen;i++)
        arIMG[i].src = 'my_new_image.jpg';
}

//Add the handler
oBXEditorUtils.addDOMHandler(myDOMHandler);
This handler replaces the src attribute of all document pictures with my_new_image.jpg (leaving other attributes unchanged).
© 2001-2007 Bitrix Bitrix Site Manager


addPHPParser

oBXEditorUtils.addPHPParser

void
oBXEditorUtils.addPHPParser(
   function handler[,
   int orderInd]
);

The oBXEditorUtils.addPHPParser method installs a handler to process PHP sessions of an HTML document.

A PHP handler processes the PHP inclusions before such are substituted with the PHP code icon in the visual editor. This happens at the document load time, and when switching from the HTML mode to WYSIWYG.

Parameters

Parameter | Description
handler | Globally declared handler function. A handler receives a string containing the PHP code. The handler function returns a string if any change took place, or false otherwise. Note that the whole PHP island is passed to be processed, including the standard PHP open and close tags.
orderInd | Handler priority; optional. By default, parsers are called in the same order they were previously registered in the system. For example, if orderInd is 0, this handler will be called before calling any other PHP parsers. However, if another handler with orderInd of 0 gets registered later, it will become the first in the calling queue.

Example

function myPHPParser(str)
{
    // If the PHP fragment is <?MyPHPFunction();?>,
    // it is replaced by the

    if (str=='<?MyPHPFunction();?>') icon
        return '<img src="icon.gif" title="Image Title" __bxtagname="customtag">';
    return false;
}

//Add parser
oBXEditorUtils.addPHPParser(myPHPParser);
© 2001-2007 Bitrix Bitrix Site Manager


addPropertyBarHandler

oBXEditorUtils.addPropertyBarHandler

void
oBXEditorUtils.addPropertyBarHandler(
 string tagname,
 function handler
);

The oBXEditorUtils.addPropertyBarHandler method adds a new handler which will be called when the editor creates a toolbar for a tag specified by tagname.

The toolbar is activated automatically when a user clicks a tag or right upon insertion of an element from a user's taskbar. You can supply, if needed, a function to create the element parameters (passed as the second parameter). The parameter creation function can also implement element parameter editing. The use of anonymous functions as handler is undesirable.

Parameters:
Parameter | Description
tagname | The tag name.
handler Function or method to handle the event of property bar initialisation. The following three parameters are passed to this function when an event fires:
Parameter | Description
bool bNewParams | True if the property bar currently displays properties for a tag of the same name as new. False if the properties of some other tag are displayed. This parameters can be used to speed up the property display. If you have to display properties of an element of the same name as current, you can simply supply new data to the property controls instead of having to re-create the whole property bar.
object pTaskbar | Reference to a property bar object. Used to display the element properties. Pay attention to pCellProps. It is an important property which can be used to attach and display property controls. pCellProps is a DOM node which is a container of the property bar scrollable area.
object pElement | Reference to the selected element. The getCustomNodeParams() and setCustomNodeParams() methods of the oBXEditorUtils global object can be used to read or modify element properties.

Example of creating the property bar handler

<script>
function CustomTaskbar()
{
    var oTaskbar = this;

    CustomTaskbar.prototype.OnTaskbarCreate = function ()
    {
        //...
        //Add the property bar handler for the "_customtag" element
        oBXEditorUtils.addPropertyBarHandler('_customtag',this.ShowProperties);
        //...
    }

    //...

    CustomTaskbar.prototype.ShowProperties = function(_bNew, _pTaskbar, _pElement)
    {
        // _pTaskbar.pCellProps - scrolled area of the property bar
        // Read the element properies
        var arParams = oBXEditorUtils.getCustomNodeParams(_pElement);
        //...
        // Do some operations over the properties
        //...
        //Save the element properties
        oBXEditorUtils.setCustomNodeParams(_pElement,arParams);
    }
}
</script>
© 2001-2007 Bitrix Bitrix Site Manager


addTaskBar

oBXEditorUtils.addTaskBar

void
oBXEditorUtils.addTaskBar(
 string className,
 int taskbarSetPos,
 string taskbarTitle,
 array params
);

The oBXEditorUtils.addTaskBar method is used to add a user's taskbar to the visual editor. Requires that a user taskbar class to be declared beforehand (see also Adding custom taskbars).

Parameters
Parameter | Description
className | The name of the taskbar class.
taskbarSetPos Defines the taskbar position relative to the editing area.
0 | At the top, over the editing area.
1 | The left of the editing area.
2 | The right of the editing area.
3 | At the bottom, under the editing area.
taskbarTitle | The name of the taskbar. Displayed in the title.
params | Additional parameters.

Example of creating a taskbar

<script>

function CustomTaskbar()
{
    var oTaskbar = this;

    CustomTaskbar.prototype.OnTaskbarCreate = function()
    {
        //...
    }

    CustomTaskbar.prototype.UnParseElement = function(node)
    {
        //...
    }

    CustomTaskbar.prototype.OnElementDragEnd = function(oEl)
    {
        //...
    }
}

//Add the taskbar
oBXEditorUtils.addTaskBar('CustomTaskbar',2,"Help",[]);

</script>
© 2001-2007 Bitrix Bitrix Site Manager


BXRemoveAllChild

oBXEditorUtils.BXRemoveAllChild

void
oBXEditorUtils.BXRemoveAllChild(
 object pNode
);

The oBXEditorUtils.BXRemoveAllChild method removes all child nodes of an element passed in pNode.

Parameters
Parameter | Description
pNode | The document DOM node whose child items are to be removed.

Example

<script>

var oTable = document.getElementById('tableId');

//Remove child nodes of the id='tableId' table
oBXEditorUtils.BXRemoveAllChild(oTable);

</script>
© 2001-2007 Bitrix Bitrix Site Manager


getCustomNodeParams

oBXEditorUtils.getCustomNodeParams

array
oBXEditorUtils.getCustomNodeParams(
 object pNode
);

The oBXEditorUtils.getCustomNodeParams method returns parameters of a custom element as an array. Used for processing element properties when defining a custom taskbar (see also Adding custom taskbars).

In WYSIWYG mode, code fragments or other elements can be substituted with their visual representation, for example icons. Properties of these elements are stored in the serialized form as an attribute of this element. This method deserializes properties and returns them in the array.

Parameters:

Parameter | Description
pNode | A DOM node of the document structure or a BXNodeElement object that is passed to the UnParseElement() method when describing the class of the user taskbar. (See also Adding custom taskbars).

Return Values

Returns an array. The array structure and type (associated or simple) depend on properties assigned to the element when creating or editing it.

Example

<script>

function CustomTaskbar()
{
    var oTaskbar = this;

    CustomTaskbar.prototype.OnTaskbarCreate = function ()
    {
        // ...
    }

    CustomTaskbar.prototype.ShowProperties = function(_bNew, _pTaskbar, _pElement)
    {
        // ...
        // Returns an array of properties
        var arParams = oBXEditorUtils.getCustomNodeParams(_pElement);
        // ...
    }

    CustomTaskbar.prototype.UnParseElement = function(node)
    {
        // ...
        // Returns an array of properties
        var arParams = oBXEditorUtils.getCustomNodeParams(node);
        // ...
        return false;
    }
}

</script>

See also

oBXEditorUtils.setCustomNodeParams().

© 2001-2007 Bitrix Bitrix Site Manager


setCustomNodeParams

oBXEditorUtils.setCustomNodeParams

void
oBXEditorUtils.setCustomNodeParams(
  object pNode
  array arParams
);

The oBXEditorUtils.setCustomNodeParams method sets the custom element parameters passed in the array. Used when processing element properties when defining a custom taskbar. (See also Adding custom taskbars).

In WYSIWYG mode, code fragments or other elements can be substituted with their visual representation, for example icons. Properties of these elements are stored in the serialized form as an attribute of this element. This method deserializes properties and returns them in the array.

Parameters

Parameter | Description
pNode | A DOM node of the document structure or a BXNodeElement object that is passed to UnParseElement() when defining the class of the user taskbar. (See also Adding custom taskbars).
arParams | Property array. Both associated and nested arrays are possible.

Return Values

This method does not return a value.

See also

oBXEditorUtils.getCustomNodeParams()

Example

<script>

function CustomTaskbar()
{
    var oTaskbar = this;

    CustomTaskbar.prototype.OnTaskbarCreate = function ()
    {
        //...
    }

    CustomTaskbar.prototype.ShowProperties = function(_bNew, _pTaskbar, _pElement)
    {
        //...
        //Returns an array of properties
        var _arParams = oBXEditorUtils.getCustomNodeParams(_pElement);
        _arParams['value'] = 'new value';
        //...
        //Sets the property array
        oBXEditorUtils.setCustomNodeParams(_pElement,_arParams);
        //...
    }

    CustomTaskbar.prototype.UnParseElement = function(node)
    {
        //...
        //Returns an array of properties
        var arParams = oBXEditorUtils.getCustomNodeParams(node);
        //...
        arParams['property'] = 'new property';
        //...
        //Sets a property array
        oBXEditorUtils.setCustomNodeParams(node,arParams);
        //...
        return false;
    }
}

</script>
© 2001-2007 Bitrix Bitrix Site Manager


Вложенный объект oBXEditorUtils.PHPParser

oBXEditorUtils.PHPParser

The nested PHPParser object brings amalgamates methods used to simplify creation of PHP parsers (oBXEditorUtils.addPHPParser).

Methods

Method | Description
cleanCode | Cleans PHP code of comments, line feeds and carriage returns, excessive whitespace.
getArray | Takes a piece of PHP code in the format "Array([parameters])" and returns an array of parameters passed in the string. The method can correctly process both nested and associated arrays.
getParams | Takes comma-separated parameters and returns an array of string values. Does not process arrays.
parseFunction | Takes a string containing a PHP function call. Returns the function name and the string with parameters.
parseParameters | Takes comma-separated parameters and returns an array of these parameters. The method can processes arrays as parameters.
trimPHPTags | Strips <?php ?> or <? ?> off the PHP tags passed as the parameter.
trimQuotes | Unquotes a code fragment.
© 2001-2007 Bitrix Bitrix Site Manager


cleanCode

oBXEditorUtils.PHPParser.cleanCode

string
oBXEditorUtils.PHPParser.cleanCode(
 string sCode
);

The oBXEditorUtils.PHPParser.cleanCode method removes comments, CR and LF, excessive white space from the PHP code. Can be used to simplify parsing the PHP code fragment when creating a PHP parser.

Parameters:

Parameter | Description
sCode | The string containing a PHP code fragment.

Return Values

Returns a string.

Example

<script>

var sCode = '$arFields   =   array('+
       '"LID" => "en", //language'+
       '"TEXT" => "text text text", //text'+
       '"PAYED" => "N",'+
       '"CANCELED" => "N"'+
       ');'

sCode = oBXEditorUtils.PHPParser.cleanCode(sCode);
//sCode = '$arFields=array("LID"=>"en","TEXT"=>"text text text","PAYED"=>"N","CANCELED"=>"N")';

</script>
© 2001-2007 Bitrix Bitrix Site Manager


getArray

oBXEditorUtils.PHPParser.getArray

array
oBXEditorUtils.PHPParser.getArray(
 string sCode
);

Takes a piece of PHP code in the format "Array([parameters])" and returns an array of parameters passed in the string. The method can correctly process both nested and associated arrays maintaining their structure.

getArray can be used to simplify the PHP code parsing when creating a PHP parser.

Parameters:

Parameter Description
sCode The string in the following format:
Array([parameters])

Return Values

Return an array whose structure depends on the input.

Example

<script>

var sCode = 'array("LID"=>"en","TEXT"=>"text text text","PAYED"=>"N","CANCELED"=>"N")';

arParams = oBXEditorUtils.PHPParser.getArray(sCode);
//arParams["LID"] = "en";
//arParams["TEXT"] = "text text text";
//arParams["PAYED"] = "N";
//arParams["CANCELED"] ="N";

</script>
© 2001-2007 Bitrix Bitrix Site Manager


getParams

oBXEditorUtils.PHPParser.getParams

array
oBXEditorUtils.PHPParser.getParams(
 string sCode
);

The oBXEditorUtils.PHPParser.getParams method takes comma-separated parameters and returns an array of string values. This method cannot be used to process arrays.

getParams can be used to simplify the PHP code parsing when creating a PHP parser.

Parameters:

Parameter Description
sCode The string in the following format:
param1[,param2[,...,paramN]]

Return Values

Returns an array of string values.

See also

parseParameters.

Example

<script>

var sCode1 = '2,"text text text",5,"N"';
var sCode2 = 'array("LID"=>"en","TEXT"=>"text text text","PAYED"=>"N","CANCELED"=>"N")';

arParams1 = oBXEditorUtils.PHPParser.getArray(sCode1);
//arParams[0] = '2';
//arParams[1] = '"text text text"';
//arParams[2] = '5';
//arParams[3] = '"N"';

arParams2 = oBXEditorUtils.PHPParser.getArray(sCode2);
//arParams[0] = 'array("LID"=>"en"';
//arParams[1] = '"TEXT"=>"text text text"';
//arParams[2] = '"PAYED"=>"N"';
//arParams[3] = '"CANCELED"=>"N")';

</script>
© 2001-2007 Bitrix Bitrix Site Manager


parseFunction

oBXEditorUtils.PHPParser.parseFunction

object
oBXEditorUtils.PHPParser.parseFunction(
 string sCode
);

The oBXEditorUtils.PHPParser.parseFunction method takes a string containing a PHP function call and returns the string with the function name and parameters.

parseFunction can be used to simplify the PHP code parsing when creating a PHP parser.

Parameters:

Parameter | Description
sCode | A string with the function call.

Return Values

Returns an object having the following properties:

Type | Property | Description
string | name | The function name.
string | params | The string containing parameters passed to the function.

The method returns false if the string does not comply with the specified format.

See also

parseParameters.

Example

<script>

var sCode = 'MyPHPFunction("param",$var)';

var oFunc = oBXEditorUtils.PHPParser.parseFunction(sCode);
//oFunc.name = 'MyPHPFunction';
//oFunc.params = '"param",$var';

</script>
© 2001-2007 Bitrix Bitrix Site Manager


parseParameters

oBXEditorUtils.PHPParser.parseParameters

array
oBXEditorUtils.PHPParser.parseParameters(
 string sCode
);

The oBXEditorUtils.PHPParser.parseParameters method takes comma-separated parameters and returns an array of these parameters. The method can processes correctly process both nested and associated array declarations passed in the parameter string.

parseParameters can be used to simplify the PHP code parsing when creating a PHP parser.

Parameters:

Parameter Description
sCode The string in the following format:
param1[,param2[,...,paramN]]

Return Values

Return an array.

Example

<script>

var sCode = '2,"Y",Array(1,2,"string1"),Array("name"=>"SomeName","id"=>$phpVar)';

arParams = oBXEditorUtils.PHPParser.parseParameters(sCode);
//arParams[0] = 2;
//arParams[1] = "Y";
//arParams[2][0] = 1;
//arParams[2][1] = 2;
//arParams[2][2] = "string";
//arParams[3]["name"] = "SomeName";
//arParams[3]["id"] = "$phpVar";

</script>
See also getParams, parseParameters, parseFunction.
© 2001-2007 Bitrix Bitrix Site Manager


trimPHPTags

oBXEditorUtils.PHPParser.trimPHPTags

string
oBXEditorUtils.PHPParser.trimPHPTags(
 string sCode
);

The oBXEditorUtils.PHPParser.trimPHPTags method strips <?php ?> or <? ?> off the PHP tags passed as the parameter. If the input does not contain PHP tags, the original string is returned.

trimPHPTags can be used to simplify the PHP code parsing when creating a PHP parser.

Parameters:

Parameter | Description
sCode | The string which is a PHP code fragment.

Return Values

Returns the string.

Example

<script>

var sCode = '<?php MyPHPFunction(); ?>';

sCode = oBXEditorUtils.PHPParser.trimPHPTags(sCode);//sCode = ' MyPHPFunction(); ';

</script>
See also trimQuotes.
© 2001-2007 Bitrix Bitrix Site Manager


trimQuotes

oBXEditorUtils.PHPParser.trimQuotes

string
oBXEditorUtils.PHPParser.trimQuotes(
 string sCode[,
 string cSym]
);

The oBXEditorUtils.PHPParser.trimQuotes method trims single and double quotes (or other symbols) from the specified string.

Parameters:

Parameter | Description
sCode | The string which is a PHP code fragment.
cSym | Optional string containing symbols to be removed from head and tail of the string. By default, single and double quotes are removed.

Return Values

Returns the string.

Example

<script>

var sCode1 = '"My String"';
sCode1 = oBXEditorUtils.PHPParser.trimQuotes(sCode1);//sCode1 = 'My String';

var sCode2 = "'My String'";
sCode2 = oBXEditorUtils.PHPParser.trimQuotes(sCode2);//sCode2 = "My String";

var sCode3 = '-My String-';
sCode3 = oBXEditorUtils.PHPParser.trimQuotes(sCode3,'-');//sCode3 = 'My String';

</script>
See also trimPHPTags.
© 2001-2007 Bitrix Bitrix Site Manager


Installation

Perform the following operations to install the Advertising module.
  1. Go to the page Modules and click Set beside the Advertising module.
  2. After the installation, go to the page Types of banners and create the required types of banners.
  3. In the HTML template of a site, allocate areas which will be used to display banners. After this, use the following model to display banners:

    <?
// obtain the HTML code of banners before a page is displayed
if (CModule::IncludeModule("advertising")):
    $strBanner_top    = CAdvBanner::Show("TOP");
    $strBanner_bottom = CAdvBanner::Show("BOTTOM");
    $strBanner_left   = CAdvBanner::Show("LEFT");
endif;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head></head>
<body>
    <?
    // display the banner HTML
       // in the previously allocated advertising areas
    echo $strBanner_top;
    echo $strBanner_bottom;
    echo $strBanner_left;
    ?>
</body>
</html>
    In other words, you should store the HTML of all banners in PHP variables prior to displaying the HTML content. Then, display them in the required design area.


Classes

The CAdvBanner class is used with advertising banners.

Methods

Method | Description
Set | Creates a new banner or modifies an existing one.
GetList | Returns a filtered list of banners.
GetByID | Returns a banner by its ID.
Delete | Deletes a banner.
Show | Selects a random banner of the specified type, registers the banner show in the database and returns a ready to use HTML code of the banner (used in the site template code). The banner is selected according to its priority relative to priorities of other banners.
Click | Registers a banner click in the database by the banner ID.
FixShow | Registers the banner show in the database.
GetRandom | Selects a random banner of the specified type, according to priority of each banner in the system. Returns an array containing the partial description of this banner.
GetHTML | Returns a ready to use HTML code of the banner by the specified array describing this banner.

The CAdvContract class is used with advertising contracts.

Methods

Method | Description
Set | Creates a new contract, or modifies the existing one.
GetList | Obtains a filtered list of contracts.
GetByID | Returns a contract by its ID.
Delete | Deletes a contract and all banners attached to it.
GetUserPermissionArray | Returns an array of permissions of a specified user for all contracts.
GetContractPermissionArray | Returns an array of permissions of all users for a specified contract.
IsModuleAccess | Returns true if the current user owns the specified permission, or false otherwise.

The CAdvType class is used with types of banners.

Methods

Method | Description
Set | Creates a new banner type, or modifies the existing one.
GetList | Obtains a filtered list of banner types.
GetByID | Returns a type by its symbolic ID.
Delete | Deletes a type and all banners of this type.


CAdvBanner

This class provides programming interface for handling banners.

Methods

Method | Description
Set | Creates a new or modifies an existing banner.
GetList | Returns a list of banners.
GetByID | Returns a banner given its ID.
Delete | Deletes a banner.
Show | Selects a random banner of the specified type and returns a ready to use HTML code of the banner.
Click | Registers a banner click in the database.
FixShow | Registers the display of a banner in the database.
GetRandom | Selects and returns a random banner of the specified type, according to priority of each banner in the system.
GetHTML | Returns a ready to use HTML code of the banner.
GetKeywords | Returns all or part of an array containing keyword specified for the given page.
ResetKeywords | Deletes keywords assigned to a page.
SetDesiredKeywords | Assigns a set of desired keywords to a given page.
SetRequiredKeywords | Assigns a set of required keywords to a given page.


Click

CAdvBanner::Click

CAdvBanner::Click(
 int BANNER_ID,
 int CONTRACT_ID = false
);

The Click method registers a banner click in the database.

Parameters

Parameter | Description
BANNER_ID | Banner ID.
CONTRACT_ID | The ID of a contract to which the banner is attached. Pass false to make the contract ID to be taken from the banner parameters.

Return Value

No return value.


Delete

CAdvBanner::Delete

boolean
CAdvBanner::Delete(
 int BANNER_ID,
 char(1) CHECK_RIGHTS = "Y"
);

The Delete method is used to delete a banner.

Parameters

Parameter | Description
BANNER_ID | Banner ID.
CHECK_RIGHTS | Pass "Y" to check the current user's permissions for the deletion, or "N" to delete a banner unconditionally.

Return Value

The method returns true on success or false otherwise.


FixShow

CAdvBanner::FixShow

CAdvBanner::FixShow(
 array arrBanner
);

The FixShow method registers the banner show in the database. The method sets a cookie indicating a fact of displaying a banner to a visitor.

Parameters

Parameter Description
arrBanner An array with the banner parameters. The following parameters are required and sufficient for the successful call:
  • ID - banner ID;
  • CONTRACT_ID - the ID of a contract to which the banner is attached.

Return Value

No return value.


GetByID

CAdvBanner::GetByID

record set
CAdvBanner::GetByID(
 int BANNER_ID
);

The GetByID function returns a banner given its ID.

Parameters

Parameter | Description
BANNER_ID | Banner ID.

Return Value

The method returns an array containing the banner fields. See Example for a list of the fields.

Example

The following is an example of array returned by a call to the Fetch method of the returned object:

<?
Array
(
    [LAMP] => green
    [ID] => 88
    [CONTRACT_ID] => 1
    [TYPE_SID] => TOP
    [GROUP_SID] =>
    [STATUS_SID] => PUBLISHED
    [STATUS_COMMENTS] =>
    [NAME] =>
    [ACTIVE] => Y
    [LID] =>
    [WEIGHT] => 100
    [MAX_SHOW_COUNT] => 300
    [MAX_CLICK_COUNT] => 100
    [SHOW_COUNT] => 102
    [CLICK_COUNT] => 4
    [IMAGE_ID] => 1032
    [IMAGE_ALT] =>
    [URL] => http://www.bitrixsoft.com?banner_param=#EVENT_GID#
    [URL_TARGET] => _parent
    [CODE] =>
<TABLE class=smalltext cellSpacing=0 cellPadding=0 width=145>
<TR>
<TD></TD>
<TD>
<DIV align=center>
<A class=righthead
   href="/en/partners/partnership.php">Partnership Program</A>
</DIV></TD></TR>
<TR>
<TD></TD>
<TD height=8></TD></TR>
<TR>
<TD width=5></TD>
<TD vAlign=bottom>
<DIV align=center>
<A href="/en/partners/partnership.php">
<IMG height=95 src="/images/advert/free.gif"
     width=100 border=0></A></DIV></TD></TR>
<TR>
<TD></TD>
<TD height=5></TD></TR>
<TR>
<TD></TD>
<TD>Developers and integrators obtain:<BR>
<B><FONT class=smalltext>
<IMG height=8 src="/images/list_bullet.gif" width=8>
</FONT></B>
<FONT color=#ff5a31>50% discounts</FONT>
<BR><B><FONT class=smalltext>
<IMG height=8 src="/images/list_bullet.gif" width=8>
</FONT></B>
<FONT color=#ff5a31>free license</FONT></TD></TR>
<TR>
<TD></TD>
<TD height=5></TD></TR>
<TR>
<TD></TD>
<TD>
<DIV align=right>
<A class=bottomlinks
 href="/en/partners/partnership.php">More info</A>
 <IMG height=7 src="/images/main_button_more_3.gif" width=7>
 </DIV></TD></TR></TABLE>
    [CODE_TYPE] => html
    [STAT_EVENT_1] =>
    [STAT_EVENT_2] =>
    [STAT_EVENT_3] =>
    [FOR_NEW_GUEST] =>
    [COMMENTS] =>
    [CREATED_BY] => 2
    [MODIFIED_BY] => 2
    [CTR] => 3.92
    [DATE_LAST_SHOW] => 24.06.2004 17:39:50
    [DATE_LAST_CLICK] => 24.06.2004 14:47:53
    [DATE_SHOW_FROM] => 10.06.2004
    [DATE_SHOW_TO] => 07.07.2007
    [DATE_CREATE] => 10.06.2004 11:25:59
    [DATE_MODIFY] => 24.06.2004 14:33:56
    [CONTRACT_NAME] => Default
    [TYPE_NAME] => Top banner
)
?>


GetHTML

CAdvBanner::GetHTML

text
CAdvBanner::GetHTML(
 array arrBanner
);

The GetHTML method returns a ready to use HTML code of the banner.

Parameters

Parameter Description
arrBanner An array with the banner parameters. The following parameters are required and sufficient for the successful call:
  • IMAGE_ID - the ID of a banner image (if used);
  • IMAGE_ALT - tooltip for an image (if used);
  • URL - link which is opened upon click on a banner;
  • URL_TARGET - value of the target attribute of the tag <a>;
  • CODE - banner code (if used);
  • CODE_TYPE - type of the banner code (text or html).

Return Value

HTML code of the banner which can be used without additional preparations.


GetKeywords

CAdvBanner::GetKeywords

array
CAdvBanner::GetKeywords(
 varchar(255) TYPE_SID="",
 varchar(255) LOGIC="",
 char(1) EXACT_MATCH=""
);

The method returns all or part of an array containing keyword specified for the given page with the functions SetDesiredKeywords or SetRequiredKeywords.

Parameters

Parameter | Description
TYPE_SID | Symbolic identifier of the advertisement type. If specified, the method returns all keywords assigned to this type.
LOGIC Specifies which keywords of the banner to return from the specified advertisement type. Possible values:
  • DESIRED - return desired keywords (SetDesiredKeywords);
  • REQUIRED - return required keywords (SetRequiredKeywords).
EXACT_MATCH Specifies the type of keywords to return with respect to their match exactness settings.

If set to "Y", the method returns only those keywords which are required to fully match the sample.

If set to "N", the method returns keywords which are required to be at least a part of the sample.

Example

Array
(
    [LEFT] => Array
    (
        [REQUIRED] => Array
        (
            [Y] => Array
            (
                [0] => GeForce
                [1] => Radeon
                [2] => AverTV
                [3] => Sony
            )
        )
    )

    [TOP] => Array
    (
        [DESIRED] => Array
        (
            [N] => Array
            (
                [0] => BMW
                [1] => top soft
                [2] => XP
            )
        )
    )
)

The above array prescribe the following logics of the banner selection.

  1. Banners of the type "LEFT" exactly matching the keywords "GeForce", "Radeon", "AverTV", "Sony" will have the highest priority of the display.
  2. Banners of the type "TOP" that have at least one of the words of the list "BMW", "top soft", "XP" or part of a word will have the highest priority of the display..

If a page contains keywords, the following two scenarios are possible.

  1. No banners matching the keyword list are found. In this case, banners with an empty list of keywords are displayed according to their priority.
  2. More than one matching banners are found. In this case, a banner is selected that has the highest priority with respect to the priority of its contract.

Please remember that a full list of banner keywords is comprised by both banner keywords and keywords of a contract to which the banner is attached.


GetList

CAdvBanner::GetList

record set
CAdvBanner::GetList(
 varchar &by,
 varchar &order,
 array arFilter = array(),
 boolean &is_filtered
);

The GetList method returns a list of banners.

Parameters

Parameter | Description
by Identifier specifying the name of the field that is to be used for sorting. This can be one of the following fields:
  • s_id - by ID;
  • s_lamp - by the indicator value;
  • s_name - by the banner name;
  • s_type_sid - by the banner type;
  • s_contract_id - by the banner ID;
  • s_group_sid - by the group name;
  • s_show_count - by the number of shows;
  • s_max_show_count - by the maximum number of shows;
  • s_date_last_show - by the date of the last show;
  • s_click_count - by the number of banner clicks;
  • s_max_click_count - by the maximum number of clicks;
  • s_date_last_click - by the date of the last click;
  • s_active - by the active state flag;
  • s_weight - by banner weight;
  • s_status_sid - by the banner status;
  • s_date_show_from - by the date of the first show;
  • s_date_show_to - by the date of the last show;
  • s_ctr - by the banner CTR.
order Sort order. The following values are possible:
  • desc - descending (default);
  • asc - ascending.
arFilter Optional additional filter by fields in the form of Array("Filtering field"=>"Value", ...). The Filtering field can be one of the following:
  • ID - banner ID (complex logics allowed)
  • ID_EXACT_MATCH - if set to "Y", banner ID's must match exactly. If set to "N", it can be an entry in the banner ID text.
  • LAMP - indicator value: "red", "green"
  • LANG - double-character language identifier. Denotes the site on which the required banners are shown;
  • SHOW_COUNT_1 - minimum shows;
  • SHOW_COUNT_2 - maximum shows;
  • CLICK_COUNT_1 - minimum clicks;
  • CLICK_COUNT_2 - maximum clicks;
  • CTR_1 - minimum CTR;
  • CTR_2 - maximum CTR;
  • GROUP - name of the banner group (complex logics allowed)
  • GROUP_EXACT_MATCH - if set to "Y", group name must match exactly; if set to "N", it can be an entry in the group name.
  • STATUS_SID - symbolic status code (complex logics allowed); can be one of the following :
    • PUBLISHED - a banner is approved and published;
    • READY - a banner is still on approval;
    • REJECTED - a banner is rejected.
  • CONTRACT_ID - contract ID (complex logics allowed)
  • CONTRACT_ID_EXACT_MATCH - if set to "Y", the contract ID must match exactly; if set to "N", it can be an entry in the contract ID.
  • CONTRACT - ID, name and description of the contract (complex logics allowed)
  • CONTRACT_EXACT_MATCH - if set to "Y", the contract ID, name or description must match exactly; if set to "N", it can be an entry in the contract ID, name or description.
  • TYPE_SID - symbolic code of a banner type (complex logics allowed)
  • TYPE_SID_EXACT_MATCH - if set to "Y", the symbolic code of a banner type must match exactly; if set to "N", it can be an entry in the symbolic code of a banner type.
  • NAME - banner name (complex logics allowed)
  • NAME_EXACT_MATCH - if set to "Y", the banner name must match exactly; if set to "N", it can be an entry in the banner name (default).
  • CODE - banner code (complex logics allowed)
  • CODE_EXACT_MATCH - if set to "Y", the banner code must match exactly; if set to "N", it can be an entry in the banner code (default).
  • COMMENTS - banner comment (complex logics allowed)
  • COMMENTS_EXACT_MATCH - if set to "Y", the banner comment must match exactly; if set to "N", it can be an entry in the banner comment text (default).
is_filtered | Reference to a variable that contains true on the method return if a list of banners has been filtered, or false otherwise.

Return Value

The method returns an array containing the selected banners. See Example.

Example

<?
$FilterArr = Array(
    "find_id",
    "find_id_exact_match",
    "find_lamp",
    "find_lang",
    "find_show_count_1",
    "find_show_count_2",
    "find_click_count_1",
    "find_click_count_2",
    "find_ctr_1",
    "find_ctr_2",
    "find_contract_id",
    "find_contract",
    "find_contract_exact_match",
    "find_group",
    "find_group_exact_match",
    "find_status_sid",
    "find_type_sid",
    "find_type",
    "find_type_exact_match",
    "find_name",
    "find_name_exact_match",
    "find_code",
    "find_code_exact_match",
    "find_comments",
    "find_comments_exact_match"
    );

if (strlen($set_filter)>0)
    InitFilterEx($FilterArr,"ADV_BANNER_LIST","set");
else
    InitFilterEx($FilterArr,"ADV_BANNER_LIST","get");

if (strlen($del_filter)>0)
    DelFilterEx($FilterArr,"ADV_BANNER_LIST");

InitBVar($find_id_exact_match);
InitBVar($find_status_exact_match);
InitBVar($find_group_exact_match);
InitBVar($find_contract_exact_match);
InitBVar($find_type_exact_match);
InitBVar($find_name_exact_match);
InitBVar($find_code_exact_match);
InitBVar($find_comments_exact_match);

$arFilter = Array(
    "ID"                    => $find_id,
    "ID_EXACT_MATCH"        => $find_id_exact_match,
    "LAMP"                  => $find_lamp,
    "LANG"                  => $find_lang,
    "SHOW_COUNT_1"          => $find_show_count_1,
    "SHOW_COUNT_2"          => $find_show_count_2,
    "CLICK_COUNT_1"         => $find_click_count_1,
    "CLICK_COUNT_2"         => $find_click_count_2,
    "CTR_1"                 => $find_ctr_1,
    "CTR_2"                 => $find_ctr_2,
    "GROUP"                 => $find_group,
    "GROUP_EXACT_MATCH"     => $find_group_exact_match,
    "STATUS_SID"            => $find_status_sid,
    "CONTRACT_ID"           => $find_contract_id,
    "CONTRACT"              => $find_contract,
    "CONTRACT_EXACT_MATCH"  => $find_contract_exact_match,
    "TYPE_SID"              => $find_type_sid,
    "TYPE"                  => $find_type,
    "TYPE_EXACT_MATCH"      => $find_type_exact_match,
    "NAME"                  => $find_name,
    "NAME_EXACT_MATCH"      => $find_name_exact_match,
    "CODE"                  => $find_code,
    "CODE_EXACT_MATCH"      => $find_code_exact_match,
    "COMMENTS"              => $find_comments,
    "COMMENTS_EXACT_MATCH"  => $find_comments_exact_match
    );

$rsBanners = CAdvBanner::GetList($by, $order, $arFilter, $is_filtered);
$rsBanners->NavStart(20);
$rsBanners->NavPrint("Banners");

while($arBanner = $rsBanners->NavNext(true, "f_"))
{
    echo "<pre>"; print_r($arBanner); echo "</pre>";
}
?>

The following is an example of array returned by a call to the Fetch method of one of the returned objects:

<?
Array
(
    [LAMP] => green
    [ID] => 88
    [CONTRACT_ID] => 1
    [TYPE_SID] => TOP
    [GROUP_SID] =>
    [STATUS_SID] => PUBLISHED
    [STATUS_COMMENTS] =>
    [NAME] =>
    [ACTIVE] => Y
    [LID] =>
    [WEIGHT] => 100
    [MAX_SHOW_COUNT] => 300
    [MAX_CLICK_COUNT] => 100
    [SHOW_COUNT] => 102
    [CLICK_COUNT] => 4
    [IMAGE_ID] => 1032
    [IMAGE_ALT] =>
    [URL] => http://www.bitrixsoft.com?banner_param=#EVENT_GID#
    [URL_TARGET] => _parent
    [STAT_EVENT_1] =>
    [STAT_EVENT_2] =>
    [STAT_EVENT_3] =>
    [FOR_NEW_GUEST] =>
    [COMMENTS] =>
    [CREATED_BY] => 2
    [MODIFIED_BY] => 2
    [CTR] => 3.92
    [DATE_LAST_SHOW] => 24.06.2004 17:39:50
    [DATE_LAST_CLICK] => 24.06.2004 14:47:53
    [DATE_SHOW_FROM] => 10.06.2004
    [DATE_SHOW_TO] => 07.07.2007
    [DATE_CREATE] => 10.06.2004 11:25:59
    [DATE_MODIFY] => 24.06.2004 14:33:56
    [CONTRACT_NAME] => Default
    [TYPE_NAME] => Top banner
    [CODE_TYPE] => html
    [CODE] => <TABLE class=smalltext cellSpacing=0 cellPadding=0 width=145>
<TR>
<TD></TD>
<TD>
<DIV align=center>
<A class=righthead
   href="/en/partners/partnership.php">Partnership Program</A>
</DIV></TD></TR>
<TR>
<TD></TD>
<TD height=8></TD></TR>
<TR>
<TD width=5></TD>
<TD vAlign=bottom>
<DIV align=center>
<A href="/en/partners/partnership.php">
<IMG height=95 src="/images/advert/free.gif"
     width=100 border=0></A></DIV></TD></TR>
<TR>
<TD></TD>
<TD height=5></TD></TR>
<TR>
<TD></TD>
<TD>Developers and integrators obtain:<BR>
<B><FONT class=smalltext>
<IMG height=8 src="/images/list_bullet.gif" width=8>
</FONT></B>
<FONT color=#ff5a31>50% discounts</FONT>
<BR><B><FONT class=smalltext>
<IMG height=8 src="/images/list_bullet.gif" width=8>
</FONT></B>
<FONT color=#ff5a31>free license</FONT></TD></TR>
<TR>
<TD></TD>
<TD height=5></TD></TR>
<TR>
<TD></TD>
<TD>
<DIV align=right>
<A class=bottomlinks
 href="/en/partners/partnership.php">More info</A>
 <IMG height=7 src="/images/main_button_more_3.gif" width=7>
 </DIV></TD></TR></TABLE>
)
?>


GetRandom

CAdvBanner::GetRandom

array
CAdvBanner::GetRandom(
 varchar(255) TYPE_SID
);

The GetRandom method selects and returns a random banner of the specified type, according to priority of each banner in the system.

Parameters

Parameter | Description
TYPE_SID | Symbolic type identifier.

Return Value

The method returns an array describing the selected banner. See Example for a list of the fields.

Example

The following is an example of array returned.

Array
(
    [ID] => 94
    [CONTRACT_ID] => 3
    [TYPE_SID] => LEFT2
    [STATUS_SID] => PUBLISHED
    [STATUS_COMMENTS] =>
    [NAME] => banner
    [GROUP_SID] => group 1
    [ACTIVE] => Y
    [LID] =>
    [WEIGHT] => 2000
    [MAX_SHOW_COUNT] => 1000
    [MAX_CLICK_COUNT] => 50
    [SHOW_COUNT] => 67
    [CLICK_COUNT] => 4
    [DATE_LAST_SHOW] => 2004-06-24 14:47:47
    [DATE_LAST_CLICK] => 2004-06-22 11:33:18
    [DATE_SHOW_FROM] => 2004-01-07 00:00:00
    [DATE_SHOW_TO] => 2004-07-07 23:59:59
    [IMAGE_ID] => 1028
    [IMAGE_ALT] => tooltip
    [URL] => http://www.bitrixsoft.com
    [URL_TARGET] => _parent
    [CODE] => <TABLE class=smalltext cellSpacing=0 cellPadding=0 width=145>
<TR>
<TD></TD>
<TD>
<DIV align=center>
<A class=righthead
   href="/en/partners/partnership.php">Partnership Program</A>
</DIV></TD></TR>
<TR>
<TD></TD>
<TD height=8></TD></TR>
<TR>
<TD width=5></TD>
<TD vAlign=bottom>
<DIV align=center>
<A href="/en/partners/partnership.php">
<IMG height=95 src="/images/advert/free.gif"
     width=100 border=0></A></DIV></TD></TR>
<TR>
<TD></TD>
<TD height=5></TD></TR>
<TR>
<TD></TD>
<TD>Developers and integrators obtain:<BR>
<B><FONT class=smalltext>
<IMG height=8 src="/images/list_bullet.gif" width=8>
</FONT></B>
<FONT color=#ff5a31>50% discounts</FONT>
<BR><B><FONT class=smalltext>
<IMG height=8 src="/images/list_bullet.gif" width=8>
</FONT></B>
<FONT color=#ff5a31>free license</FONT></TD></TR>
<TR>
<TD></TD>
<TD height=5></TD></TR>
<TR>
<TD></TD>
<TD>
<DIV align=right>
<A class=bottomlinks
 href="/en/partners/partnership.php">More info</A>
 <IMG height=7 src="/images/main_button_more_3.gif" width=7>
 </DIV></TD></TR></TABLE>
    [CODE_TYPE] => html
    [STAT_EVENT_1] =>
    [STAT_EVENT_2] =>
    [STAT_EVENT_3] =>
    [FOR_NEW_GUEST] =>
    [COMMENTS] =>
    [DATE_CREATE] => 2004-06-15 15:13:41
    [CREATED_BY] => 342
    [DATE_MODIFY] => 2004-06-22 19:31:50
    [MODIFIED_BY] => 343
)


ResetKeywords

CAdvBanner::ResetKeywords

array
CAdvBanner::ResetKeywords(
 varchar(255) TYPE_SID="",
 varchar(255) LOGIC="",
 char(1) EXACT_MATCH=""
);

The method deletes keywords assigned to a page. Depending on parameters passed, the method can delete all keywords or those only defined by parameters.

Parameters

Parameter | Description
TYPE_SID | Symbolic identifier of the advertisement type. If specified, the method deletes keywords assigned to this type only.
LOGIC Specifies which keywords of the banner to delete. Possible values:
  • DESIRED - delete desired keywords (see SetDesiredKeywords);
  • REQUIRED - delete required keywords (see SetRequiredKeywords).
EXACT_MATCH Specifies the type of keywords to delete with respect to their match exactness settings.

If set to "Y", the method deletes only those keywords which are required to fully match the sample.

If set to "N", the method deletes keywords which are required to be at least a part of the sample.

Example

Consider the following keywords array:

Array
(
    [LEFT] => Array
    (
        [REQUIRED] => Array
        (
            [Y] => Array
            (
                [0] => GeForce
                [1] => Radeon
            )
            [N] => Array
            (
                [0] => video
                [1] => directx
            )
        )

        [DESIRED] => Array
        (
            [N] => Array
            (
                [0] => game
                [1] => 3D
            )
        )
    )

    [] => Array
    (
        [DESIRED] => Array
        (
            [N] => Array
            (
                [0] => GeForce
                [1] => Radeon
                [2] => Sony
            )
        )
    )

    [TOP] => Array
    (
        [DESIRED] => Array
        (
            [N] => Array
            (
                [0] => BMW
                [1] => top soft
                [2] => XP
            )
        )
    )
)

The below is the modified array after a call to CAdvBanner::ResetKeywords("LEFT","REQUIRED","N"):

Array
(
    [LEFT] => Array
    (
        [REQUIRED] => Array
        (
            [Y] => Array
            (
                [0] => GeForce
                [1] => Radion
            )
        )

        [DESIRED] => Array
        (
            [N] => Array
            (
                [0] => game
                [1] => 3D
            )
        )
    )

    [] => Array
    (
        [DESIRED] => Array
        (
            [N] => Array
            (
                [0] => GeForce
                [1] => Radion
                [2] => Sony
            )
        )
    )

    [TOP] => Array
    (
        [DESIRED] => Array
        (
            [N] => Array
            (
                [0] => BMW
                [1] => top soft
                [2] => Print
            )
        )
    )
)


Set

CAdvBanner::Set

int
CAdvBanner::Set(
 array arFields,
 int BANNER_ID="",
 char(1) CHECK_RIGHTS="Y"
);

The Set method creates a new or modifies an existing banner. To modify an existing banner, pass the banner ID in the second parameter.

Parameters

Parameter | Description
arFields Array containing the banner parameters. The following array keys are possible:
  • CONTRACT_ID - contract ID (required for a new banner)
  • TYPE_SID - symbolic code of a banner type
  • STATUS_SID - symbolic status code; can be one of the following :
    • PUBLISHED - a banner is approved and published;
    • READY - a banner is still on approval;
    • REJECTED - a banner is rejected.
  • STATUS_COMMENTS - comments for the status
  • NAME - banner name
  • GROUP_SID - name of a banner group
  • ACTIVE - active state: "Y" - banner is active; "N" - banner is inactive;
  • LID - code of the site to display the banner
  • WEIGHT - banner weight
  • MAX_SHOW_COUNT - maximum shows
  • RESET_SHOW_COUNT - indicates that the shows counter is to be reset; the contract counter will decrements accordingly
  • MAX_CLICK_COUNT - maximum clicks
  • RESET_CLICK_COUNT - indicates that the clicks counter is to be reset; the contract counter will decrements accordingly
  • DATE_SHOW_FROM - the date of the first show
  • DATE_SHOW_TO - the date of the last show
  • arrIMAGE - array that describes the image to load; the following array keys are possible:
    • name - image file name
    • type - MIME type of a file (e.g.: "image/gif")
    • tmp_name - name of the temporary file on server
    • error - error code ("0" means no error)
    • size - file size
    • MODULE_ID - module identifier ("advertising")
  • IMAGE_ALT - image tooltip text
  • URL - link which is opened upon click on a banner. This field can contain the template #EVENT_GID# that is replaced upon click with the visitor ID used in the Statistics module
  • URL_TARGET - value of the target attribute of the tag <a>:
    • _blank - specifies to load the link into a new blank window. This window is not named.
    • _parent - specifies to load the link into the immediate parent of the document the link is in.
    • _self - specifies to load the link into the same window the link was clicked in.
    • _top - specifies to load the link into the full body of the window.
  • CODE - HTML code of the banner, or banner text
  • CODE_TYPE - type of the banner code: "text" for plain text; "html" for HTML;
  • STAT_EVENT_1 - event type identifier "event1" (for registration in the Statistics module)
  • STAT_EVENT_2 - event type identifier "event2"
  • STAT_EVENT_3 - auxiliary event type identifier "event3". The identifiers event1, event2, event3 allow the following templates:
    • #BANNER_NAME# - banner name
    • #BANNER_ID# - banner ID
    • #CONTRACT_ID# - contract ID
    • #TYPE_SID# - banner type
  • FOR_NEW_GUEST - if set to "Y", the banner is to be shown to new visitors solely; if "N", the banner is shown to all visitors
  • COMMENTS - banner comments
  • arrSHOW_PAGE - array of pages and sections of the site where the banner is allowed to be shown
  • arrNOT_SHOW_PAGE - array of pages and sections of the site where the banner is disallowed to be shown
  • arrCOUNTRY - array of two-character country codes. Describes countries whose visitors the banner is allowed to be shown to.
  • arrSTAT_ADV - array of the advertising campaign identifiers. Describes campaigns whose visitors, both direct and returned, the banner is allowed to be shown to.
  • arrWEEKDAY - array with days of week and time when the banner is to be displayed. The following keys are possible:
    • SUNDAY - array of hours when the banner is to be displayed on Sunday (0-23)
    • MONDAY - on Monday
    • TUESDAY - on Tuesday
    • WEDNESDAY - on Wednesday
    • THURSDAY - on Thursday
    • FRIDAY - on Friday
    • SATURDAY - on Saturday
  • SEND_EMAIL - indicates that the e-mail message is to be sent to contract owners upon change of the banner status.
BANNER_ID | Banner ID. If omitted, a new banner is created.
CHECK_RIGHTS | Indicates to check the current user permissions. If "Y", permissions are checked before the creation or modification of a banner. If set to "N", the method creates or modifies a banner disregarding permissions.

Return Value

Returns the ID of a new or modified banner.

Example

// This code adds a new banner or modifies the existing one
<?
if ((strlen($save)>0 || strlen($apply)>0) && $REQUEST_METHOD=="POST")
{
    InitBVar($SEND_EMAIL);
    $arrIMAGE_ID = $HTTP_POST_FILES["IMAGE_ID"];
    $arrIMAGE["MODULE_ID"] = "advertising";
    $arrIMAGE_ID["del"] = ${"IMAGE_ID_del"};
    $arrWEEKDAY = array(
        "SUNDAY"    => $arrSUNDAY,
        "MONDAY"    => $arrMONDAY,
        "TUESDAY"   => $arrTUESDAY,
        "WEDNESDAY" => $arrWEDNESDAY,
        "THURSDAY"  => $arrTHURSDAY,
        "FRIDAY"    => $arrFRIDAY,
        "SATURDAY"  => $arrSATURDAY
        );
    if ($action=="view" && $isAbsAdmin)
    {
         $arFields = array(
            "STATUS_SID"        => $STATUS_SID,
            "STATUS_COMMENTS"   => $STATUS_COMMENTS
            );
    }
    else
    {
         $arFields = array(
            "CONTRACT_ID"       => $CONTRACT_ID,
            "TYPE_SID"          => $TYPE_SID,
            "STATUS_SID"        => $STATUS_SID,
            "STATUS_COMMENTS"   => $STATUS_COMMENTS,
            "NAME"              => $NAME,
            "GROUP_SID"         => $GROUP_SID,
            "ACTIVE"            => $ACTIVE,
            "LID"               => $LID,
            "WEIGHT"            => $WEIGHT,
            "MAX_SHOW_COUNT"    => $MAX_SHOW_COUNT,
            "RESET_SHOW_COUNT"  => $RESET_SHOW_COUNT,
            "MAX_CLICK_COUNT"   => $MAX_CLICK_COUNT,
            "RESET_CLICK_COUNT" => $RESET_CLICK_COUNT,
            "DATE_SHOW_FROM"    => $DATE_SHOW_FROM,
            "DATE_SHOW_TO"      => $DATE_SHOW_TO,
            "arrIMAGE_ID"       => $arrIMAGE_ID,
            "IMAGE_ALT"         => $IMAGE_ALT,
            "URL"               => $URL,
            "URL_TARGET"        => $URL_TARGET,
            "CODE"              => $CODE,
            "CODE_TYPE"         => $CODE_TYPE,
            "STAT_EVENT_1"      => $STAT_EVENT_1,
            "STAT_EVENT_2"      => $STAT_EVENT_2,
            "STAT_EVENT_3"      => $STAT_EVENT_3,
            "FOR_NEW_GUEST"     => $FOR_NEW_GUEST,
            "COMMENTS"          => $COMMENTS,
            "arrSHOW_PAGE"      => split("[\n\r]",$SHOW_PAGE),
            "arrNOT_SHOW_PAGE"  => split("[\n\r]",$NOT_SHOW_PAGE),
            "arrCOUNTRY"        => $arrCOUNTRY,
            "arrSTAT_ADV"       => $arrSTAT_ADV,
            "arrWEEKDAY"        => $arrWEEKDAY,
            "SEND_EMAIL"        => $SEND_EMAIL
            );
    }
    if ($ID = CAdvBanner::Set($arFields, $ID))
    {
        if (strlen($strError) <= 0)
        {
             if (strlen($save) > 0)
                 LocalRedirect("adv_banner_list.php?lang=".LANG);
             else
                 LocalRedirect(
                     "adv_banner_edit.php?ID=".$ID."&CONTRACT_ID=".$CONTRACT_ID."=".LANG."&action=".$action);
        }
    }
    $DB->PrepareFields("b_adv_banner");
}
?>


SetDesiredKeywords

CAdvBanner::SetDesiredKeywords

CAdvBanner::SetDesiredKeywords(
 mixed keywords,
 varchar(255) TYPE_SID=""
);

The method assigns a set of desired keywords to a given page. If one of the banner or contract keywords are found within a page, the probability of show of the banner is higher. In case no banner satisfying the keyword set can be found, a banner for the show is selected from those without any keywords.

Parameters

Parameter | Description
keywords | Keywords. See Remarks for description of information types that can be passed in this parameter.
TYPE_SID | Type identifier. Describes the advertisement type to which the keywords are to be assigned. Leave this parameter empty to assign keywords to all types.

Example

The following is an example of using the method in the real page.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("advertising"))
{
     // desirable exact-match keywords
     $arrKeywords = array();
     $arrKeywords[] = array("EXACT_MATCH" => "Y", "KEYWORD" => "GeForce");
     $arrKeywords[] = array("EXACT_MATCH" => "Y", "KEYWORD" => "video");
     CAdvBanner::SetDesiredKeywords($arrKeywords, "LEFT");

     // desirable fuzzy match keywords
     CAdvBanner::SetDesiredKeywords(array("Ford", "BMW", "Lada"), "RIGHT");
}

$APPLICATION->SetTitle("Title");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");

// page body
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>

Global use in prolog_after.php:

<?
if (CModule::IncludeModule("advertising"))
{
    CAdvBanner::SetDesiredKeywords($APPLICATION->GetPageProperty("keywords"));
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
...

Remarks

Structures that can be passed in the keywords parameter include the following.

  1. Array with arrays with keys:
    • EXACT_MATCH - denotes the match type: exact match (Y) or occurrence (N).
    • KEYWORDS - the keyword.
    Sample

    Array
(
    [0] => Array
    (
        [EXACT_MATCH] => Y
        [KEYWORD] => GeForce
    )

    [1] => Array
    (
        [EXACT_MATCH] => Y
        [KEYWORD] => Radeon
    )
)
  2. Array of keywords.
    Sample

    Array
(
    [0] => GeForce
    [1] => Radeon
    [2] => Sony
)
    In this case, the fuzzy match algorithm is applied for searching for matching keywords.
  3. Comma-separated list of keywords.
    Sample

    "GeForce, Radeon, Sony"
    In this case, the fuzzy match algorithm is also applied for searching for matching keywords.


SetRequiredKeywords

CAdvBanner::SetRequiredKeywords

CAdvBanner::SetRequiredKeywords(
    mixed keywords,
    varchar(255) TYPE_SID=""
);

The method assigns a set of required keywords to a given page. If all of the banner or contract keywords are found within a page, the probability of show of the banner is higher. In case no banner satisfying the keyword set can be found, a banner for the show is selected from those without any keywords.

Parameters

Parameter | Description
keywords | Keywords. See Remarks for description of information types that can be passed in this parameter.
TYPE_SID | Type identifier. Describes the advertisement type to which the keywords are to be assigned. Leave this parameter empty to assign keywords to all types.

Example

The following is an example of using the method in the real page.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("advertising"))
{
    // required exact match keywords
    $arrKeywords = array();
    $arrKeywords[] = array("EXACT_MATCH" => "Y", "KEYWORD" => "GeForce");
    $arrKeywords[] = array("EXACT_MATCH" => "Y", "KEYWORD" => "video");
    CAdvBanner::SetRequiredKeywords($arrKeywords, "LEFT");

     // required fuzzy match keywords
    CAdvBanner::SetRequiredKeywords(array("Ford", "BMW", "Lada"), "RIGHT");
}

$APPLICATION->SetTitle("Title");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");

// page body
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>

Global use in prolog_after.php:

<?
if (CModule::IncludeModule("advertising"))
{
    CAdvBanner::SetRequiredKeywords($APPLICATION->GetProperty("keywords"));
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
...

If a page contains keywords, the following two scenarios are possible.

  1. No banners matching the keyword list are found. In this case, banners with an empty list of keywords are displayed according to their priority.
  2. More than one matching banners are found. In this case, a banner is selected that has the highest priority with respect to the priority of its contract.

Please remember that a full list of banner keywords is comprised by both banner keywords and keywords of a contract to which the banner is attached.

Remarks

Structures that can be passed in the keywords parameter include the following.

  1. Array with arrays with keys:
    • EXACT_MATCH - denotes the match type: exact match (Y) or occurrence (N).
    • KEYWORDS - the keyword.
    Sample

    Array
(
    [0] => Array
    (
        [EXACT_MATCH] => Y
        [KEYWORD] => GeForce
    )

    [1] => Array
    (
        [EXACT_MATCH] => Y
        [KEYWORD] => Radeon
    )
)
  2. Array of keywords.
    Sample

    Array
(
    [0] => GeForce
    [1] => Radion
    [2] => Sony
)
    In this case, the fuzzy match algorithm is applied for searching for matching keywords; search includes all of the required keywords.
  3. Comma-separated list of keywords.
    Sample

    "GeForce, Radion, Sony"
    In this case, the fuzzy match algorithm is also applied for searching for matching keywords.


Show

CAdvBanner::Show

text
CAdvBanner::Show(
 varchar(255) TYPE_SID
);

The Show method selects a random banner of the specified type and returns a ready to use HTML code of the banner (used in the site template code). The banner is selected according to its priority relative to priorities of other banners.

Parameters

Parameter | Description
TYPE_SID | Symbolic type identifier.

Return Value

HTML code of the banner which can be used without additional preparations.

Example

<!-- Sample code that can be used in the HTML code
of a site template to display banners of the type TOP -->

<?
if (CModule::IncludeModule("advertising")) :
    $s = CAdvBanner::Show("TOP");
    if (strlen($s)>0) :
        // display banner HTML
        ?>
        <table width="0%" border="0"
               cellspacing="0" cellpadding="0">
            <tr>
                <td align=center><?=$s?></td>
            </tr>
        </table>
        <?
    endif;
endif;
?>


CAdvContract

The CAdvContract class is used with advertising contracts.

Methods

Method | Description
Set | Creates a new contract, or modifies the existing one.
GetList | Obtains a filtered list of contracts.
GetByID | Returns a contract by its ID.
Delete | Deletes a contract and all banners attached to it.
GetUserPermissionArray | Returns an array of permissions of a specified user for all contracts.
GetContractPermissionArray | Returns an array of permissions of all users for a specified contract.
IsModuleAccess | Returns true if the current user owns the specified permission, or false otherwise.
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CAdvContract::Delete

boolean
CAdvContract::Delete(
 int CONTRACT_ID,
 char(1) CHECK_RIGHTS="Y"
);

The method Delete deletes a contract and all banners attached to it.

Parameters

CONTRACT_ID
Contract ID
CHECK_RIGHTS
If "Y", the deletion permissions are checked for the current user. If "N", permissions are not checked.
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CAdvContract::GetByID

record set
CAdvContract::GetByID(
 int CONTRACT_ID
);

The method GetByID returns a contract by its ID.

Parameters

CONTRACT_ID
Contract ID

Example

The following is the example of an array after the method result has been fetched.

<?
Array
(
    [LAMP] => green
    [ID] => 3
    [ACTIVE] => Y
    [NAME] => contract name
    [DESCRIPTION] => contract description
    [ADMIN_COMMENTS] => administrative comment
    [WEIGHT] => 1000
    [SORT] => 200
    [MAX_SHOW_COUNT] => 1000
    [SHOW_COUNT] => 312
    [MAX_CLICK_COUNT] => 100
    [CLICK_COUNT] => 64
    [EMAIL_COUNT] => 0
    [CREATED_BY] => 2
    [MODIFIED_BY] => 2
    [DEFAULT_STATUS_SID] => READY
    [CTR] => 20.51
    [DATE_SHOW_FROM] => 15.06.2004
    [DATE_SHOW_TO] => 07.07.2009
    [DATE_CREATE] => 07.06.2004 19:04:55
    [DATE_MODIFY] => 24.06.2004 10:56:08
    [BANNER_COUNT] => 12
)
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetContractPermissionArray

CAdvContract::GetContractPermissionArray

text
CAdvContract::GetContractPermissionArray(
 int CONTRACT_ID
);

The method GetContractPermissionArray returns permissions of all users for a specified contract.

Parameters

CONTRACT_ID
Contract ID

Example

The following is an example of an array returned by the method.

Array
(
    [VIEW] => Array
        (
            [0] => Array
                (
                    [USER_ID] => 341
                    [USER_LOGIN] => view
                    [USER_NAME] => John
                    [USER_LAST_NAME] => Smith
                    [USER_EMAIL] => view@bitrix.com
                )

            [1] => Array
                (
                    [USER_ID] => 340
                    [USER_LOGIN] => edit
                    [USER_NAME] => Lisa
                    [USER_LAST_NAME] => Brown
                    [USER_EMAIL] => edit@bitrix.com
                )

            [2] => Array
                (
                    [USER_ID] => 2
                    [USER_LOGIN] => nessy
                    [USER_NAME] => Vitaly
                    [USER_LAST_NAME] => Kaplich
                    [USER_EMAIL] => nessy@bitrix.com
                )

        )

    [ADD] => Array
        (
            [0] => Array
                (
                    [USER_ID] => 342
                    [USER_LOGIN] => add
                    [USER_NAME] => David
                    [USER_LAST_NAME] => Gahan
                    [USER_EMAIL] => add@bitrix.com
                )

            [1] => Array
                (
                    [USER_ID] => 340
                    [USER_LOGIN] => edit
                    [USER_NAME] => Lisa
                    [USER_LAST_NAME] => Brown
                    [USER_EMAIL] => edit@bitrix.com
                )

            [2] => Array
                (
                    [USER_ID] => 2
                    [USER_LOGIN] => nessy
                    [USER_NAME] => Vitaly
                    [USER_LAST_NAME] => Kaplich
                    [USER_EMAIL] => nessy@bitrix.com
                )

        )

    [EDIT] => Array
        (
            [0] => Array
                (
                    [USER_ID] => 340
                    [USER_LOGIN] => edit
                    [USER_NAME] => Lisa
                    [USER_LAST_NAME] => Brown
                    [USER_EMAIL] => edit@bitrix.com
                )

            [1] => Array
                (
                    [USER_ID] => 2
                    [USER_LOGIN] => nessy
                    [USER_NAME] => Vitaly
                    [USER_LAST_NAME] => Kaplich
                    [USER_EMAIL] => nessy@bitrix.com
                )

        )

)
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CAdvContract::GetList

record set
CAdvContract::GetList(
 varchar &by,
 varchar &order,
 array arFilter=array(),
 boolean &is_filtered
);

The method GetList obtains a list of contracts.

Parameters

by
The field ID by which the sorting is performed. The following values are possible:
  • s_id - by the ID
  • s_lamp - by the contract indicator;
  • s_name - by the contract name;
  • s_description - by the contract description;
  • s_active - by the active state flag;
  • s_weight - by the weight;
  • s_sort - by the sorting;
  • s_date_modify - by the date of modification;
  • s_modified_by - by the ID of the user who modified the contract;
  • s_banner_count - by the number of banners assigned to the contract;
  • s_ctr - by the contract CTR;
  • s_show_count - by the total number of the contract banner shows;
  • s_max_show_count - by the maximum total number of the contract banner shows;
  • s_click_count - by the total number of contract banner clicks;
  • s_max_click_count - by the maximum total number of contract banner clicks.
order
Sort order. The following values are possible:
  • desc - descending (default)
  • asc - ascending
arFilter
An array used to filter the values. The following keys are possible in this array:
  • ID - contract ID (complex logic can be used);
  • ID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the contract ID (default). If "N", the method performs loose searches (entry is sufficient);
  • LAMP - the indicator value: "red" or "green";
  • DATE_MODIFY_1 - lower bound of the date range when the contract could be modified;
  • DATE_MODIFY_2 - upper bound of the date range when the contract could be modified;
  • NAME - contract name (complex logic can be used);
  • NAME_EXACT_MATCH - set to "Y" for exact match searches when filtering by the contract name. If "N", the method performs loose searches (default);
  • DESCRIPTION - contract description (complex logic can be used);
  • DESCRIPTION_EXACT_MATCH - set to "Y" for exact match searches when filtering by the contract description. If "N", the method performs loose searches (default);
  • OWNER - ID, user first and last names, login of the contract owner (complex logic can be used);
  • OWNER_EXACT_MATCH - set to "Y" for exact match searches when filtering by the ID, user first and last names and login of the contract owner. If "N", the method performs loose searches (default);
  • BANNER_COUNT_1 - lower bound of the range of contract banners count;
  • BANNER_COUNT_2 - upper bound of the range of contract banners count;
  • SHOW_COUNT_1 - lower bound of the range of the total number of contract banner shows;
  • SHOW_COUNT_2 - upper bound of the range of the total number of contract banner shows;
  • CLICK_COUNT_1 - lower bound of the range of the total count of contract banner clicks;
  • CLICK_COUNT_2 - upper bound of the range of the total count of contract banner clicks;
  • CTR_1 - lower bound of the contract CTR range;
  • CTR_2 - upper bound of the contract CTR range;
  • ADMIN_COMMENTS - contract administrative comment (complex logic can be used);
  • ADMIN_COMMENTS_EXACT_MATCH - set to "Y" for exact match searches when filtering by the contract administrative comment. If "N", the method performs loose searches (default).
is_filtered
On return, this variable contains true if the returned list of contracts is filtered by any above criteria, or false otherwise.

Example

<?
// filter
$FilterArr = Array(
    "find_id",
    "find_id_exact_match",
    "find_date_modify_1",
    "find_date_modify_2",
    "find_name",
    "find_name_exact_match",
    "find_description",
    "find_description_exact_match",
    "find_lamp",
    "find_owner",
    "find_owner_exact_match",
    "find_banner_count_1",
    "find_banner_count_2",
    "find_show_count_1",
    "find_show_count_2",
    "find_click_count_1",
    "find_click_count_2",
    "find_ctr_1",
    "find_ctr_2",
    "find_admin_comments",
    "find_admin_comments_exact_match"
    );
if (strlen($set_filter)>0) InitFilterEx($FilterArr,"ADV_CONTRACT_LIST","set");
else InitFilterEx($FilterArr,"ADV_CONTRACT_LIST","get");
if (strlen($del_filter)>0) DelFilterEx($FilterArr,"ADV_CONTRACT_LIST");
InitBVar($find_id_exact_match);
InitBVar($find_name_exact_match);
InitBVar($find_description_exact_match);
InitBVar($find_owner_exact_match);
InitBVar($find_admin_comments_exact_match);
$arFilter = Array(
    "ID"                            => $find_id,
    "ID_EXACT_MATCH"                => $find_id_exact_match,
    "DATE_MODIFY_1"                 => $find_date_modify_1,
    "DATE_MODIFY_2"                 => $find_date_modify_2,
    "NAME"                          => $find_name,
    "NAME_EXACT_MATCH"              => $find_name_exact_match,
    "DESCRIPTION"                   => $find_description,
    "DESCRIPTION_EXACT_MATCH"       => $find_description_exact_match,
    "LAMP"                          => $find_lamp,
    "OWNER"                         => $find_owner,
    "OWNER_EXACT_MATCH"             => $find_owner_exact_match,
    "BANNER_COUNT_1"                => $find_banner_count_1,
    "BANNER_COUNT_2"                => $find_banner_count_2,
    "SHOW_COUNT_1"                  => $find_show_count_1,
    "SHOW_COUNT_2"                  => $find_show_count_2,
    "CLICK_COUNT_1"                 => $find_click_count_1,
    "CLICK_COUNT_2"                 => $find_click_count_2,
    "CTR_1"                         => $find_ctr_1,
    "CTR_2"                         => $find_ctr_2,
    "ADMIN_COMMENTS"                => $find_admin_comments,
    "ADMIN_COMMENTS_EXACT_MATCH"    => $find_admin_comments_exact_match
    );
$rsAdvContract = CAdvContract::GetList($by, $order, $arFilter, $is_filtered);
?>

Example.

The following is the sample array obtained by fetching a row of selection returned by this function.

<?
Array
(
    [LAMP] => green
    [ID] => 3
    [ACTIVE] => Y
    [NAME] => contract name
    [DESCRIPTION] => contract description
    [ADMIN_COMMENTS] => administrative comment
    [WEIGHT] => 1000
    [SORT] => 200
    [MAX_SHOW_COUNT] => 1000
    [SHOW_COUNT] => 312
    [MAX_CLICK_COUNT] => 100
    [CLICK_COUNT] => 64
    [EMAIL_COUNT] => 0
    [CREATED_BY] => 2
    [MODIFIED_BY] => 2
    [DEFAULT_STATUS_SID] => READY
    [CTR] => 20.51
    [DATE_SHOW_FROM] => 15.06.2004
    [DATE_SHOW_TO] => 07.07.2009
    [DATE_CREATE] => 07.06.2004 19:04:55
    [DATE_MODIFY] => 24.06.2004 10:56:08
    [BANNER_COUNT] => 12
)
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetUserPermissionArray

CAdvContract::GetUserPermissionArray

text
CAdvContract::GetUserPermissionArray(
 int USER_ID=false
);

The method GetUserPermissionArray returns the array of a specified user permissions by all the contracts.

Parameters

USER_ID
The user ID. If it is not specified, the current user ID is used.

Example

The following is an example of an array returned by the method

Array
(
    [34] => Array
        (
            [0] => ADD
            [1] => VIEW
            [2] => EDIT
        )
    [52] => Array
        (
            [0] => ADD
            [1] => VIEW
        )
)

The array index is the contract ID.
The value is the array of permissions for this contract.
© 2001-2005 Bitrix Bitrix Site Manager


IsModuleAccess

CAdvContract::IsModuleAccess

boolean
CAdvContract::IsModuleAccess(
 char(1) permission
);

The method IsModuleAccess returns true if the current user owns the specified permission, or false otherwise.

Parameters

permission
Symbol specifying an access permission for the advertisement module. The following values are possible:
  • D - access denied;
  • K - handling contracts (advertiser);
  • R - read-only access;
  • T - managing banners;
  • W - full administrative access.
© 2001-2005 Bitrix Bitrix Site Manager


Set

CAdvContract::Set

int
CAdvContract::Set(
 array arFields,
 int CONTRACT_ID="",
 char(1) CHECK_RIGHTS="Y"
);

The method Set creates a new contract, or modifies the existing one if a valid contract ID is passed in the second parameter. Returns the ID of the created contract, or the ID of the modified contract.

Parameters

arFields
An array of the contract parameters. The following keys are possible in this array:
  • ACTIVE - active state flag: if "Y", the contract is active, if "N" the contract is inactive;
  • NAME - contract name;
  • DESCRIPTION - contract description;
  • ADMIN_COMMENTS - administrative comment;
  • WEIGHT - contract weight (priority);
  • SORT - sort order;
  • MAX_SHOW_COUNT - the maximum total number of all the contract banner shows;
  • MAX_CLICK_COUNT - the maximum total number of all the contract banner clicks;
  • DATE_SHOW_FROM - the date banner shows commenced;
  • DATE_SHOW_TO - the date banner shows stopped;
  • DEFAULT_STATUS_SID - the default status for creating new banners; it is also set when the visual aspect of the existing ones becomes modified. The following values are possible:
    • PUBLISHED - the banner is approved and published;
    • READY - the banner is being reviewed;
    • REJECTED - the banner is rejected.
  • arrSHOW_PAGE - array of pages and sections of the site on which contract banners are to be shown;
  • arrNOT_SHOW_PAGE - array of pages and sections of the site on which contract banners cannot be shown;
  • arrTYPE - array of available banner types;
  • arrWEEKDAY - array describing time and days of week for the banner show. The following keys are possible in this array:
    • SUNDAY - array of hours on which the banner is to be shown on Sunday (0-23);
    • MONDAY - the same on Monday;
    • TUESDAY - on Tuesday;
    • WEDNESDAY - on Wednesday;
    • THURSDAY - on Thursday;
    • FRIDAY - on Friday;
    • SATURDAY - on Saturday.
  • arrUSER_VIEW - array of the ID of users who can view parameters, banners and charts of a contract;
  • arrUSER_ADD - array of the ID of users who can view contract parameters and manage banners;
  • arrUSER_EDIT - array of the ID of users who can edit header and description of a contract, assign permissions and manage banners.
CONTRACT_ID
The ID of an existing contract. If omitted, a new contract is created.
CHECK_RIGHTS
Flag indicating that the current user permissions should be checked. If "Y", the current user permissions should be checked. If "N", a contract can be created and modified disregarding the current user permissions.

Example

// The following example adds a new contract
// or modifies the existing one:
<?
if ((strlen($save)>0 ||
    strlen($apply)>0) &&
    $REQUEST_METHOD=="POST")
{
    $arrWEEKDAY = array(
        "SUNDAY"    => $arrSUNDAY,
        "MONDAY"    => $arrMONDAY,
        "TUESDAY"    => $arrTUESDAY,
        "WEDNESDAY"    => $arrWEDNESDAY,
        "THURSDAY"    => $arrTHURSDAY,
        "FRIDAY"    => $arrFRIDAY,
        "SATURDAY"    => $arrSATURDAY
        );
    $arFields = array(
        "ACTIVE"                => $ACTIVE,
        "NAME"                  => $NAME,
        "DESCRIPTION"           => $DESCRIPTION,
        "ADMIN_COMMENTS"        => $ADMIN_COMMENTS,
        "WEIGHT"                => $WEIGHT,
        "SORT"                  => $SORT,
        "MAX_SHOW_COUNT"        => $MAX_SHOW_COUNT,
        "MAX_CLICK_COUNT"       => $MAX_CLICK_COUNT,
        "DATE_SHOW_FROM"        => $DATE_SHOW_FROM,
        "DATE_SHOW_TO"          => $DATE_SHOW_TO,
        "DEFAULT_STATUS_SID"    => $DEFAULT_STATUS_SID,
        "arrSHOW_PAGE"          => split("[\n\r]",$SHOW_PAGE),
        "arrNOT_SHOW_PAGE"      => split("[\n\r]",$NOT_SHOW_PAGE),
        "arrTYPE"               => $arrTYPE,
        "arrWEEKDAY"            => $arrWEEKDAY,
        "arrUSER_VIEW"          => $arrUSER_VIEW,
        "arrUSER_ADD"           => $arrUSER_ADD,
        "arrUSER_EDIT"          => $arrUSER_EDIT
        );
    if ($ID = CAdvContract::Set($arFields, $ID))
    {
        if (strlen($strError)<=0)
        {
            if (strlen($save) > 0)
                LocalRedirect("adv_contract_list.php?lang=".LANG);
            else
                LocalRedirect("adv_contract_edit.php?ID=".$ID."〈=".LANG);
        }
    }
    $DB->PrepareFields("b_adv_contract");
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


CAdvType

The CAdvType class is used with types of banners.

Methods

Method | Description
Set | Creates a new banner type, or modifies the existing one.
GetList | Obtains a filtered list of banner types.
GetByID | Returns a type by its symbolic ID.
Delete | Deletes a type and all banners of this type.
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CAdvType::Delete

boolean
CAdvType::Delete(
 varchar(255) TYPE_SID,
 char(1) CHECK_RIGHTS="Y"
);

The method Delete deletes a type of banners and all banners of this type.

Parameters

TYPE_SID
The symbolic type ID.
CHECK_RIGHTS
If set to "Y", the current user deletion permissions are to be checked. If "N", permissions will not be checked.
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CAdvType::GetByID

record set
CAdvType::GetByID(
 varchar(255) TYPE_SID
);

The method GetByID returns the banner type by its symbolic ID.

Parameters

TYPE_SID
The type symbolic ID.

Example

The following is the example of an array after the method result has been fetched.

<?
Array
(
    [SID] => TOP
    [ACTIVE] => Y
    [SORT] => 10
    [NAME] => Top banner
    [DESCRIPTION] => type description
    [DATE_CREATE] => 03.06.2004 17:27:00
    [DATE_MODIFY] => 03.06.2004 17:27:00
    [CREATED_BY] => 2
    [MODIFIED_BY] => 2
    [BANNER_COUNT] => 63
)
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CAdvType::GetList

record set
CAdvType::GetList(
 varchar &by,
 varchar &order,
 array arFilter=array(),
 boolean &is_filtered
);

The method GetList is intended for obtaining a list of banner types.

Parameters

by
The field ID by which the sorting is performed. The following values are possible:
  • s_sid - by symbolic type ID;
  • s_date_modify - by the date of modification;
  • s_modified_by - by the ID of a user who has modified the type;
  • s_date_create - by the date of creation;
  • s_created_by - by the ID of a user who has created the type;
  • s_active - by the active state flag;
  • s_name - by name;
  • s_banners - by the number of banners of this type;
  • s_description - by description.
order
Sort order. The following values are possible:
  • desc - descending (default);
  • asc - ascending.
arFilter
An array used to filter the values. The following keys are possible in this array:
  • SID - symbolic type ID (complex logic can be used);
  • SID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the symbolic type ID (default). If "N", the method performs loose searches (entry is sufficient);
  • DATE_MODIFY_1 - lower bound of the date range when the type could be modified;
  • DATE_MODIFY_2 - upper bound of the date range when the type could be modified;
  • ACTIVE - active state flag: if "Y", the type is active, if "N" the type is inactive;
  • NAME - name of type (complex logic can be used);
  • NAME_EXACT_MATCH - set to "Y" for exact match searches when filtering by the name of type. If "N", the method performs loose searches (default);
  • DESCRIPTION - description of type (complex logic can be used);
  • DESCRIPTION_EXACT_MATCH - set to "Y" for exact match searches when filtering by the description of type. If "N", the method performs loose searches (default).
is_filtered
On return, this variable contains true if the returned list of types is filtered by any above criteria, or false otherwise.

Example

<?
$FilterArr = Array(
    "find_sid",
    "find_sid_exact_match",
    "find_date_modify_1",
    "find_date_modify_2",
    "find_active",
    "find_name",
    "find_name_exact_match",
    "find_description",
    "find_description_exact_match"
    );
if (strlen($set_filter)>0) InitFilterEx($FilterArr,"ADV_TYPE_LIST","set");
else InitFilterEx($FilterArr,"ADV_TYPE_LIST","get");
if (strlen($del_filter)>0) DelFilterEx($FilterArr,"ADV_TYPE_LIST");
InitBVar($find_sid_exact_match);
InitBVar($find_name_exact_match);
InitBVar($find_description_exact_match);
$arFilter = Array(
    "SID"                       => $find_sid,
    "SID_EXACT_MATCH"           => $find_sid_exact_match,
    "DATE_MODIFY_1"             => $find_date_modify_1,
    "DATE_MODIFY_2"             => $find_date_modify_2,
    "ACTIVE"                    => $find_active,
    "NAME"                      => $find_name,
    "NAME_EXACT_MATCH"          => $find_name_exact_match,
    "DESCRIPTION"               => $find_description,
    "DESCRIPTION_EXACT_MATCH"   => $find_description_exact_match,
    );
$rsAdvType = CAdvType::GetList($by, $order, $arFilter, $is_filtered);
?>

Example

The following is the sample array obtained by fetching a row of selection returned by this function.

<?
Array
(
    [SID] => TOP
    [ACTIVE] => Y
    [SORT] => 10
    [NAME] => Top banner
    [DESCRIPTION] => description of type
    [DATE_CREATE] => 03.06.2004 17:27:00
    [DATE_MODIFY] => 03.06.2004 17:27:00
    [CREATED_BY] => 2
    [MODIFIED_BY] => 2
    [BANNER_COUNT] => 63
)
?>
© 2001-2005 Bitrix Bitrix Site Manager


Set

CAdvType::Set

varchar(255)
CAdvType::Set(
 array arFields,
 varchar(255) TYPE_SID="",
 char(1) CHECK_RIGHTS="Y"
);

The method Set creates a new type of banners, or modifies the existing one if a symbolic type ID is passed in the second parameter. Returns the created type ID, or the modified type ID.

Parameters

arFields
An array of the type parameters. The following keys are possible in this array:
  • SID - symbolic type ID (used in the public section when displaying banners by their type);
  • ACTIVE - active state flag: if "Y", the type is active, if "N" the type is inactive;
  • NAME - name of type;
  • DESCRIPTION - description of type;
  • SORT - sort order of this type in lists.
TYPE_SID
The ID of an existing type. If omitted, a new type is created.
CHECK_RIGHTS
Flag indicating that the current user permissions should be checked. If "Y", the current user permissions should be checked. If "N", a type can be created and modified disregarding the current user permissions.

Example

<!--
The following example adds a new type
or modifies the existing one:
 -->
<?
if ((strlen($save)>0 ||
    strlen($apply)>0) &&
    $REQUEST_METHOD=="POST")
{
    $arFields = array(
        "SID"               => $SID,
        "ACTIVE"            => $ACTIVE,
        "SORT"              => $SORT,
        "NAME"              => $NAME,
        "DESCRIPTION"       => $DESCRIPTION
        );
    if ($SID = CAdvType::Set($arFields, $OLD_SID))
    {
        if (strlen($strError)<=0)
        {
            if (strlen($save) > 0)
                LocalRedirect("adv_type_list.php?lang=".LANG);
            else
                LocalRedirect("adv_type_edit.php?SID=".$SID."〈=".LANG);
        }
    }
    $DB->PrepareFields("b_adv_type");
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Notes for developers - Bitrix Site Manager - Content Management & Portal Solutions

Notes for developers

Before calling any of the module functions or class methods, you have first to check for its availability and include the module using the following code:

<?
if (CModule::IncludeModule("catalog"))
{
    // call module functions here
}
?>

If you want to use any information block as a commercial catalog, you need to check whether this information block is a catalog (i.e. it is attached to the Commercial Catalog module) using the following code:

<?
if (CCatalog::GetByID($IBLOCK_ID))
{
    // now you can handle the information block
    // as a catalog
}?>

You can combine the above stated code into a single condition that checks for the module availability and includes it, as well as verifies for the ability of an information block $IBLOCK_ID to behave as a catalog:

<?
if (CModule::IncludeModule("catalog") &&
    CCatalog::GetByID($IBLOCK_ID))
{
    // now you can handle the information block
    // as a catalog
}
?>

See Also

Displaying prices
Adding items to basket

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Adding items to basket - Bitrix Site Manager - Content Management & Portal Solutions

Adding items to basket

The Commercial Catalog module includes wrapper functions that are used in connection with the e-Store module.

Add2Basket

int
Add2Basket(
 int PRICE_ID [,
 int QUANTITY ]
);

The Add2Basket function adds a product item to the shopping cart given the price code PRICE_ID and the required QUANTITY (one by default) and returns the product position ID in the shopping cart.

Parameters

Parameter | Description
PRICE_ID | Product item price code.
QUANTITY | Number of items to be added (one by default).

Example

<?
if (CModule::IncludeModule("sale") &&
    CModule::IncludeModule("catalog"))
{
    if (($action == "ADD2BASKET" || $action == "BUY") &&
        IntVal($PRICE_ID)>0)
    {
        Add2Basket($PRICE_ID);
        if ($action == "BUY")
            LocalRedirect("basket.php");
    }
}
?>

Callback Functions

array
CatalogBasketCallback(
 int PRODUCT_ID [,
 int QUANTITY] )

);
void
CatalogBasketOrderCallback(
 int PRODUCT_ID,
 int QUANTITY
);

The callback functions are used for processing the shopping cart and order operations. See the e-Store module reference for more information on the callback functions.


Displaying prices - Bitrix Site Manager - Content Management & Portal Solutions

Displaying prices

A set of special functions is used for displaying the information pertaining to the Commercial Catalog module in the public section of the site. Note that in terms of the Commercial Catalog module, a product is an element of an information block. This means that if a function requires a product ID to be passed on input, you have to pass the ID of an information block element.

Function | Description
GetCatalogGroups | Returns a sorted list of price types.
GetCatalogGroup | Returns an array describing the price type, by its ID.
GetCatalogProductPrice | Returns the specified price type for the specified product.
GetCatalogProductPriceList | Returns an array of the product prices given the product ID, optionally sorted.
GetCatalogProduct | Returns a product by its ID.
FormatCurrency | Formats the price using the specified formatting options.

GetCatalogGroups

CDBResult
GetCatalogGroups(
 string by,
 string order
);

The function returns a list of price types. The list returned is sorted by the field by in the order order.

Parameters

Parameter Description
by Field by which the list entries are to be sorted. Can be one of the following:
  • SORT - by the field "Sort weight" (default option);
  • NAME - by the field "Name";
  • ID - by the field "ID".
order Sort order. Can be one of the following:
  • ASC - ascending (default);
  • DESC - descending.

Return Values

The function returns a sorted list of the CDBResult records each having the following keys.

Parameter | Description
ID | Price type ID.
NAME | Internal name of the price type.
BASE | If "Y", this is the base price type. Otherwise "N".
SORT | Value of the field Sort weight of the price type.
NAME_LANG | Name of the price type for the current site.
CAN_ACCESS | If "Y", the current user is allowed to view prices of this type. If "N", prices of this type should be hidden.
CAN_BUY | If "Y", the current user is allowed to purchase at prices of this type. Otherwise "N".

GetCatalogGroup

array
GetCatalogGroup(
 int CATALOG_GROUP_ID
);

The function returns a price type description array by the specified ID.

Parameters

Parameter | Description
CATALOG_GROUP_ID | Price type ID.

Return Values

The function GetCatalogGroup returns an array of the same structure as each entry in a list returned by the function GetCatalogGroups.

GetCatalogProductPrice

array
GetCatalogProductPrice(
 int PRODUCT_ID,
 int CATALOG_GROUP_ID
);

The function returns the price of the type CATALOG_GROUP_ID for the product PRODUCT_ID.

Parameters

Parameter | Description
PRODUCT_ID | Product ID.
CATALOG_GROUP_ID | Price type ID.

Return Values

The function GetCatalogProductPrice returns an array with the following keys.

Parameter | Description
ID | Price ID.
PRODUCT_ID | Product ID.
EXTRA_ID | The ID of a discount (or extra).
CATALOG_GROUP_ID | Price type ID.
PRICE | Price value.
CURRENCY | Currency of price.
CATALOG_GROUP_NAME | Name of the price type for the current site.
CAN_ACCESS | If "Y", the current user is allowed to view prices of this type. If "N", prices of this type should be hidden.
CAN_BUY | If "Y", the current user is allowed to purchase at prices of this type. Otherwise "N".

GetCatalogProductPriceList

array
GetCatalogProductPriceList(
 int PRODUCT_ID,
 string by,
 string order
);

The function returns an array of prices for the product PRODUCT_ID sorted by the field by in the order order.

Parameters

Parameter | Description
PRODUCT_ID | Product ID.
by Field by which the list entries are to be sorted. Can be one of the following:
  • ID - by the field "ID" (default option);
  • SORT - by the field "Sort weight";
  • CURRENCY - by the field "Currency";
  • CATALOG_GROUP_ID - by the field "Price type ID".
order Sort order. Can be one of the following:
  • ASC - ascending (default);
  • DESC - descending.

Return Values

The function GetCatalogProductPriceList returns an array of the same structure as each entry in a list returned by the function GetCatalogProductPrice.

GetCatalogProduct

array
GetCatalogProduct(
 int PRODUCT_ID
);

The function returns information on a product by its ID.

Parameters

Parameter | Description
PRODUCT_ID | Product ID.

Return Values

The function GetCatalogProduct returns an array with the following keys.

Parameter | Description
ID | Product ID.
QUANTITY | Quantity of product units.
QUANTITY_TRACE | "Y" tells the system to keep track of quantity of the product.
WEIGHT | Product weight.

FormatCurrency

string
FormatCurrency(
 double PRICE,
 string CURRENCY
);

The function formats the price using the formatting options assigned to the CURRENCY.

Parameters

Parameter | Description
PRICE | Price value.
CURRENCY | Currency.

Return Values

String containing the value in the requested format.

Example

The following code illustrates the use of the Commercial Catalog module functions.

<?
//
// Display price types available to the current user
//
$db_res = GetCatalogGroups(($b="SORT"), ($o="ASC"));
while ($res = $db_res->Fetch())
{
    if ($res["CAN_ACCESS"]=="Y")
    {
        echo $res["NAME_LANG"];
    }
}
?>

<?
//
// Display prices of the type $TYPE_ID
// for the product $PRODUCT_ID
//
$arProduct = GetCatalogProduct($PRODUCT_ID);
if ($res = GetCatalogProductPrice($PRODUCT_ID, $TYPE_ID))
{
    if ($res["CAN_ACCESS"]=="Y")
    {
        echo FormatCurrency($res["PRICE"], $res["CURRENCY"]);
        echo " (price type ".$res["CATALOG_GROUP_NAME"].") ";
        // Display the positive purchase offer to the current user
        // if the product $PRODUCT_ID can be purchased
        // at the price of the type $TYPE_ID
        // and the product is either available in stock or
        // if its availability is not tracked
        if ($res["CAN_BUY"]=="Y" &&
            (IntVal($arProduct["QUANTITY"])>0 ||
            $arProduct["QUANTITY_TRACE"]!="Y"))
        {
            echo "Buy";
        }
    }
}
?>

<?
//
// Display a list of allowed price types
// for the product $PRODUCT_ID
//
$arProduct = GetCatalogProduct($PRODUCT_ID);
$arPrice = GetCatalogProductPriceList($PRODUCT_ID, "SORT", "ASC");
$bCanBuy = False;
for ($i = 0; $i<count($arPrice); $i++)
{
    if ($arPrice[$i]["CAN_ACCESS"]=="Y")
    {
        if ($arPrice[$i]["CAN_BUY"]=="Y" &&
            (IntVal($arProduct["QUANTITY"])>0 ||
            $arProduct["QUANTITY_TRACE"]!="Y"))
        {
            $bCanBuy = True;
        }
        echo $arPrice[$i]["CATALOG_GROUP_NAME"].": ";
        echo FormatCurrency($arPrice[$i]["PRICE"],
                            $arPrice[$i]["CURRENCY"])."<br>";
    }
}

// Display the positive purchase offer to the current user
// if the product can be purchased at one of the available prices
// and the product is either available in stock or
// if its availability is not tracked
if ($bCanBuy)
{
    echo "Buy";
}
?>


Classes (commercial catalog) - Bitrix Site Manager - Content Management & Portal Solutions

Classes

Warning
The Commercial Catalog module is an add-on to the Information Blocks module. It cannot be used stand-alone.

The Commercial Catalog module uses facilities of the Information Blocks module to build and maintain product properties and the tree of groups. An element of an information block that is used as a commercial catalog is enriched with additional records describing properties specific to a product (weight, quantity in stock etc.). The methods of the class CCatalogProduct are used to add such properties to an information block element.

The Commercial Catalog module exports the following PHP classes.

Classes

Class | Description
CCatalog | Contains methods used to disable or enable the catalog function of an information block.
CCatalogGroup | Class that is used to manage price types of the commercial catalog.
CExtra | This class handles extras and discounts to the base price.
CPrice | Allows to create and maintain your prices (price offers).
CCatalogProduct | Class used to control product properties, i.e. ones that relate to a product as such (weight, quantity etc.).


Add

CCatalog::Add

bool
CCatalog::Add(
 array arFields
);

The method Add is used to add a new record to the binding table that describes relationships between the information block and the Commercial Catalog module.

Parameters

Parameter Description
arFields Binding description array. The array has the following format:
$arFields = array(
   "IBLOCK_ID" => [information block ID],
   "YANDEX_EXPORT" => [specifies the export to
                       a special XML file is required (Y/N)]
);

Return Values

Returns True on success, or False otherwise.


Delete

CCatalog::Delete

bool
CCatalog::Delete(
 int ID
);

The method Delete deletes the binding between the information block specified by the ID and the commercial catalog. All product configurations and offers pertaining to this block are also deleted. Descriptions of products relating to the information block element are not deleted.

Parameters

Parameter | Description
ID | The ID of the information block used as a catalog.

Return Values

Returns True on success, or False otherwise.


GetByID

CCatalog::GetByID

array
CCatalog::GetByID(
 int ID
);

The method GetByID returns an array with the catalog parameters including some of the information block related ones.

Parameters

Parameter | Description
ID | The ID of the information block used as a catalog.

Return Values

Returns the associated array with the following keys.

Key | Description
IBLOCK_ID | Information block ID.
IBLOCK_TYPE_ID | Information block type.
NAME | Name of the information block.
YANDEX_EXPORT | Specifies the export to a special XML file is required (Y/N).


GetList

CCatalog::GetList

CDBResult
CCatalog::GetList(
 string &by,
 string &order,
 array arFilter = Array()
);

The method GetList returns a collection of catalogs satisfying the passed filter arFilter, sorted by the parameter by in the order order.

Parameters

Parameter Description
by Field by which the collection entries are to be sorted. Can be one of the following:
  • SORT - sort weight (default option);
  • NAME - information block name;
  • IBLOCK_TYPE_ID - information block type ID.
order Sort order. Can be one of the following:
  • ASC - ascending (default);
  • DESC - descending.
arFilter Filter by which entries are to be sorted. The filter is an associated array with the field names as keys and the conditions as values. The following values are used:
  • ACTIVE - active state of the information block;
  • IBLOCK_TYPE_ID - information block type;
  • YANDEX_EXPORT - specifies the export to a special XML file is required (Y/N).

Return Values

Returns an instance of the class CDBResult containing a collection of arrays with the following keys.

Key | Description
IBLOCK_ID | Information block ID.
IBLOCK_TYPE_ID | Information block type.
NAME | Information block name.


Update

CCatalog::Update

bool
CCatalog::Update(
 int ID,
 array arFields
);

The method Update is used to update the record specified by ID in the information block to the Commercial Catalog module binding table.

Parameters

Parameter | Description
ID | The ID of the record which is to be updated.
arFields The associated array containing new record values. The array has parameter names as keys and new values as values. The possible keys include:
  • YANDEX_EXPORT - specifies the export to a special XML file is required (Y/N).

Return Values

Returns True on success, or False otherwise.


Add

CCatalogGroup::Add

int
CCatalogGroup::Add(
 array arFields
);

The method Add adds a new price type. This method stores both all the language-dependent and independent parameters. Additionally, you can specify user groups allowed to view and purchase products at prices of this type.

Parameters

Parameter Description
arFields Associated array with the parameters of the new price type. In this array, keys are the parameters names. The following key names are allowed.
  • NAME - internal name of the price type;
  • SORT - sort weight;
  • USER_GROUP - array with the ID's of user groups that are allowed to view prices of this type;
  • USER_GROUP_BUY - array with the ID's of user groups that are allowed to purchase items at prices of this type;
  • USER_LANG - array with the language-dependent parameters of the price type. Keys in this array are the language ID's, and values are names of the price type in the corresponding language.

Return Values

Returns the ID of the new price type on success, or false otherwise.

Example

<?
$arFields = array(
   "NAME" => "retail",
   "SORT" => 100,
   "USER_GROUP" => array(2, 4),   // allow members of groups 2 and 4 to view
   "USER_GROUP_BUY" => array(2),  // allow members of group 2 to purchase
   "USER_LANG" => array(
      "fr" => "Prix de détail",
      "en" => "Retail price"
      )
);

$ID = CCatalogGroup::Add($arFields);
if ($ID<=0)
   echo "Error adding the price type";
?>


Delete

CCatalogGroup::Delete

bool
CCatalogGroup::Delete(
 int ID
);

The method Delete deletes the price type identified by the ID. This also deletes all prices of this type. Note that you cannot delete the base price type.

Parameters

Parameter | Description
ID | The ID of the price type to be deleted.

Return Values

Returns True on success or False otherwise.


GetBaseGroup

CCatalogGroup::GetBaseGroup

array CCatalogGroup::GetBaseGroup();

The method GetBaseGroup returns the ID and the internal name of the base price type. Results of the method calls are cached; this means that subsequent calls within one page do not incur numerous requests to the database.

Prices specified using the discounts or extras are built on the base price. A concept of base price is used in the administrative section only; it does not affect either visual or meaningful aspect of the public section of the site.

Return Values

The function returns the associated array with the following keys.

Key | Description
ID | The ID of the base price type.
NAME | Internal name of the base price type.


GetByID

CCatalogGroup::GetByID

array
CCatalogGroup::GetByID(
 int ID,
 string lang = LANGUAGE_ID
);

The method GetByID returns parameters of the price type identified by the ID. The returned parameters include the language-dependent parameters for the specified language lang.

Parameters

Parameter | Description
ID | Price type ID.
lang | Language ID. By default, current language is used.

Return Values

Returns the associated array with the following keys.

Key | Description
ID | Price type ID.
NAME | Internal name of the price type.
BASE | Indicates that the returned type is the base price type ("Y"). Otherwise, value of this key is "N".
SORT | Sort weight.
CAN_ACCESS | If "Y", the current user is allowed to view prices of this type. If "N", prices of this type should be hidden.
CAN_BUY | If "Y", the current user is allowed to purchase at prices of this type. Otherwise "N".
NAME_LANG | Name of the price type in the language lang.

Example

<?
$rn = CCatalogGroup::GetByID($ID);
if ($rn["CAN_ACCESS"]=="Y")
   echo "You can view prices ".$rn["NAME_LANG"]."<br>";
if ($rn["CAN_BUY"]=="Y")
   echo "You can buy at prices ".$rn["NAME_LANG"]."<br>";
?>


GetGroupsList

CCatalogGroup::GetGroupsList

CDBResult
CCatalogGroup::GetGroupsList(
 array arFilter = Array()
);

The method GetGroupsList returns records from the binding table that describes relationships between price types and site users. The returned array is filtered using the parameters specified in arFilter.

Parameters

Parameter Description
arFilter Array with fields by which the returned records are to be filtered. Keys are the field names; values are conditions. The array can have the following keys:
  • CATALOG_GROUP_ID - price type ID;
  • GROUP_ID - user group ID;
  • BUY - flag with values: "Y" - users of this group can purchase products at prices of this type; "N" - users of this group can view prices of this type;
  • ID - record ID.

Return Values

An instance of the class CDBResult containing a set of the associated arrays with the following keys.

Key | Description
ID | Record ID.
CATALOG_GROUP_ID | Price type ID.
GROUP_ID | User group ID.
BUY Flag (Y/N) specifying one of the following:
  • "Y" - users of this group can purchase products at prices of this type;
  • "N" - users of this group can view prices of this type.

Example

<?
// Print ID's of price types
// at which users of the group 2 can purchase products
$db_res = CCatalogGroup::GetGroupsList(array("GROUP_ID"=>2, "BUY"=>"Y"));
while ($ar_res = $db_res->Fetch())
{
   echo $ar_res["CATALOG_GROUP_ID"].", ";
}
?>


GetList

CCatalogGroup::GetList

CDBResult
CCatalogGroup::GetList(
 string &by,
 string &order,
 array arFilter = Array(),
 string lang = LANGUAGE_ID
);

The method GetList returns a set of price types satisfying the specified filter arFilter. The returned records are sorted by the parameter by in the order order.

Parameters

Parameter | Description
by Field by which the list entries are to be sorted. Can be one of the following:
  • SORT - by the field "Sort weight" (default option);
  • BASE - by the flag denoting the base price type;
  • NAME - by the field "Name" (internal name);
  • ID - by the field "ID".
order Sort order. Can be one of the following:
  • ASC - ascending (default);
  • DESC - descending.
arFilter Array with fields by which the returned records are to be filtered. Keys are the field names; values are conditions. The array can have the following keys:
  • BASE - flag "base price type";
  • NAME - internal name of the price type.
lang | Language ID. By default, current language is used.

Return Values

An instance of the class CDBResult containing a set of the associated arrays with the following keys.

Key | Description
ID | Price type ID.
NAME | Internal name of the price type.
BASE | Indicates that the returned type is the base price type ("Y"). Otherwise, value of this key is "N".
SORT | Sort weight.
CAN_ACCESS | If "Y", the current user is allowed to view prices of this type. If "N", prices of this type should be hidden.
CAN_BUY | If "Y", the current user is allowed to purchase at prices of this type. Otherwise "N".
NAME_LANG | Name of the price type in the language lang.

Example

<?
// Select all price types with the internal name "retail"
$dbPriceType = CCatalogGroup::GetList(($v1="SORT"),
                                      ($v2="ASC"),
                                      array("NAME" => "retail"));

while ($arPriceType = $dbPriceType->Fetch())
{
    echo $arPriceType["NAME_LANG"]." - ".$arPriceType["CAN_ACCESS"]."<br>";
}
?>


Update

CCatalogGroup::Update

bool
CCatalogGroup::Update(
 int ID,
 array arFields
);

The method Update is used to update information on the price type identified by the ID. The parameter arFields contain new values of the updated price type. This method can update both all the language-dependent and independent parameters. Additionally, you can specify user groups allowed to view and purchase products at prices of this type.

Parameters

Parameter | Description
ID | The ID of the price type to be updated.
arFields Associated array with the parameters of the updated price type. In this array, keys are the parameters names. The following key names are allowed.
  • NAME - internal name of the price type;
  • SORT - sort weight;
  • USER_GROUP - array with the ID's of user groups that are allowed to view prices of this type;
  • USER_GROUP_BUY - array with the ID's of user groups that are allowed to purchase items at prices of this type;
  • USER_LANG - array with the language-dependent parameters of the price type. Keys in this array are the language ID's, and values are names of the price type in the corresponding language.

Return Values

Returns True on success or False otherwise.

Example

<?
$arFields = array(
   "NAME" => "retail",
   "SORT" => 100,
   "USER_GROUP" => array(2, 4),   // allow members of groups 2 and 4 to view
   "USER_GROUP_BUY" => array(2),  // allow members of group 2 to purchase
   "USER_LANG" => array(
      "fr" => "Prix de détail",
      "en" => "Retail price"
      )
);

if (!CCatalogGroup::Update($ID, $arFields))
   echo "Error updating price type";
?>


Add

CCatalogProduct::Add

bool
CCatalogProduct::Add(
 array arFields
);

The method Add adds the product specifications to a catalog element that represents the affected product. The method can also be used to update the existing specifications.

Parameters

Parameter Description
arFields Associated array with the specifications of the product. In this array, keys are the parameters names. The following key names are allowed.
  • ID - product ID (catalog element. Required key);
  • QUANTITY - quantity of product items in stock;
  • QUANTITY_TRACE - "Y" tells the system to keep track of quantity of the product;
  • WEIGHT - product weight.

Return Values

Returns True on success or False otherwise.


Delete

CCatalogProduct::Delete

bool
CCatalogProduct::Delete(
 int ID
);

The method Delete deletes the product properties and specifications from the catalog element.

Parameters

Parameter | Description
ID | Product ID (catalog element).

Return Values

Returns True on success or False otherwise.


GetByID

CCatalogProduct::GetByID

array
CCatalogProduct::GetByID(
 int ID
);

The method GetByID returns an array of the product properties. The returned data pertains to the product itself, these are not the catalog element properties.

Parameters

Parameter | Description
ID | Product ID.

Return Values

Associated array with the following keys:

Key | Description
ID | Product ID.
QUANTITY | Quantity of product items in stock.
QUANTITY_TRACE | "Y" tells the system to keep track of quantity of the product and decrement the counter upon successful order.
WEIGHT | Product item weight.

Example

<?
$ID = 5;
$ar_res = CCatalogProduct::GetByID($ID);
echo "<br>Product #".$ID." has the following parameters:<pre>";
print_r($ar_res);
echo "</pre>";
?>


GetByIDEx

CCatalogProduct::GetByIDEx

array
CCatalogProduct::GetByIDEx(
 int ID
);

The method GetByIDEx returns an array of the product properties. The returned data contains all properties of the product including the catalog element properties.

Parameters

Parameter | Description
ID | Product ID.

Return Values

Returns the associated array of the product properties on success, or False otherwise. The Example shows how to view all available properties of the product.

Example

<?
$ID = 5;
$ar_res = CCatalogProduct::GetByIDEx($ID);
echo "<br>Product #".$ID." has the following parameters:<br><pre>";
print_r($ar_res);
echo "</pre>";
?>


GetList

CCatalogProduct::GetList

CDBResult
CCatalogProduct::GetList(
 string &by,
 string &order,
 array arFilter = Array()
);

The method GetList returns properties of products sorted and optionally filtered. The parameters returned pertain to a product itself; these are not catalog element properties.

Parameters

Parameter Description
by Field by which the returned collection entries are to be sorted. Can be one of the following:
  • ID - product ID (default);
  • QUANTITY - quantity of product items in stock;
  • QUANTITY_TRACE - "Y" tells the system to keep track of quantity of the product;
  • WEIGHT - product weight.
order Sort order. Can be one of the following:
  • ASC - ascending (default);
  • DESC - descending.
arFilter Filter by which entries are to be sorted. The filter is an associated array with the field names as keys and the conditions as values. The following values are used:
  • QUANTITY - quantity of product items in stock;
  • QUANTITY_TRACE - "Y" tells the system to keep track of quantity of the product;
  • WEIGHT - product weight.

Note
The filter allows only equation operator "=" ; it does not support operators like >, <= etc.

Return Values

An instance of the class CDBResult containing a set of the associated arrays with the following keys.

Key | Description
ID | Product ID.
QUANTITY | Quantity of product items in stock.
QUANTITY_TRACE | "Y" tells the system to keep track of quantity of the product and decrement the counter upon successful order.
WEIGHT | Product item weight.

Example

<?
//
// Display ID's of the first 10 products that are
// most in stock and automatically tracked
//
$ind = 0;
$db_res = CCatalogProduct::GetList(($b="QUANTITY"),
                                   ($o="DESC"),
                                   array("QUANTITY_TRACE"=>"Y"));

while (($ar_res = $db_res->Fetch()) && ($ind < 10))
{
    echo $ar_res["ID"].", ";
    $ind++;
}
?>


QuantityTracer

CCatalogProduct::QuantityTracer

bool
CCatalogProduct::QuantityTracer(
 int PRODUCT_ID,
 int DELTA_QUANTITY
);

The method QuantityTracer decrements the number of products in stock. The method succeeds if only the resulting quantity is not below zero and the specified product has the flag Reduce quantity upon order set.

Parameters

Parameter | Description
PRODUCT_ID | The ID of the product whose quantity is to be changed.
DELTA_QUANTITY | Specifies the number to be subtracted from the product counter.

Return Values

Returns True on success or False otherwise.

Example

<?
// Decrement the quantity of product "5" in stock by 12 items
CCatalogProduct::QuantityTracer(5, 12);
?>


Update

CCatalogProduct::Update

bool
CCatalogProduct::Update(
 int ID,
 array arFields
);

The method Update updates the product parameters. The properties updated pertain to the product itself; these do not relate to the commercial catalog element.

Parameters

Parameter | Description
ID | Product ID.
arFields Associated array with the new values of the product properties. In this array, keys are the parameters names. The following key names are allowed.
  • QUANTITY - quantity of product items in stock;
  • QUANTITY_TRACE - "Y" tells the system to keep track of quantity of the product;
  • WEIGHT - product weight.

Return Values

Returns True on success or False otherwise.


Add

CExtra::Add

bool
CExtra::Add(
 array arFields
);

The method Add adds a new record to the table of discounts.

Parameters

Parameter Description
arFields Associated array with the following keys:
  • NAME - name of the discount;
  • PERCENTAGE - percentage value of the discount (both positive and negative values allowed).

Return Values

Returns True on success or False otherwise.


Delete

CExtra::Delete

bool
CExtra::Delete(
 int ID
);

The method Delete deletes the specified discount from the database. If any price has been fixed using the base price and this discount, such a price is assigned an absolute number. The final value of an affected price does not change.

Parameters

Parameter | Description
ID | Discount ID.

Return Values

Returns True on success or False otherwise.


GetByID

CExtra::GetByID

array
CExtra::GetByID(
 int ID
);

The method GetByID returns the discount properties.

Parameters

Parameter | Description
ID | Discount ID.

Return Values

Associated array with the following keys.

Key | Description
ID | Discount ID.
NAME | Name of the discount.
PERCENTAGE | Percentage value of the discount. The value can be both positive and negative number.


GetList

CExtra::GetList

CDBResult
CExtra::GetList(
 string &by,
 string &order
);

The method GetList returns a list of discounts. The list returned is sorted by the parameter by in the order order.

Parameters

Parameter Description
by Name of the field by which the list of discounts is to be sorted. Names include the following:
  • NAME - by the name of the discount (default);
  • PERCENTAGE - by the percentage value of the discount.
order Sort order. Can be one of the following:
  • ASC - ascending (default);
  • DESC - descending.

Return Values

An instance of the CDBResult class containing a set of the associated arrays with the following keys.

Key | Description
ID | Discount ID.
NAME | Name of the discount.
PERCENTAGE | Percentage value of the discount. The value can be both positive and negative number.


SelectBox

CExtra::SelectBox

string
CExtra::SelectBox(
 string sFieldName,
 string sValue,
 string sDefaultValue = "",
 string JavaChangeFunc = "",
 string sAdditionalParams = ""
);

The method SelectBox returns the HTML code that can be used to display the drop-down list of discounts. The results of the method calls are cached; this means that subsequent calls within one page do not incur numerous requests to the database.

Parameters

Parameter | Description
sFieldName | Value of the NAME attribute of the SELECT tag used for the drop-down list of discounts.
sValue | Initial value.
sDefaultValue | Name of the special value describing the void discount (e.g. All or No).
JavaChangeFunc | Name of the JavaScript function handler of the OnChange event of the list. If empty, the OnChange event is not handled.
sAdditionalParams | Additional attributes to be included in the SELECT tag.

Return Values

Returns the string with the HTML code of the list.

Example

<?
echo CExtra::SelectBox("CAT_EXTRA",
                       2,
                       "No",
                       "ChangeExtra()",
                       "class='typeselect'");
?>


Update

CExtra::Update

bool
CExtra::Update(
 int ID,
 array arFields
);

The method Update updates the specified discount parameters with the specified values.

Parameters

Parameter | Description
ID | Discount ID.
arFields Associated array of the new parameter values with the following keys:
  • NAME - name of the discount;
  • PERCENTAGE - percentage value of the discount (both positive and negative values allowed);
  • RECALCULATE - if "Y", all prices specified using this discount are recalculated.

Return Values

Returns True on success or FALSE otherwise.


Add

CPrice::Add

bool
CPrice::Add(
 array arFields
);

The method Add adds a new price to a product.

Parameters

Parameter Description
arFields Associated array of the price parameters with the following keys.
  • PRODUCT_ID - product ID;
  • EXTRA_ID - the ID of discount or extra;
  • CATALOG_GROUP_ID - price type ID;
  • PRICE - price value;
  • CURRENCY - currency of the price.
If the discount ID is specified, the created price will be automatically recalculated when the base price or discount changes.

Return Values

Returns True on success or False otherwise.

Example

<?
// Assign the price of USD29.95 of the type 2
// to the product with the ID of 15

$PRODUCT_ID = 15;
$PRICE_TYPE_ID = 2;

$arFields = Array(
    "PRODUCT_ID" => $PRODUCT_ID,
    "CATALOG_GROUP_ID" => $PRICE_TYPE_ID,
    "PRICE" => 29.95,
    "CURRENCY" => "USD"
);

$res = CPrice::GetList(($o=""),
                       ($b=""),
                       Array("PRODUCT_ID"=>$PRODUCT_ID,
                             "CATALOG_GROUP_ID"=>$PRICE_TYPE_ID));

if ($arr = $res->Fetch())
{
    CPrice::Update($arr["ID"], $arFields);
}
else
{
    CPrice::Add($arFields);
}
?>


Delete

CPrice::Delete

bool
CPrice::Delete(
 int ID
);

The method Delete deletes the price of the specified ID.

Parameters

Parameter | Description
ID | Price ID.

Return Values

Returns True on success or False otherwise.

Example

<?
// Delete the price with the ID of 11
CPrice::Delete(11);
?>


GetBasePrice

CPrice::GetBasePrice

array
CPrice::GetBasePrice(
 int PRODUCT_ID
);

The method GetBasePrice returns the base price description array of the specified product. A base price is the price of the base price type.

Parameters

Parameter | Description
PRODUCT_ID | Product ID.

Return Values

Associated array with the following keys.

Key | Description
ID | Price ID.
PRODUCT_ID | Product ID.
EXTRA_ID | The ID of the applicable discount (or extra).
CATALOG_GROUP_ID | Price type ID.
PRICE | Base price value.
CURRENCY | Currency of the base price.

Example

<?
$ar_res = CPrice::GetBasePrice(11);
echo "Base price of the product 11 is ".$ar_res["PRICE"]." ".$ar_res["CURRENCY"]."<br>";
echo "Formatted base price: ".CurrencyFormat($ar_res["PRICE"], $ar_res["CURRENCY"]);
?>


GetByID

CPrice::GetByID

array
CPrice::GetByID(
 int ID
);

The method GetByID returns the description array of the specified price .

Parameters

Parameter | Description
ID | Price ID.

Return Values

Associated array with the following keys.

Key | Description
ID | Price ID.
PRODUCT_ID | Product ID.
EXTRA_ID | The ID of the applicable discount (or extra).
CATALOG_GROUP_ID | Price type ID.
PRICE | Price value.
CURRENCY | Currency of the price.
CAN_ACCESS | If "Y", the current user is allowed to view prices of this type. If "N", prices of this type should be hidden.
CAN_BUY | If "Y", the current user is allowed to purchase at prices of this type. Otherwise "N".
CATALOG_GROUP_NAME | Name of the price type in the current language.

Example

<?
$ID = 11;
$arPrice = CPrice::GetByID($ID);
echo "Price of type ".$arPrice["CATALOG_GROUP_NAME"].
     " for the product #".$ID.": ";
echo CurrencyFormat($arPrice["PRICE"],
                    $arPrice["CURRENCY"])."<br>";
echo "You are ".(($arPrice["CAN_ACCESS"]=="Y") ?
         "allowed" :
         "not allowed")." to view this price.";
?>


GetList

CPrice::GetList

CDBResult
CPrice::GetList(
 string &by,
 string &order,
 array arFilter = Array()
);

The method GetList returns a set of arrays each describing a single price. The set returned is sorted and optionally filtered.

Parameters

Parameter Description
by Name of the field by which the list of prices is to be sorted. Names include the following:
  • ID - price ID (default);
  • PRODUCT_ID - product ID;
  • EXTRA_ID - discount ID;
  • CATALOG_GROUP_ID - price type ID;
  • PRICE - price value;
  • CURRENCY - currency of price;
  • SORT - price type sort weight.
order Sort order. Can be one of the following:
  • ASC - ascending (default);
  • DESC - descending.
arFilter Array with fields by which the returned prices are to be filtered. Keys are the field names; values are conditions. The array can have the following keys:
  • PRODUCT_ID - product ID;
  • EXTRA_ID - discount ID;
  • CATALOG_GROUP_ID - price type ID;
  • CURRENCY - currency;
  • BASE - flag "base price type".
Current version of the filter allows to specify negation operations by inserting the symbol ! at the beginning of the key value.

Return Values

An instance of the class CDBResult containing a set of the associated arrays with the following keys.

Key | Description
ID | Price ID.
PRODUCT_ID | Product ID.
EXTRA_ID | The ID of a discount (or extra).
CATALOG_GROUP_ID | Price type ID.
PRICE | Price value.
CURRENCY | Currency.
CAN_ACCESS | If "Y", the current user is allowed to view prices of this type. If "N", prices of this type should be hidden.
CAN_BUY | If "Y", the current user is allowed to purchase at prices of this type. Otherwise "N".
CATALOG_GROUP_NAME | Name of the price type in the current language.

Example

<?
// Display a price of the type $PRICE_TYPE_ID for the product $PRODUCT_ID
$db_res = CPrice::GetList(($b=""),
                          ($o=""),
                          Array("PRODUCT_ID"=>$PRODUCT_ID,
                                "CATALOG_GROUP_ID"=>$PRICE_TYPE_ID));

if ($ar_res = $db_res->Fetch())
{
    echo CurrencyFormat($ar_res["PRICE"],
                        $ar_res["CURRENCY"]);
}
else
{
    echo "Price not found!";
}
?>


SetBasePrice

CPrice::SetBasePrice

bool
CPrice::SetBasePrice(
 int PRODUCT_ID,
 float PRICE,
 string CURRENCY
);

The method SetBasePrice is used to assign a base price to the specified product.

Parameters

Parameter | Description
PRODUCT_ID | Product ID.
PRICE | New base price.
CURRENCY | Currency of the new base price.

Return Values

Returns True on success or False otherwise.


Update

CPrice::Update

bool
CPrice::Update(
 int ID,
 array arFields
);

The method Update updates the price properties with the new values.

Parameters

Parameter | Description
ID | Price ID.
arFields Associated array of the new parameter values with the following keys:
  • PRODUCT_ID - product ID;
  • EXTRA_ID - the ID of discount or extra;
  • CATALOG_GROUP_ID - price type ID;
  • PRICE - price value;
  • CURRENCY - currency of the price.
If the discount ID is specified, the created price will be automatically recalculated when the base price or discount changes.

Return Values

Returns True on success or False otherwise.

Example

<?
// Assign the price of USD29.95 of the type 2
// to the product with the ID of 15
$PRODUCT_ID = 15;
$PRICE_TYPE_ID = 2;

$arFields = Array(
    "PRODUCT_ID" => $PRODUCT_ID,
    "CATALOG_GROUP_ID" => $PRICE_TYPE_ID,
    "PRICE" => 29.95,
    "CURRENCY" => "USD"
);

$res = CPrice::GetList(($o=""),
                       ($b=""),
                       Array("PRODUCT_ID"=>$PRODUCT_ID,
                             "CATALOG_GROUP_ID"=>$PRICE_TYPE_ID));

if ($arr = $res->Fetch())
{
    CPrice::Update($arr["ID"], $arFields);
}
else
{
    CPrice::Add($arFields);
}
?>


Notes for developers

The module checks the variable $HTTP_ACCEPT_ENCODING to acknowledge the client ability to receive the compressed data and starts buffering content upon the OnBeforeProlog event. Upon the OnAfterEpilog event the module compresses information using the compress ratio 4.

The module does not provide any interface.

To display debugging table (if the URL contains the parameter compress=Y), the module uses CSS classes tableborder, tablehead, tableheadtext, tablebodytext.


Classes

The following classes are used with the Currencies module.

Classes

Class | Description
CCurrency | This class is used to manage currencies.
CCurrencyLang | This class helps to handle the language dependent parameters of currencies (name, format etc.)
CCurrencyRates | This class provides methods to work with currency rates.


CCurrency

The CCurrency class is used manage currencies.

Methods

Method | Description
Add | The method adds a new currency.
Delete | The method deletes a currency by its identifier.
GetBaseCurrency | The method returns the identifier of the base currency.
GetByID | The method returns an array of the language independent parameters of a currency by its identifier.
GetCurrency | The method returns an array of the language independent parameters of a currency by its identifier. The method is similar to GetByID except the fact that the GetCurrency result is cached.
GetList | The method returns a sorted list of currencies.
SelectBox | Builds the ready-to-use HTML code of the drop-down list of currencies (<SELECT>).
Update | The method replaces parameters of the currency with those specified in the arFields array.


Add

CCurrency::Add

string
CCurrency::Add(
 array arFields
);

The method Add is used to add a new currency. After the new currency is added, its language dependent parameters are to be set using the CCurrencyLang::Add method.

Parameters

Parameter Description
arFields Associated array of the currency parameters in which keys are the parameter names and values are the parameter values.
The following parameter names are possible:
  • CURRENCY - the three character currency code (must be set);
  • AMOUNT_CNT - the number of currency units used by default to define the rate of exchange (for example, if CYP 10 equal to USD 21.58, 10 is the number of currency units);
  • AMOUNT - the default rate of exchange. (One of currencies within a site must equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency;)
  • SORT - sort order;
  • DATE_UPDATE - the date that the record was last modified.

Return Values

The method returns the ID of the added currency on success, or false otherwise.

Example

<?
// Add a new currency "ISK"
$arFields = array(
   "CURRENCY" => "ISK",
   "AMOUNT" => 157.06,
   "AMOUNT_CNT" => 10000,
   "SORT" => 250
);
CCurrency::Add($arFields);
?>


Delete

CCurrency::Delete

bool
CCurrency::Delete(
 string currency
);

The method Delete is used to delete a currency by its identifier. All the exchange rates for this currency and language dependent properties are deleted as well.

Parameters

Parameter | Description
currency | The currency ID.

Return Values

The function returns true on success, or false otherwise.

Example

<?
CCurrency::Delete("USD");
?>


GetBaseCurrency

CCurrency::GetBaseCurrency

string CCurrency::GetBaseCurrency();

The method GetBaseCurrency returns the identifier of the base currency.

One of currencies within a site must be equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency.

Parameters

No parameters.


GetByID

CCurrency::GetByID

array
CCurrency::GetByID(
 string currency
);

The method GetByID returns an array of the language independent parameters of a currency by its identifier.

Parameters

Parameter | Description
currency | The currency identifier.

Return Values

Associated array with the following keys.

Key | Description
CURRENCY | The three character currency code.
AMOUNT_CNT | The number of currency units used by default to define the rate of exchange (for example, if CYP 10 equal to USD 21.58, 10 is the number of currency units).
AMOUNT | The default rate of exchange. (One of currencies within a site must equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency.)
SORT | Sort order.
DATE_UPDATE | The date that the record was last modified.

See also

CCurrency::GetCurrency

Example

<?
if (!($ar_usd_cur = CCurrency::GetByID("USD")))
{
    echo "The USD currency cannot be found";
}
else
{
    echo "The USD currency has the following parameters:<pre>";
    print_r($ar_usd_cur);
    echo "</pre>";
}
?>


GetCurrency

CCurrency::GetCurrency

array
CCurrency::GetCurrency(
 string currency
);

The method GetCurrency returns an array of the language independent parameters of a currency by its identifier. The method is similar to CCurrency::GetByID except the fact that the GetCurrency result is cached. Therefore, the repeated calls with the same currency identifier within the same page does not incur extra queries to the database.

Parameters

Parameter | Description
currency | The currency identifier.

Return Values

Associated array with the following keys.

Key | Description
CURRENCY | The three character currency code.
AMOUNT_CNT | The number of currency units used by default to define the rate of exchange (for example, if CYP 10 equal to USD 21.58, 10 is the number of currency units).
AMOUNT | The default rate of exchange. (One of currencies within a site must equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency.)
SORT | Sort order.
DATE_UPDATE | The date that the record was last modified.

See also

CCurrency::GetByID

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CCurrency::GetList

CDBResult
CCurrency::GetList(
 string &by,
 string &order,
 string lang = LANGUAGE_ID
);

The method GetList returns a sorted list of currencies. The language dependent values are returned for the language specified in the parameter lang which is the current language by default.

Parameters

Parameter | Description
by Variable containing the currency sort order. The following values are possible:
  • currency - currency identifier;
  • name - name of currency in the language lang;
  • sort - sort index (default).
order Variable containing the sort direction. The following values are possible:
  • asc - ascending (default);
  • desc - descending.
lang | The ID of the language for which the language dependent values are returned.

Return Values

Returns an instance of the CDBResult class, each record in which is an array with the following keys.

Key | Description
CURRENCY | The three character currency code.
AMOUNT_CNT | The number of currency units used by default to define the rate of exchange (for example, if CYP 10 equal to USD 21.58, 10 is the number of currency units).
AMOUNT | The default rate of exchange. (One of currencies within a site must equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency.)
SORT | Sort order.
DATE_UPDATE | The date that the record was last modified.
LID | The language ID.
FORMAT_STRING | Format string used to display amounts in this currency.
FULL_NAME | Full name of the currency.
DEC_POINT | Symbol used as decimal point when displaying amounts in this currency.
THOUSANDS_SEP | Symbol used as thousands separator when displaying amounts in this currency.
DECIMALS | Number of digits in the fractional part of an amount.

Example

<?
// Display the list of currencies in the current language, sorted by name.
// Besides, display 11.95 in the format of this currency in the current language.
$lcur = CCurrency::GetList(($b="name"), ($order1="asc"), LANGUAGE_ID);
while($lcur_res = $lcur->Fetch())
{
    echo "[".$lcur_res["CURRENCY"]."] ".$lcur_res["FULL_NAME"].": ";
    echo CurrencyFormat(11.95, $lcur_res["CURRENCY"])."<br>";
}
?>


SelectBox

CCurrency::SelectBox

string
CCurrency::SelectBox(
 string sFieldName,
 string sValue,
 string sDefaultValue = "",
 bool bFullName = True,
 string JavaFunc = "",
 string sAdditionalParams = ""
);

The method SelectBox is intended for building the ready-to-use HTML code of the drop-down list of currencies (<SELECT>). The built list of currencies is stored in the cache. Therefore, displaying the same drop-down lists within the same page does not incur extra queries to the database.

Parameters

Parameter | Description
sFieldName | Name of the drop-down list.
sValue | The identifier of currency, which is to be selected in the list.
sDefaultValue | In the list, a special value which corresponds to none of existing currencies. For example, the value All or Not specified. In this case, the currency identifier will be empty in the list. If the parameter is empty, no special value is included in the list.
bFullName | Specifies to show the full currency name. If the parameter is false, the list contains three character currency codes only.
JavaFunc | Name of the JavaScript method which is called when the OnChange event of the list fires. If the value is empty, the method is not called.
sAdditionalParams | String containing additional arbitrary parameters to include in the <select> tag.

Return Values

String containing a code for building the drop-down list of currencies.

Example

<?
// Display the drop-down list of currencies
// named CURRENCY_DEFAULT, with the currency USD
// which has been selected by default, without a special value.

echo CCurrency::SelectBox("CURRENCY_DEFAULT",
                          "RUR",
                          "",
                          True,
                          "",
                          "class='typeselect'");
?>


Update

CCurrency::Update

bool
CCurrency::Update(
 string currency,
 array arFields
);

The method Update replaces parameters of the currency with those specified in the arFields array.

Parameters

Parameter | Description
currency | The identifier of the currency whose parameters are to be modified.
arFields | Array of the currency new parameters. Value $arFields["CURRENCY"] must be the same as the identifier of the modified currency.

Return Values

Identifier of the currency whose parameters have been modified on success, or false otherwise.


CCurrencyLang

The CCurrencyLang class is used for handling the language dependent parameters of currencies.

Methods

Method | Description
Add | The method adds new language dependent parameters of currency.
Delete | The method deletes language dependent parameters of a currency for a specified language.
GetByID | The method returns an array of language dependent parameters of a currency for a specified language.
GetCurrencyFormat | The method returns an array of language dependent formatting parameters of a currency for a specified language.
Update | The method updates the language dependent parameters of currency for a specified language.


Add

CCurrencyLang::Add

bool
CCurrencyLang::Add(
 array arFields
);

The method Add is used to add new language dependent parameters to currency.

Parameters

Parameter Description
arFields Associated array of the currency parameters whose keys are the parameter names and values are the parameter values.

The following keys are possible:
  • CURRENCY - the identifier of currency to which the language dependent parameters are added (required);
  • LID - the language ID (required);
  • FORMAT_STRING - format string used to display amounts of this currency in LID (required);
  • FULL_NAME - full name of the currency;
  • DEC_POINT - symbol used as a decimal point when displaying amounts (required);
  • THOUSANDS_SEP - symbol used as thousands separator when displaying amounts;
  • DECIMALS - number of digits in the fractional part of an amount (when displaying) (required).

Return Values

Returns true on success, or false otherwise.

Example

<?
$arFields = array(
    "FORMAT_STRING" => "# USD", // symbol # is replaced with "# USD",
                                // with the real amount when displaying
    "FULL_NAME" => "Dollar",
    "DEC_POINT" => ".",
    "THOUSANDS_SEP" => "\xA0",  // NBSP
    "DECIMALS" => 2,
    "CURRENCY" => "USD",
    "LID" => "en"
);

// If the record exists, modify
// or add a new one otherwise
$db_result_lang = CCurrencyLang::GetByID("USD", "en");
if ($db_result_lang)
    CCurrencyLang::Update("USD", "en", $arFields);
else
    CCurrencyLang::Add($arFields);
?>


Delete

CCurrencyLang::Delete

bool
CCurrencyLang::Delete(
 string currency,
 string lang
);

The method Delete is used to delete the language dependent parameters of the specified currency for the specified language.

Parameters

Parameter | Description
currency | The identifier of the currency whose language dependent parameters are to be deleted.
lang | The ID of the language for which the parameters are to be deleted.

Return Values

The method returns true on success, or false otherwise.


GetByID

CCurrencyLang::GetByID

array
CCurrencyLang::GetByID(
 string currency,
 string lang
);

The method GetByID returns an array of the language dependent parameters of the specified currency for the specified language.

Parameters

Parameter | Description
currency | Identifier of currency whose language dependent parameters are required.
lang | The ID of the language for which the parameters are to be returned.

Return Values

Associated array containing the following keys:

Key | Description
CURRENCY | The three character currency code.
LID | The language ID.
FORMAT_STRING | Format string according to which the amounts in this currency are displayed in LID.
FULL_NAME | Full name of the currency.
DEC_POINT | Symbol used as decimal point when displaying amounts.
THOUSANDS_SEP | Symbol used as thousands separator when displaying amounts.
DECIMALS | Number of digits in the fractional part of an amount when displaying amounts.

Example

<?
$arFields = array(
    "FORMAT_STRING" => "# USD", // symbol # is replaced
                                // with the real amount when displaying
    "FULL_NAME" => "Dollar",
    "DEC_POINT" => ".",
    "THOUSANDS_SEP" => "\xA0",  // NBSP
    "DECIMALS" => 2,
    "CURRENCY" => "USD",
    "LID" => "en"
);

// If the record exists, modify, or add a new one otherwise
$db_result_lang = CCurrencyLang::GetByID("USD", "en");
if ($db_result_lang)
    CCurrencyLang::Update("USD", "en", $arFields);
else
    CCurrencyLang::Add($arFields);
?>


GetCurrencyFormat

CCurrencyLang::GetCurrencyFormat

array
CCurrencyLang::GetCurrencyFormat(
 string currency,
 string lang = LANGUAGE_ID
);

The method GetCurrencyFormat returns an array of the language dependent parameters of the specified currency for the specified language.

The method is similar to CCurrencyLang::GetByID except the fact that the CCurrencyLang::GetCurrencyFormat result is cached. Therefore, the repeated calls with the same currency identifier and language ID within the same page does not incur extra queries to the database.

Parameters

Parameter | Description
currency | Identifier of currency whose language dependent parameters are required.
lang | The ID of the language for which the parameters are to be returned.

Return Values

Associated array containing the following keys.

Key | Description
CURRENCY | The three character currency code.
LID | The language ID.
FORMAT_STRING | Format string used to display amounts of this currency in LID.
FULL_NAME | Full name of the currency.
DEC_POINT | Symbol used as a decimal point when displaying amounts.
THOUSANDS_SEP | Symbol used as thousands separator when displaying amounts.
DECIMALS | Number of digits in the fractional part of an amount when displaying amounts.

Example

<?
function MyFormatCurrency($fSum, $strCurrency)
{
    if (!isset($fSum) || strlen($fSum)<=0)
        return "";

    $arCurFormat = CCurrencyLang::GetCurrencyFormat($strCurrency);

    if (!isset($arCurFormat["DECIMALS"]))
        $arCurFormat["DECIMALS"] = 2;

    $arCurFormat["DECIMALS"] = IntVal($arCurFormat["DECIMALS"]);

    if (!isset($arCurFormat["DEC_POINT"]))
        $arCurFormat["DEC_POINT"] = ".";

    if (!isset($arCurFormat["THOUSANDS_SEP"]))
        $arCurFormat["THOUSANDS_SEP"] = "\\"."xA0";

    $tmpTHOUSANDS_SEP = $arCurFormat["THOUSANDS_SEP"];
    eval("\$tmpTHOUSANDS_SEP = \"$tmpTHOUSANDS_SEP\";");
    $arCurFormat["THOUSANDS_SEP"] = $tmpTHOUSANDS_SEP;

    if (!isset($arCurFormat["FORMAT_STRING"]))
        $arCurFormat["FORMAT_STRING"] = "#";

    $num = number_format($fSum,
                         $arCurFormat["DECIMALS"],
                         $arCurFormat["DEC_POINT"],
                         $arCurFormat["THOUSANDS_SEP"]);

    return str_replace("#",
                       $num,
                       $arCurFormat["FORMAT_STRING"]);
}

echo "The amount $11800.95 in the current language has the following format: ";
echo MyFormatCurrency(11800.95, "USD");
?>


Update

CCurrencyLang::Update

bool
CCurrencyLang::Update(
 string currency,
 string lang,
 array arFields
);

The method Update modifies the language dependent parameters of the specified currency for the specified language.

Parameters

Parameter | Description
currency | Identifier of currency whose language dependent parameters are to be updated.
lang | The ID of language for which the language dependent parameters of a currency are to be updated.
arFields Associated array of new parameters of the currency whose keys are the parameter names and values are the parameter values.

The following keys are possible:
  • CURRENCY - the currency identifier;
  • LID - the language ID;
  • FORMAT_STRING - format string according to which the amounts in this currency are displayed in this language;
  • FULL_NAME - the currency full name;
  • DEC_POINT - symbol used as a decimal point when displaying amounts;
  • THOUSANDS_SEP - symbol used as thousands separator when displaying amounts;
  • DECIMALS - number of digits in the fractional part of an amount when displaying amounts.

Return Values

Returns true on success, or false otherwise.

Example

<?
$arFields = array(
    "FORMAT_STRING" => "# USD", // symbol # is replaced
                                // with the real amount when displaying
    "FULL_NAME" => "Dollar",
    "DEC_POINT" => ".",
    "THOUSANDS_SEP" => "\xA0",  // NBSP
    "DECIMALS" => 2,
    "CURRENCY" => "USD",
    "LID" => "en"
);

// If the record exists, modify, or add a new one otherwise
$db_result_lang = CCurrencyLang::GetByID("USD", "en");
if ($db_result_lang)
    CCurrencyLang::Update("USD", "en", $arFields);
else
    CCurrencyLang::Add($arFields);
?>


CCurrencyRates

The CCurrencyRates class is used to handle currency rates.

Methods

Method | Description
Add | The method adds a new record to the exchange rate table.
ConvertCurrency | The method converts the specified amount from one currency to another at the exchange rate set on the specified date.
Delete | The method deletes a record from the exchange rate table.
GetByID | The method returns the exchange rate parameters.
GetConvertFactor | The method returns the factor for converting amounts on the specified date.
GetList | The method returns the sorted list of exchange rates matching the specified filter.
Update | The method replaces the parameters of a record in the exchange rate table with the new values.


Add

CCurrencyRates::Add

bool
CCurrencyRates::Add(
 array arFields
);

The method Add is used to add a new record in the exchange rate table.

Parameters

Parameter Description
arFields Associated array of new currency rate parameters in which keys are the parameter names and values are the parameter values.

The following keys are possible:
  • CURRENCY - the ID of currency for which a rate is added (required);
  • DATE_RATE - the date for which the rate is being added (required);
  • RATE_CNT - the number of currency units used to define the rate of exchange (for example, if CYP 10 equal to USD 21.58, 10 is the number of currency units) (required);
  • RATE - the default rate of exchange. (One of currencies within a site must equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency.)

Return Values

Returns true on success, or false otherwise.

Example

<?
// Consider CYP a base currency.
// CYP rate for 10.08.2005 is 10 CYP for 21.58 USD

$arFields = array(
    "RATE" => 21.58    48.1756,
    "RATE_CNT" => 10,
    "CURRENCY" => "CYP",  "ISK",
    "DATE_RATE" => "10.08.2005"
    );

if (!CCurrencyRates::Add($arFields))
    echo "error adding rate";
?>


ConvertCurrency

CCurrencyRates::ConvertCurrency

float
CCurrencyRates::ConvertCurrency(
 float valSum,
 string curFrom,
 string curTo,
 string valDate = ""
);

The method ConvertCurrency is used to convert the amount valSum from currency curFrom to currency curTo at the exchange rate set on the date valDate.

Parameters

Parameter | Description
valSum | Amount in the curFrom currency which is to be converted to the curTo currency.
curFrom | The currency to be converted.
curTo | The currency to which the conversion is to be performed.
valDate | The date of the exchange rate is to be used for conversion. If the date is empty, the conversion is performed at the current rate.

Return Values

The amount in the destination currency.

Example

<?
// suggest the USD and EUR currencies exist in the database
$val = 11.95; // amount in USD
$newval = CCurrencyRates::ConvertCurrency($val, "USD", "EUR");
echo $val." USD = ".$newval." EUR";
?>


Delete

CCurrencyRates::Delete

bool
CCurrencyRates::Delete(
 int ID
);

The method Delete deletes a record from the exchange rate table.

Parameters

Parameter | Description
ID | The record ID to be deleted.

Return Values

Returns true on success, or false otherwise.


GetByID

CCurrencyRates::GetByID

array
CCurrencyRates::GetByID(
 int ID
);

The method GetByID returns the exchange rate parameters.

Parameters

Parameter | Description
ID | The ID of the currency rate whose parameters are to be returned.

Return Values

Associated array with the following keys.

Key | Description
ID | The rate ID.
CURRENCY | The currency identifier.
DATE_RATE | The date for which the rate is set.
RATE_CNT | Number of currency units used to define the rate of exchange (for example, if CYP 10 equal to USD 21.58, 10 is the number of currency units).
RATE | The default rate of exchange. (One of currencies within a site must equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency.)


GetConvertFactor

CCurrencyRates::GetConvertFactor

float
CCurrencyRates::GetConvertFactor(
 string curFrom,
 string curTo,
 string valDate = ""
);

The method GetConvertFactor returns the factor for converting amounts from currency curFrom to currency curTo at the exchange rate set on the date valDate.

Parameters

Parameter | Description
curFrom | The currency to be converted.
curTo | The currency to which the conversion is to be performed.
valDate | The date of the exchange rate at which the conversion is to be performed. If the date is empty, the conversion is performed at the current rate.

Return Values

Returns the conversion factor.

Example

<?
$arVals = array(11.95, 18.27, 5.01);
$rate_cost = CCurrencyRates::GetConvertFactor("GBP", "USD");
for ($i = 0; $i < count($arVals); $i++)
{
    echo $arVals[$i]." GBP = ".Round($rate_cost*$arVals[$i], 2)." USD";
}
?>


GetList

CCurrencyRates::GetList

CDBResult
CCurrencyRates::GetList(
 string &by,
 string &order,
 array arFilter = Array()
);

The method GetList returns the sorted list of exchange rates satisfying the specified filter.

Parameters

Parameter Description
by Variable containing the name of the sorting field. The following values are possible:
  • date - date of the rate (default);
  • curr - currency field;
  • rate - rate field.
order Variable containing sort direction. The following values are possible:
  • asc - ascending (default);
  • desc - descending.
arFilter Record filter in the form of an associated array in which keys are the names of filtered fields and values are the filter conditions.

The following filter fields are possible:
  • CURRENCY - the currency identifier;
  • DATE_RATE - the date of the rate (records containing dates later or equal to the specified one are chosen);
  • !DATE_RATE - the date of the rate (records containing earlier dates than the specified one are chosen).

Return Values

An instance of the CDBResult class containing the records with the following keys.

Key | Description
ID | The rate ID.
CURRENCY | The currency identifier.
DATE_RATE | The date for which the rate is set.
RATE_CNT | The number of currency units used to define the rate of exchange (for example, if CYP 10 equal to USD 21.58, 10 is the number of currency units).
RATE | The default rate of exchange. (One of currencies within a site must equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency.)

Example

<?
// Display all USD rates, sorted by date
$arFilter = array(
    "CURRENCY" => "USD"
    );
$by = "date";
$order = "desc";

$db_rate = CCurrencyRates::GetList($by, $order, $arFilter);
while($ar_rate = $db_rate->Fetch())
{
    echo $ar_rate["RATE"]."<br>";
}
?>


Update

CCurrencyRates::Update

bool
CCurrencyRates::Update(
 int ID,
 array arFields
);

The method Update replaces the parameters of a record in the exchange rate table with the values of the arFields array.

Parameters

Parameter | Description
ID | The record ID.
arFields Associated array of new parameters of the currency rate in which keys are the parameter names and values are the parameter values.

The following keys are possible:
  • CURRENCY - the currency identifier;
  • DATE_RATE - the date for which the rate is set;
  • RATE_CNT - the number of currency units used to define the rate of exchange (for example, if CYP 10 equal to USD 21.58, 10 is the number of currency units);
  • RATE - the default rate of exchange. (One of currencies within a site must equal to 1. Such currency is called a base currency. Other currencies are defined relative to the base currency.)

Return Values

Returns true on success, or false otherwise.


e-Learning module classes

The following PHP classes are exported by the e-Learning module.

Classes

Class | Description
CCourse | Класс для работы с курсами.
CChapter | Класс для работы с главами.
CLesson | Класс для работы с уроками.
CLQuestion | Класс для работы с вопросами.
CLAnswer | Класс для работы с ответами.
CTest | Класс для работы с тестами.
CTestAttempt | Класс для работы с попытками прохождения теста.
CTestResult | Класс для работы с планом тестирования.
CGradeBook | Класс для работы с журналом.
CCertification | Класс для работы с сертификатами.
CStudent | Класс для работы c профилем студента.
CCoursePackage | Класс для экспорта курса.
CCourseImport | Класс для импорта курса.


CCertification

The CCertification class is used with certificates of students.
Method | Description
GetList | Returns the list of selected certificates.
GetByID | Returns the certificate by its ID.
Add | Adds a new certificate.
Update | Modifies the certificate parameters.
Delete | Deletes the certificate. Удаляет сертификат.
IsCourseCompleted | Checks if the course has been completed.
Certificate | Adds or modifies the certificate if the course has been completed.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CCertification::Add

int
CCertification::Add(
 array arFields
);

The Add method adds a new certificate.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all the certificate fields. Required fields must be present.

Return Values

The method returns the ID of the added certificate on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CCertification::Update
  • Fields

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $STUDENT_ID = 3;

    $arFields = Array(
        "ACTIVE" => "Y",
        "COURSE_ID" => $COURSE_ID,
        "STUDENT_ID" => $STUDENT_ID,
        "SUMMARY" => 300,
        "MAX_SUMMARY" => 300
    );

    $certificate = new CCertification;
    $ID = $certificate->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Certificate

CCertification::Certificate

bool
CCertification::Certificate(
 int STUDENT_ID,
 int COURSE_ID
);

The Certificate method adds or modifies the certificate if the course has been passed.

Parameters

Parameter | Description
STUDENT_ID | The student ID.
COURSE_ID | The course ID.

Return Values

The method returns true if a certificate has been successfully added, or false otherwise.

See Also

  • CCertification::Add
  • CCertification::Update
  • CTest::GetList
  • CGradeBook::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $STUDENT_ID = 1;
    $COURSE_ID = 92;

    $done = CCertification::Certificate($STUDENT_ID, $COURSE_ID);

    if ($done)
        echo "Success!";
    else
        echo "Failed!";

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CCertification::Delete

bool
CCertification::Delete(
 int ID
);

The Delete method deletes the certificate specified by the ID.

Parameters

Parameter | Description
ID | The certificate ID.

Return Values

The method returns true if the certificate has been successfully deleted, or false otherwise.

See Also

  • CCertification::Add

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $CERTIFICATE_ID = 19;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if (!CCertification::Delete($CERTIFICATE_ID))
        {
            echo "Error!";
            $DB->Rollback();
        }
        else
            $DB->Commit();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CCertification::GetByID

CDBResult
CCertification::GetByID(
 int ID
);

The GetByID method returns the ID certificate respecting the current user's access permissions.

Parameters

Parameter | Description
ID | The certificate ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Certificate fields
  • CCertification::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $CERTIFICATE_ID = 13;

    $res = CCertification::GetByID($CERTIFICATE_ID);

    if ($arCertificate = $res->GetNext())
    {
        echo "Course: ".$arCertificate["COURSE_NAME"].
             " User: ".$arCertificate["USER_NAME"].
             " Score: ".$arCertificate["SUMMARY"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CCertification::GetList

CDBResult
CCertification::GetList(
 array arOrder = Array("ID"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns a list of certificates filtered by arFilter and sorted in the arOrder order. The current user access permissions are respected.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the certificate ID;
  • STUDENT_ID - the student ID;
  • COURSE_ID - the course ID;
  • SUMMARY - number of points obtained while taking all tests of the course;
  • MAX_SUMMARY - maximum number of points that can be obtained;
  • SORT - sort index;
  • ACTIVE - active state flag (Y|N);
  • FROM_ONLINE - the certificate has been obtained via an online training course (Y/N);
  • PUBLIC_PROFILE - the certificate will be published in the profile (Y/N);
  • DATE_CREATE - the date when the certificate was created;
  • TIMESTAMP_X - the date when the student's information was modified.
Sort order can be one of the following:
  • asc - ascending;
  • desc - descending;

    Optional. The default value is descending.
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the certificate ID;
  • STUDENT_ID - the student ID;
  • COURSE_ID - the course ID;
  • SUMMARY - number of points obtained while taking the tests of the course;
  • MAX_SUMMARY - maximum number of points;
  • SORT - sort index;
  • ACTIVE - active state flag (Y|N);
  • FROM_ONLINE - the certificate has been obtained via an online training course (Y/N);
  • PUBLIC_PROFILE - the certificate can be viewed in the user profile (Y/N);
  • DATE_CREATE - the date when the certificate was created;
  • TIMESTAMP_X - the date when the student's data was modified;
  • USER - the user (complex conditions of the ID, LOGIN, NAME, LAST_NAME fields are allowed);
  • MIN_PERMISSION - minimum access permission level. "R" by default. See CCourse::SetPermission for available access permissions.
  • CHECK_PERMISSIONS - the level of access permission will be checked. If set to "N", the check is not performed.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CCertification::GetByID
  • Certificate fields

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 100;
    $res = CCertification::GetList(
        Array("SUMMARY" => "DESC", "SORT"=>"ASC"),
        Array("ACTIVE" => "Y", "COURSE_ID" => $COURSE_ID)
    );

    while ($arCertification = $res->GetNext())
    {
        echo "User:".$arCertification["USER_NAME"].
             "; Course name: ".$arCertification["COURSE_NAME"]."<br>";
    }
}
?>

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 100;
    $res = CCertification::GetList(
        Array("SUMMARY" => "DESC", "SORT"=>"ASC"),
        Array("ACTIVE" => "Y", "CHECK_PERMISSIONS" => "N")
    );

    while ($arCertification = $res->GetNext())
    {
        echo "User:".$arCertification["USER_NAME"].
             "; Course name: ".$arCertification["COURSE_NAME"]."<br>";
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


IsCourseCompleted

CCertification::IsCourseCompleted

bool
CCertification::IsCourseCompleted(
 int STUDENT_ID,
 int COURSE_ID
);

The IsCourseCompleted method checks if the course has been completed. A course is considered completed if all its tests are passed.

Parameters

Parameter | Description
STUDENT_ID | The student ID.
COURSE_ID | The course ID.

Return Values

The method returns true if the course has been successfully passed, or false otherwise.

See Also

  • CGradeBook::GetList
  • CTest::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $STUDENT_ID = 1;
    $COURSE_ID = 92;

    $done = CCertification::IsCourseCompleted($STUDENT_ID, $COURSE_ID);

    if ($done)
        echo "Course completed";
    else
        echo "Course is not completed";

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CCertification::Update

bool
CCertification::Update(
 int   ID,
 array arFields
);

The Update method modifies parameters of the specified certificate.

Parameters

Parameter | Description
ID | The certificate ID.
arFields | The array Array("field"=>"value", ...). Contains values of all certificate fields. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Fields
  • CCertification::Add

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $CERTIFICATE_ID = 15;

    $arFields = Array(
        "ACTIVE" => "N",
        "SUMMARY" => 290,
        "MAX_SUMMARY" => 555
    );

    $certificate = new CCertification;
    $success =  $certificate->Update($CERTIFICATE_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CChapter

The CChapter class is used to handle chapters.
Method | Description
GetList | Returns a filtered list of selected chapters.
GetByID | Returns a chapter record by its ID.
Add | Adds a new chapter.
Update | Modifies the parameters of the specified chapter
Delete | Deletes the specified chapter.
GetCount | Returns the number of chapters that match the passed filter fields.
GetTreeList | Returns a sorted list of chapters as a fully expanded tree.
GetNavChain | Returns the root path to the specified chapter.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CChapter::Add

int
CChapter::Add(
 array arFields
);

The Add method adds a new chapter.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all chapter fields. Required fields must be present.

Return Values

The method returns the ID of the added chapter on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CChapter::Update
  • Chapter fields

    • Example

if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $arFields = Array(
        "COURSE_ID" => $COURSE_ID,
        "ACTIVE" => "Y",
        "NAME" => "Chapter 1",
        "SORT" => "100",
        "DETAIL_TEXT" => "In this chapter ...",
    );

    $chapter = new CChapter;
    $ID = $chapter->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CChapter::Delete

bool
CChapter::Delete(
 int ID
);

The Delete method deletes the specified chapter.

Parameters

Parameter | Description
ID | The chapter ID.

Return Values

The method returns true if the chapter has been successfully deleted, or false otherwise.

Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $CHAPTER_ID = 300;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if (!CChapter::Delete($CHAPTER_ID))
        {
            echo "Error!";
            $DB->Rollback();
        }
        else
            $DB->Commit();
    }
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CChapter::GetByID

CDBResult
CChapter::GetByID(
 int ID
);

The GetByID method returns a chapter record by its ID.

Parameters

Parameter | Description
ID | The chapter ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Chapter fields
  • CChapter::GetList

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $CHAPTER_ID = 97;

    $res = CChapter::GetByID($CHAPTER_ID);

    if ($arChapter = $res->GetNext())
    {
        echo "Name: ".$arChapter["NAME"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetCount

CChapter::GetCount

int
CChapter::GetCount(
 array arFilter = Array()
);

The GetCount method returns the number of chapters that match the passed filter fields.

Parameters

Parameter | Description
arFilter | The array array("filtered field"=>"filter value" [, ...]). Filter description is available in CChapter::GetList.

Return Values

The method returns the number of chapters.

See Also

  • CChapter::GetList

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $cnt = CChapter::GetCount(Array("ACTIVE" => "Y",
                                    "COURSE_ID" => $COURSE_ID));

    echo "Number of chapters: ".$cnt;
}
?>

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $cnt = CChapter::GetCount(Array("CHECK_PERMISSIONS" => "N",
                                    "COURSE_ID" => $COURSE_ID));

    echo "Number of chapters: ".$cnt;
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CChapter::GetList

CDBResult
CChapter::GetList(
 array arOrder = Array("TIMESTAMP_X"=>"DESC"),
 array arFilter = Array(),
 bool bIncCnt = false
);

The GetList method returns the list of chapters filtered by arFilter and sorted in the arOrder order. The current user access permissions are considered.

Parameters

Parameter | Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the chapter ID;
  • NAME - the chapter name;
  • ACTIVE - active state flag;
  • SORT - sort index;
  • TIMESTAMP_X - the date when the chapter was modified.
Sort order can be one of the following:
  • asc - ascending;
  • desc - descending;

    Optional. The default is the descending order.
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the chapter ID;
  • NAME - the chapter name (wildcards allowed: [%_]);
  • SORT - sort index;
  • CODE - mnemonic chapter name (wildcards allowed: [%_]);
  • ACTIVE - active state flag (Y|N);
  • TIMESTAMP_X - the date when the chapter was modified;
  • CHAPTER_ID - the chapter ID. To obtain a list of parent chapters, set this item to an empty string;
  • COURSE_ID - the course ID;
  • DETAIL_TEXT - filter by an entry in the detailed description (wildcards allowed: [%_]);
  • PREVIEW_TEXT - short chapter description (wildcards allowed: [%_]);
  • MIN_PERMISSION - minimum access permission level. "R" by default. See CCourse::SetPermission for available access permissions.
  • CHECK_PERMISSIONS - the level of access permission will be checked. If set to "N", the check is not performed;
  • CNT_ACTIVE - if set bIncCnt to true, only active lessons will be counted.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.

"filter values" is a single value or an array.

Optional. By default, records are not filtered.
bIncCnt | Defines whether the number of chapter lessons is to be returned in ELEMENT_CNT. Optional, false by default.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CChapter::GetByID
  • Chapter fields

    Examples

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $res = CChapter::GetList(
        Array("SORT"=>"ASC"),
        Array("ACTIVE" => "Y", "COURSE_ID" => $COURSE_ID, "CNT_ACTIVE" => "Y"),
        true
    );

    while ($arChapter = $res->GetNext())
    {
        echo "Chapter name: ".$arChapter["NAME"]."<br>";
        echo "Active lessons: ".$arChapter["ELEMENT_CNT"]."<br><br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $res = CChapter::GetList(
        Array("SORT"=>"ASC"),
        Array("?NAME" => "Site")
    );

    while ($arChapter = $res->GetNext())
    {
        echo "Chapter name: ".$arChapter["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $res = CChapter::GetList(
        Array("NAME" => "ASC", "SORT"=>"ASC"),
        Array("COURSE_ID" => $COURSE_ID)
    );

    while ($arChapter = $res->GetNext())
    {
        echo "Chapter name: ".$arChapter["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $res = CChapter::GetList(
        Array("TIMESTAMP_X" => "ASC", "SORT"=>"ASC"),
        Array("CHECK_PERMISSIONS" => "N", "CHAPTER_ID" => "", "COURSE_ID" => $COURSE_ID)
    );

    while ($arChapter = $res->GetNext())
    {
        echo "Chapter name: ".$arChapter["NAME"]."<br>";
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetNavChain

CChapter::GetNavChain

CDBResult
CChapter::GetNavChain(
 int COURSE_ID,
 int CHAPTER_ID
);

The GetNavChain method returns the root path to the CHAPTER_ID chapter.

Parameters

Parameter | Description
COURSE_ID | The course ID.
CHAPTER_ID | The chapter ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CChapter::GetList
  • CChapter::GetByID
  • Chapter fields

    Example

<?
if (CModule::IncludeModule("learning"))
{

    $COURSE_ID = 90;
    $CHAPTER_ID = 116;

    $nav = CChapter::GetNavChain($COURSE_ID, $CHAPTER_ID);
    $i = 1;
    while($arChain = $nav->GetNext())
    {
        if ($i > 1) echo " -> ";
        echo $arChain["NAME"];
        $i++;
    }

    /*
    The above example will output something similar to:

    Chapter 1 -> Chapter 1.1 -> Chapter 1.1.3 -> Chapter 1.1.2
    $CHAPTER_ID - ID of Chapter 1.1.2;
    */
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetTreeList

CChapter::GetTreeList

CDBResult
CChapter::GetTreeList(
 int COURSE_ID
);

The GetTreeList method returns a sorted list of chapters as a fully expanded tree.

Parameters

Parameter | Description
COURSE_ID | The course ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CChapter::GetByID
  • CChapter::GetList
  • CCourse::GetCourseContent
  • Chapter fields

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $res = CChapter::GetTreeList($COURSE_ID = 105);

    while ($arChapter = $res->GetNext())
    {
        echo str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $arChapter["DEPTH_LEVEL"]);
        echo "+".$arChapter["NAME"]."<br>";
    }

    /*
    The above example will output something similar to:
    +Chapter 1
      +Chapter 1.1
      +Chapter 1.2
    +Chapter 2
    +Chapter 3
      +Chapter 3.1
        +Chapter 3.1.1
    */
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CChapter::Update

bool
CChapter::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of the specified chapter.

Parameters

Parameter | Description
ID | The chapter ID.
arFields | The array Array("field"=>"value", ...). Contains values of all chapter fields. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Chapter fields
  • CChapter::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $CHAPTER_ID = 299;

    $arFields = Array(
        "ACTIVE" => "N",
        "NAME" => "New name of Chapter 1",
        "SORT" => "555",
    );

    $chapter = new CChapter;
    $success = $chapter->Update($CHAPTER_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CCourse

The CCourse class is used with training courses.
Method | Description
GetList | Returns a list of selected courses.
GetByID | Returns the course fields by the course ID.
Add | Adds a new course.
Update | Modifies the course parameters.
Delete | Deletes the specified course.
SetPermission | Sets the access permissions for the training course.
GetPermission | Sets the current user access permissions for the training course.
GetGroupPermissions | Returns all access permissions for the training course.
IsHaveCourse | Defines whether the current user has access permission to at least one course.
GetSite | Returns a list of sites for the training course.
GetCourseContent | Returns the list of active chapters and lessons (the course tree).
TimeToStr | Takes seconds and converts the value into text.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CCourse::Add

int
CCourse::Add(
 array arFields
);

The Add method adds a new course.

Parameters

Parameter Description
arFields The array Array("field"=>"value", ...). Contains values of all the course fields. Required fields must be present.
Additionally, SITE_ID should contain an array of ID's of sites to which the course is to be bound.
You can assign access permissions to user groups to access the course by passing an array of mappings between the group ID's and the access permissions in the GROUP_ID field (see also CCourse::SetPermission).

Return Values

The method returns the ID of the added course on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CCourse::Update
  • Course fields

    Example

<?

if (CModule::IncludeModule("learning"))
{
    $arFields = Array(
        "ACTIVE" => "Y",
        "NAME" => "My First Course",
        "SITE_ID" => Array("ru", "en"), //Sites
        "GROUP_ID" => Array("2" => "R"), //Permissions: Everyone can read my course
        "SORT" => "100",
        "DESCRIPTION" => "It's my first e-Learning course",
        "DESCRIPTION_TYPE" => "text",
    );

    $course = new CCourse;
    $ID = $course->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();

    }

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CCourse::Delete

bool
CCourse::Delete(
 int ID
);

The Delete course deletes the course identified by the ID.

Remarks

If any certificates were obtained for the specified course, the method returns false.

Parameters

Parameter | Description
ID | The course ID.

Return Values

The method returns true if the course has been successfully deleted, or false otherwise.

Example

<?

if (CModule::IncludeModule("learning"))
{

    $ID = 109;//Course ID

    if($USER->IsAdmin())
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if(!CCourse::Delete($ID))
            $DB->Rollback();
        else
            $DB->Commit();
    }

}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CCourse::GetByID

CDBResult
CCourse::GetByID(
 int ID
);

The GetByID method returns fields of the specified course. The current user access permissions are respected.

Parameters

Parameter | Description
ID | The course ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Course fields
  • CCourse::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $course = CCourse::GetByID($COURSE_ID);
    if ($arCourse = $course->GetNext())
    {
        echo $arCourse["NAME"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetCourseContent

CCourse::GetCourseContent

CDBResult
CCourse::GetCourseContent(
 int COURSE_ID,
 array arAddSelectFileds = Array("DETAIL_TEXT", "DETAIL_TEXT_TYPE", "DETAIL_PICTURE")
);

The GetCourseContent method returns a list of active chapters and lessons sorted in the ascending order.

Remarks

Fields in the returned list have the same names as the course's chapters and lessons. The required fields are:
  • ID - the lesson or chapter ID;
  • NAME - the lesson or chapter name;
  • CHAPTER_ID - the parent chapter ID;
  • SORT - sort index;
  • DEPTH_LEVEL - required nesting level;
  • TYPE - type of the required object ("LE" - lesson, "CH" - chapter).

To obtain other fields, use the arAddSelectFileds array. The method returns the course tree. If "DETAIL_TEXT", "DETAIL_TEXT_TYPE", "DETAIL_PICTURE" are not used, you are recommended to pass an empty arAddSelectFileds (arAddSelectFileds = Array()).

Parameters

Parameter | Description
COURSE_ID | The course ID.
arAddSelectFileds An array of additional fields. Possible fields are:
  • PREVIEW_TEXT - short course description;
  • PREVIEW_TEXT_TYPE - format of the short course description (text/html);
  • PREVIEW_PICTURE - the picture ID in the preview image table;
  • DETAIL_TEXT_TYPE - format of the detailed description (text/html);
  • DETAIL_PICTURE - the picture ID in the detail view image table;
  • DETAIL_TEXT - detailed description.

By default, the following array is passed:

arAddSelectFileds =
    Array("DETAIL_TEXT",
          "DETAIL_TEXT_TYPE",
          "DETAIL_PICTURE")

Return Values

The method returns an instance of the CDBResult object.

See Also

  • Lesson fields
  • Chapter fields
  • CDBResult
    CLesson::GetList
    CChapter::GetList
    CChapter::GetTreeList

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $res = CCourse::GetCourseContent($COURSE_ID = 105, Array());

    while ($arContent = $res->GetNext())
    {
        echo str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $arContent["DEPTH_LEVEL"]);
        echo ($arContent["TYPE"]=="CH" ? "+": "-").$arContent["NAME"]."<br>";
    }

    /*
    The above example will output something similar to:

    +Chapter 1
      +Chapter 1.1
        -Lesson 1.1.1
      +Chapter 1.2
    +Chapter 2
      -Lesson 2
    +Chapter 3
      +Chapter 3.1
        -Lesson 3.1.1
        -Lesson 3.1.2
        +Chapter 3.1.1
    */
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetGroupPermissions

CCourse::GetGroupPermissions

array
CCourse::GetGroupPermissions(
 int COURSE_ID
);

The GetGroupPermissions method returns access permissions of all user groups for the specified course.

Parameters

Parameter | Description
COURSE_ID | The course ID.

Return Values

An access permission array in the format Array("Group ID"=>"Access permission"[, ...]). The following values of access permission are possible:

  • D - deny;
  • R - read;
  • W - write;
  • X - full access (write access and permission to edit other's permissions).

See Also

  • CCourse::GetPermission

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $arPerm = CCourse::GetGroupPermissions($COURSE = 8);
    print_r($arPerm);

    /*
    The above example will output something similar to:
    Array
    (
        [2] => R
        [22] => W
    )
    */
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CCourse::GetList

CDBResult
CCourse::GetList(
 array arOrder = Array("TIMESTAMP_X"=>"DESC"),
 array arFilter = Array(),
 bool bIncCnt = false
);

The GetList method returns the list of courses filtered by arFilter and sorted in the arOrder order. The current user access permissions are considered.

Parameters

Parameter | Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the course ID;
  • NAME - the course name;
  • ACTIVE - active state flag;
  • SORT - sort index;
  • TIMESTAMP_X - the date when the course was modified.
Sort order can be one of the following:
  • asc - ascending;
  • desc - descending;
Optional. The default value is descending.
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the course ID;
  • NAME - the course name (wildcards allowed: [%_]);
  • SORT - sort index;
  • CODE - mnemonic name of the course (wildcards allowed: [%_]);
  • DESCRIPTION - the course description (wildcards allowed: [%_]);
  • ACTIVE - active state flag (Y|N);
  • SITE_ID - the site ID;
  • TIMESTAMP_X - the date when the course was modified;
  • ACTIVE_FROM - the date from which the course is active (regarding the empty value);
  • ACTIVE_TO - the date from which the course is inactive (regarding the empty value);
  • DATE_ACTIVE_FROM - the date from which the course is active (regardless of the empty value);
  • DATE_ACTIVE_TO - the date from which the course is inactive (regardless of the empty value);
  • ACTIVE_DATE - if not empty, activates the active date filter (ACTIVE_FROM и ACTIVE_TO). If set to an empty string, the active date filter is not activated;
  • MIN_PERMISSION - minimum access permission level. "R" by default. See CCourse::SetPermission for available access permissions;
  • CHECK_PERMISSIONS - the level of access permission will be checked. If set to "N", the check is not performed;
  • CNT_ACTIVE - if set bIncCnt to true, only active lessons will be counted.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.

"filter values" is a single value or an array.

Optional. By default, records are not filtered.
bIncCnt | Defines whether the number of course lessons is to be returned in ELEMENT_CNT. Optional, false by default.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CCourse::GetByID
  • Course fields

    Example

lt;?
if (CModule::IncludeModule("learning"))
{
    $res = CCourse::GetList(
        Array("SORT"=>"ASC"),
        Array("ACTIVE" => "Y", "CNT_ACTIVE" => "Y"),
        $bIncCnt = true
    );

    while ($arCourse = $res->GetNext())
    {
        echo "Course name: ".$arCourse["NAME"]."<br>";
        echo "Active lessons: ".$arCourse["ELEMENT_CNT"]."<br><br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $res = CCourse::GetList(
        Array("SORT"=>"ASC"),
        Array("?NAME" => "Site")
    );

    while ($arCourse = $res->GetNext())
    {
        echo "Course name: ".$arCourse["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $res = CCourse::GetList(
        Array("NAME" => "ASC", "SORT"=>"ASC"),
        Array("CHECK_PERMISSIONS" => "N")
    );

    while ($arCourse = $res->GetNext())
    {
        echo "Course name: ".$arCourse["NAME"]."<br>";
    }
}
?>

<?
if(CModule::IncludeModule("learning")):

    $res = CCourse::GetList(Array("SORT" => "DESC"),
                            Array("ACTIVE" => "Y",
                                  "ACTIVE_DATE" => "Y",
                                  "SITE_ID" => LANG));

    while ($arElement = $res->GetNext()):?>

        <font class="text">
        <?if ($arElement["PREVIEW_PICTURE"]):?>
            <table cellpadding="0" cellspacing="0" border="0" align="left">

                <tr>
                    <td><?echo ShowImage($arElement["PREVIEW_PICTURE"],
                                         200, 200,
                                         "hspace='0' vspace='2' align='left' border='0'",
                                         "", true);?></td>
                    <td valign="top" width="0%">
                        <img src="/bitrix/images/1.gif" width="10" height="1">
                    </td>

                </tr>
            </table>
        <?endif;?>
        <a target="blank_" href="
            <?=$COURSE_URL?>?COURSE_ID=<?=$arElement["ID"]?>"><?=$arElement["NAME"]?></a>

        <?=(strlen($arElement["PREVIEW_TEXT"])>0 ? "<br>".$arElement["PREVIEW_TEXT"]: "")?>
        </font><br clear="all"><br>

    <?endwhile?>
<?endif?>
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetPermission

CCourse::GetPermission

string
CCourse::GetPermission(
 int COURSE_ID
);

The GetPermission method returns the access permissions of a current user for the specified training course.

Parameters

Parameter | Description
COURSE_ID | The course ID.

Return Values

The following values can be returned: "D" - deny, "R" - read, "W" - write, "X" - full access (write access and permission to edit other's permissions).

See Also

  • CCourse::SetPermission
  • CCourse::GetGroupPermissions

    Example

<?
$permission = CIBlock::GetPermission($id);
if ($permission<"X")
    return false;
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetSite

CCourse::GetSite

CDBResult
CCourse::GetSite(
 int COURSE_ID
);

The GetSite method returns a list of sites on which the specified training course can be used.

Parameters

Parameter | Description
COURSE_ID | The course ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult

    Example

<?

if (CModule::IncludeModule("learning"))
{

    $ID = 106;//Course ID

    $arSite = Array();
    $db_SITE_ID = CCourse::GetSite($ID);
    while($ar_SITE_ID = $db_SITE_ID->Fetch())
        $arSite[] = $ar_SITE_ID["LID"];

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


IsHaveCourse

CCourse::IsHaveCourse

bool
CCourse::IsHaveCourse(
 string MIN_PERMISSION = "W"
);

The IsHaveCourse method defines whether a current user has the minimum specified access permission to at least one course.

Parameters

Parameter | Description
MIN_PERMISSION | Minimum access permission. "W" (write) by default.

Return Values

The method returns true if a user is entitled to access at least one course, or false otherwise.

See Also

  • CCourse::GetList

    Example

<?

if (CCourse::IsHaveCourse($MIN_PERMISSION = "W"))
{
  echo "You are a teacher!";
}
else
{
  echo "Access denied!";
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


SetPermission

CCourse::SetPermission

CCourse::SetPermission(
 int COURSE_ID,
 array arPERMISSIONS
);

The SetPermission method sets the access permissions arPERMISSIONS to the training course identified by the COURSE_ID.

Parameters

Parameter | Description
COURSE_ID | The course ID.
arPERMISSIONS The array in the format Array("group ID"=>"access permission", ....). Access permission can be one of the following:
  • D - deny;
  • R - read;
  • W - write;
  • X - full access (write access and permission to edit other's permissions for this course).

See Also

  • CCourse::GetPermission
  • CCourse::Update()

    Example

<?
    CCourse::SetPermission($COURSE_ID, Array("2"=>"R", "3"=>"W"));
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


TimeToStr

CCourse::TimeToStr

string
CCourse::TimeToStr(
 int seconds
);

The TimeToStr method takes seconds and converts the value into a date string containing days, hours, minutes and seconds.

Parameters

Parameter | Description
seconds | The number of seconds.

Return Values

The method returns a string in form of DD.HH.MM.SS.

Example

<?

if (CModule::IncludeModule("learning"))
{
    $seconds = 56789;
    $time = CCourse::TimeToStr($seconds);
    echo $time; //print 15 hr. 46 min. 29 sec.
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CCourse::Update

bool
CCourse::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of the course identified by the ID.

Parameters

Parameter | Description
ID | The course ID.
arFields An array in the format Array("field"=>"value", ...). The array contains values of all fields of a course.

Additionally, the SITE_ID field contains an array of the site identifiers describing sites to which the course is bound.

You can specify permissions of different user groups to access the course by passing an array of associations between group ID's and access permissions passed in the GROUP_ID field. (see CCourse::SetPermission).

Return Values

The method returns true on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Course fields
  • CCourse::Add

    Example

<?

if (CModule::IncludeModule("learning"))
{
    $arFields = Array(
        "ACTIVE" => "Y",
        "NAME" => "New name",
        "SITE_ID" => Array("en"), //Sites
    );

    $ID = 1;//Course ID

    $course = new CCourse;
    $success = $course->Update($ID, $arFields);

    if($success)
    {
        echo "Ok!";

    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CCourseImport

The CCourseImport class is used to import courses.
Method | Description
CCourseImport | Constructor. Initializes the course to be imported.
ImportPackage | Imports a course.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CCourseImport

CCourseImport::CCourseImport

bool
CCourseImport::CCourseImport(
 string PACKAGE_DIR,
 array arSITE_ID
);

The CCourseImport constructor of the CCourseImport class is used to initialize the course to be imported.

Parameters

Parameter | Description
PACKAGE_DIR | Path to the directory (relative to the site root) where the course archive is located.
arSITE_ID | An array of the site identifiers describing sites to which the imported course will be bound.

Remarks

If an error occurs, the LAST_ERROR object property will contain the error description.

See Also

  • CCourseImport::ImportPackage

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    if ($USER->IsAdmin())
    {
        @set_time_limit(0);
        $package = new CCourseImport($PACKAGE_DIR = "/upload/mypackage/",
                                     Array("ru", "en"));

        if (strlen($package->LAST_ERROR) > 0)
        {
            echo "Error: ".$package->LAST_ERROR;
        }
        else
        {
            $success = $package->ImportPackage();

            if (!$success)
                echo "Error: ".$package->LAST_ERROR;
            else
                echo "Ok!";
        }
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


ImportPackage

CCourseImport::ImportPackage

bool
CCourseImport::ImportPackage();

The ImportPackage method imports a course.

Parameters

No parameters.

Return Values

The method returns true on success, or false otherwise. If an error occurs, the LAST_ERROR property will contain the error description.

See Also

  • CCourseImport::CCourseImport

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    if ($USER->IsAdmin())
    {
        @set_time_limit(0);
        $package = new CCourseImport($PACKAGE_DIR = "/upload/mypackage/",
                                     Array("ru", "en"));

        if (strlen($package->LAST_ERROR) > 0)
        {
            echo "Error: ".$package->LAST_ERROR;
        }
        else
        {
            $success = $package->ImportPackage();

            if (!$success)
                echo "Error: ".$package->LAST_ERROR;
            else
                echo "Ok!";
        }
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CCoursePackage

The CCoursePackage class is used to export course.
Method | Description
CCoursePackage | Constructor initializes the course to be exported.
CreateManifest | Returns a manifest of the training course archive in the XML format.
CreatePackage | Creates an archive with the training course.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CCoursePackage

CCoursePackage::CCoursePackage

bool
CCoursePackage::CCoursePackage(
 int COURSE_ID
);

The class CCoursePackage constructor initializes the course to be exported.

Parameters

Parameter | Description
COURSE_ID | The course ID.

Remarks

If an error occurs, the LAST_ERROR property will contain the error description.

See Also

  • CCoursePackage::CreatePackage
  • CCoursePackage::CreateManifest

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $package = new CCoursePackage($COURSE_ID);

        if (strlen($package->LAST_ERROR) > 0)
        {
            echo "Error: ".$package->LAST_ERROR;
        }
        else
        {
            $success = $package->CreatePackage($PACKAGE_DIR = "/upload/mypackage/");

            if (!$success)
                echo "Error: ".$package->LAST_ERROR;
            else
                echo "Ok!";
        }

    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CreateManifest

CCoursePackage::CreateManifest

string
CCoursePackage::CreateManifest();

The CreateManifest method returns a manifest, in the XML format, of the training course archive.

Parameters

No parameters.

Return Values

The method returns a string whose bits are the contents of the imsmanifest.xml file (the training course archive).

See Also

  • CCoursePackage::CCoursePackage
  • CCoursePackage::CreatePackage

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $package = new CCoursePackage($COURSE_ID);

        if (strlen($package->LAST_ERROR) > 0)
        {
            echo "Error: ".$package->LAST_ERROR;
        }
        else
        {
            echo htmlspecialchars($package->CreateManifest());
        }
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CreatePackage

CCoursePackage::CreatePackage

bool
CCoursePackage::CreatePackage(
 int PACKAGE_DIR
);

The CreatePackage method creates an archive with the training course.

Parameters

Parameter | Description
PACKAGE_DIR | Path to the directory (relative to the site root) where the course archive will be created.

Return Values

The method returns true on success, or false otherwise. If an error occurs, the LAST_ERROR property will contain the error description.

See Also

  • CCoursePackage::CCoursePackage
  • CCoursePackage::CreateManifest

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $package = new CCoursePackage($COURSE_ID);

        if (strlen($package->LAST_ERROR) > 0)
        {
            echo "Error: ".$package->LAST_ERROR;
        }
        else
        {
            $success = $package->CreatePackage($PACKAGE_DIR = "/upload/mypackage/");

            if (!$success)
                echo "Error: ".$package->LAST_ERROR;
            else
                echo "Ok!";
        }
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CGradeBook

The CGradeBook class is used with the grade book.
Method | Description
GetList | Returns a list of filtered grade book records.
GetByID | Returns a specified grade book record.
Add | Adds a new record to the grade book.
Update | Modifies the parameters of a grade book record.
Delete | Removes a record from the grade book.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CGradeBook::Add

int
CGradeBook::Add(
 array arFields
);

The Add method adds a new record to the grade book.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all the grade book fields. Required fields must be present.

Return Values

The method returns the ID of the new record on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CGradeBook::Update
  • Grade book fields

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_ID = 32;
    $STUDENT_ID = 3;

    $arFields = Array(

        "TEST_ID" => $TEST_ID,
        "STUDENT_ID" => $STUDENT_ID,
        "RESULT" => 300,
        "MAX_RESULT" => 300
    );

    $gradebook = new CGradeBook;
    $ID = $gradebook->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CGradeBook::Delete

bool
CGradeBook::Delete(
 int ID
);

The Delete method removes a record identified by the ID from the grade book.

Parameters

Parameter | Description
ID | The record ID.

Return Values

The method returns true on success, or false otherwise.

Example

<?
if (CModule::IncludeModule("learning"))
{
    $RECORD_ID = 96;

    @set_time_limit(0);
    $DB->StartTransaction();
    if (!CGradeBook::Delete($RECORD_ID))
    {
        echo "Error!";
        $DB->Rollback();
    }
    else
        $DB->Commit();
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CGradeBook::GetByID

CDBResult
CGradeBook::GetByID(
 int ID
);

The GetByID method returns a specified grade book record. The current user access permissions are respected.

Parameters

Parameter | Description
ID | The ID of the required grade book record.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Grade book fields
  • CGradeBook::GetList

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $RECORD_ID = 95;

    $res = CGradeBook::GetByID($RECORD_ID);

    if ($arGradeBook = $res->GetNext())
    {
        echo "Test: ".$arGradeBook["TEST_NAME"]." User: ".$arGradeBook["USER_NAME"]." Score: ".$arGradeBook["RESULT"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CGradeBook::GetList

CDBResult
CGradeBook::GetList(
 array arOrder = Array("ID"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns a list of the grade book records filtered by arFilter and sorted in the arOrder order. The current user access permissions are respected.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the record ID;
  • TEST_ID - the test ID;
  • STUDENT_ID - the student ID;
  • RESULT - score;
  • MAX_RESULT - maximum score;
  • COMPLETED - the test has been completed;
  • USER_NAME - the student name;
  • TEST_NAME - the test name.
Optional sort order can be one of the following:
  • asc - ascending;
  • desc - descending (default).
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the record ID;
  • TEST_ID - the test ID;
  • STUDENT_ID - the student ID;
  • RESULT - score;
  • MAX_RESULT - maximum score;
  • COMPLETED - the test has been completed (Y|N);
  • USER - the user (can be the combination of the ID, LOGIN, NAME, LAST_NAME fields);
  • MIN_PERMISSION - minimum access permission level. "R" by default. See CCourse::SetPermission for available access permissions;
  • CHECK_PERMISSIONS - the level of access permission will be checked. If set to "N", the check is not performed.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.

"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CGradeBook::GetByID
  • Grade book fields

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_ID = 45;
    $res = CGradebook::GetList(
        Array("ID" => "ASC"),
        Array("TEST_ID" => $TEST_ID)
    );

    while ($arGradebook = $res->GetNext())
    {
        echo "Student: ".$arGradebook["USER_NAME"].
             "; Test name: ".$arGradebook["TEST_NAME"].
             "; Completed: ".$arGradebook["COMPLETED"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $TEST_ID = 45;
    $STUDENT_ID = 3;

    $res = CGradebook::GetList(
        Array("ID" => "ASC"),
        Array("CHECK_PERMISSIONS" => "N", "TEST_ID" => $TEST_ID, "STUDENT_ID" => $STUDENT_ID)
    );

    while ($arGradebook = $res->GetNext())
    {
        echo "Student: ".$arGradebook["USER_NAME"].
             "; Test name: ".$arGradebook["TEST_NAME"].
             "; Completed: ".$arGradebook["COMPLETED"]."<br>";
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CGradeBook::Update

bool
CGradeBook::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of the specified grade book record.

Parameters

Parameter | Description
ID | The grade book record ID.
arFields | An array in the format Array("field"=>"value", ...). The array contains values of all the grade book fields. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Grade book fields
  • CGradeBook::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $RECORD_ID = 96;

    $arFields = Array(
        "RESULT" => 250,
        "MAX_RESULT" => 300
    );

    $gradebook = new CGradeBook;
    $success = $gradebook->Update($RECORD_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CLAnswer

The CLAnswer class is used with answers to a question.
Method | Description
GetList | Returns a filtered list of selected answers.
GetByID | Returns an answer by its ID.
Add | Adds a new answer to the question.
Update | Modifies the parameters of an answer.
Delete | Deletes an answer.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CLAnswer::Add

int
CLAnswer::Add(
 array arFields
);

The Add method adds a new answer to the question.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all answer fields. Required fields must be present.

Return Values

The method returns the ID of the added answer on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CLAnswer::Update
  • Answer fields

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $QUESTION_ID = 289;

    $arFields = Array(
        "ANSWER" => "Another answer",
        "QUESTION_ID" => $QUESTION_ID,
    );

    $answer = new CLAnswer;
    $ID = $answer->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CLAnswer::Delete

bool
CLAnswer::Delete(
 int ID
);

The Delete method removes an answer identified by the ID.

Parameters

Parameter | Description
ID | The answer ID.

Return Values

The method returns true on success, or false otherwise.

Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $ANSWER_ID = 1553;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if (!CLAnswer::Delete($ANSWER_ID))
        {
            echo "Error!";
            $DB->Rollback();
        }
        else
            $DB->Commit();
    }
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CLAnswer::GetByID

CDBResult
CLAnswer::GetByID(
 int ID
);

The GetByID method returns an answer by the ID.

Parameters

Parameter | Description
ID | The answer ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Answer fields
  • CLAnswer::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $ANSWER_ID = 573;

    $res = CLAnswer::GetByID($ANSWER_ID);

    if ($arAnswer = $res->GetNext())
    {
        echo "Name: ".$arAnswer["ANSWER"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CLAnswer::GetList

CDBResult
CLAnswer::GetList(
 array arOrder = Array("ID"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns a selection of answers filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the answer UD;
  • SORT - sort index;
  • CORRECT - whether the answer is correct or not;
  • ANSWER - answer text;
  • RAND - random order.
Sort order can be one of the following:
  • asc - ascending;
  • desc - descending;

    Optional. The default is descending.
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the answer ID;
  • SORT - sort index;
  • QUESTION_ID - the question ID;
  • ANSWER - answer text (wildcards allowed: [%_]);
  • CORRECT - whether the answer is correct or not (Y|N);
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.

"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CLAnswer::GetByID
  • Answer fields

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $QUESTION_ID = 290;
    $res = CLAnswer::GetList(
        Array("SORT"=>"DESC"),
        Array("QUESTION_ID" => $QUESTION_ID)
    );

    while ($arAnswer = $res->GetNext())
    {
        echo "Answer name: ".$arAnswer["ANSWER"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $QUESTION_ID = 290;

    $res = CLAnswer::GetList(
        Array("SORT"=>"ASC"),
        Array("QUESTION_ID" => $QUESTION_ID, "?ANSWER" => "sys")
    );

    while ($arAnswer = $res->GetNext())
    {
        echo "Answer name: ".$arAnswer["ANSWER"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $QUESTION_ID = 290;

    $res = CLAnswer::GetList(
        Array(),
        Array("QUESTION_ID" => $QUESTION_ID, "CORRECT" => "Y")
    );

    while ($arAnswer = $res->GetNext())
    {
        echo "Answer name: ".$arAnswer["ANSWER"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $QUESTION_ID = 290;

    $res = CLAnswer::GetList(
        Array("TIMESTAMP_X" => "ASC", "SORT"=>"ASC"),
        Array("QUESTION_ID" => $QUESTION_ID)
    );

    while ($arAnswer = $res->GetNext())
    {
        echo "Answer name: ".$arAnswer["ANSWER"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $QUESTION_ID = 290;

    $res = CLAnswer::GetList(
        Array("RAND"=>""),
        Array("QUESTION_ID" => $QUESTION_ID)
    );

    while ($arAnswer = $res->GetNext())
    {
        echo "Answer name: ".$arAnswer["ANSWER"]."<br>";
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CLAnswer::Update

bool
CLAnswer::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of an answer identified by the ID.

Parameters

Parameter | Description
ID | The answer UD.
arFields | An array in the format Array("field"=>"value", ...). The array contains values of all answer fields. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Answer fields
  • CLAnswer::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $ANSWER_ID = 1553;

    $arFields = Array(
        "ANSWER" => "New answer name",
        "SORT" => "1",
    );

    $answer = new CLAnswer;
    $success = $answer->Update($ANSWER_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CLesson

The CLesson class is used with lessons.
Method | Description
GetList | Returns the list of selected lessons.
GetByID | Returns a lesson identified by the ID.
Add | Adds a new lesson.
Update | Modifies the lesson parameters.
Delete | Deletes a lesson.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CLesson::Add

int
CLesson::Add(
 array arFields
);

The Add method adds a new lesson.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all lesson fields. Required fields must be present.

Return Values

The method returns the ID of the added lesson on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CLesson::Update
  • Lesson fields

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $arFields = Array(
        "ACTIVE" => "Y",
        "COURSE_ID" => $COURSE_ID,
        "NAME" => "Lesson 1",
        "SORT" => "1",
        "DETAIL_TEXT" => "It my first lesson ...",
    );

    $lesson = new CLesson;
    $ID = $lesson->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CLesson::Delete

bool
CLesson::Delete(
 int ID
);

The Delete method deletes a lesson identified by the ID.

Parameters

Parameter | Description
ID | The lesson ID.

Return Values

The method returns true on success, or false otherwise.

Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $LESSON_ID = 732;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if (!CLesson::Delete($LESSON_ID))
        {
            echo "Error!";
            $DB->Rollback();
        }
        else
            $DB->Commit();
    }
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CLesson::GetByID

CDBResult
CLesson::GetByID(
 int ID
);

The GetByID method returns a lesson identified by the ID. The current user access permissions are considered.

Parameters

Parameter | Description
ID | The lesson ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Lesson fields
  • CLesson::GetList

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $LESSON_ID = 651;

    $res = CLesson::GetByID($LESSON_ID);

    if ($arLesson = $res->GetNext())
    {
        echo "Name: ".$arLesson["NAME"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CLesson::GetList

CDBResult
CLesson::GetList(
 array arOrder = Array("TIMESTAMP_X"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns the list of lessons filtered by arFilter and sorted in the arOrder order. The current user access permissions are considered.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the lesson ID;
  • NAME - the lesson name;
  • ACTIVE - active state flag;
  • SORT - sort index;
  • TIMESTAMP_X - the date when the lesson was modified;
  • CREATED_BY - the ID of the user who has created the lesson;
  • CHAPTER_NAME - chapter name;
  • DATE_CREATE - the date when the lesson was created.
Sort order can be one of the following:
  • asc - ascending;
  • desc - descending;

    Optional. The default value is descending.
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the lesson ID;
  • NAME - the lesson name (wildcards allowed: [%_]);
  • SORT - sort index;
  • ACTIVE - active state flag (Y/N);
  • TIMESTAMP_X - the date when the lesson was modified;
  • DATE_CREATE - the date when the lesson was created;
  • CHAPTER_ID - the chapter ID. To obtain a list of parent chapters, set this item to an empty string;
  • COURSE_ID - the course ID;
  • CREATED_BY - the ID of the user who has created the lesson;
  • DETAIL_TEXT - detailed description (wildcards allowed: [%_]);
  • PREVIEW_TEXT - short lesson description (wildcards allowed [%_]);
  • MIN_PERMISSION - minimum access permission level. "R" by default. See CCourse::SetPermission for available access permissions;
  • CHECK_PERMISSIONS - specifies that the access permissions are to be checked. If set to "N", the check is not performed.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CLesson::GetByID
  • Lesson fields

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 8;
    $res = CLesson::GetList(
        Array("SORT"=>"ASC"),
        Array("ACTIVE" => "Y", "COURSE_ID" => $COURSE_ID)
    );

    while ($arLesson = $res->GetNext())
    {
        echo "Lesson name: ".$arLesson["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $res = CLesson::GetList(
        Array("SORT"=>"ASC"),
        Array("?NAME" => "Site")
    );

    while ($arLesson = $res->GetNext())
    {
        echo "Lesson name: ".$arLesson["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 8;

    $res = CLesson::GetList(
        Array("NAME" => "ASC", "SORT"=>"ASC"),
        Array("CHECK_PERMISSIONS" => "N", "COURSE_ID" => $COURSE_ID)
    );

    while ($arLesson = $res->GetNext())
    {
        echo "Lesson name: ".$arLesson["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 8;

    $res = CLesson::GetList(
        Array("NAME" => "ASC", "SORT"=>"ASC"),
        Array("CHECK_PERMISSIONS" => "N", "CHAPTER_ID" => "", "COURSE_ID" => $COURSE_ID)
    );

    while ($arLesson = $res->GetNext())
    {
        echo "Lesson name: ".$arLesson["NAME"]."<br>";
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CLesson::Update

bool
CLesson::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of a lesson identified by the ID.

Parameters

Parameter | Description
ID | The lesson ID.
arFields | An array in the format Array("field"=>"value", ...). The array contains values of all lesson fields. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Lesson fields
  • CLesson::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $LESSON_ID = 732;

    $arFields = Array(
        "ACTIVE" => "N",
        "NAME" => "New name of Lesson 1",
        "SORT" => "555",
    );

    $lesson = new CLesson;
    $success = $lesson->Update($LESSON_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CLQuestion

The CLQuestion class is used with questions.
Method | Description
GetList | Returns the list of selected questions.
GetByID | Returns a question by its ID.
Add | Adds a new question.
Update | Modifies parameters of an existing question.
Delete | Deletes a question.
GetCount | Returns the number of questions.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CLQuestion::Add

int
CLQuestion::Add(
 array arFields
);

The Add method adds a new question.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all question fields. Required fields must be filled.

Return Values

The method returns the ID of the added question on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CLQuestion::Update
  • Question fields

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $LESSON_ID = 431;

    $arFields = Array(
        "ACTIVE" => "Y",
        "LESSON_ID" => $LESSON_ID,
        "NAME" => "Lesson 1",
        "SORT" => "1",
        "NAME" => "Assume there are several sites in the system.".
                  "Is it possible to assign users permissions on access ".
                  "to viewing statistics individually for each site?"
    );

    $question = new CLQuestion;
    $ID = $question->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CLQuestion::Delete

bool
CLQuestion::Delete(
 int ID
);

The Delete method deletes a question identified by the ID.

Parameters

Parameter | Description
ID | The question ID.

Return Values

The method returns true on success, or false otherwise.

See Also

  • CLQuestion::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $QUESTION_ID = 600;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if (!CLQuestion::Delete($QUESTION_ID))
        {
            echo "Error!";
            $DB->Rollback();
        }
        else
            $DB->Commit();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CLQuestion::GetByID

CDBResult
CLQuestion::GetByID(
 int ID
);

The GetByID method returns a question identified by the ID.

Parameters

Parameter | Description
ID | The question ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Question fields
  • CLQuestion::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $QUESTION_ID = 289;

    $res = CLQuestion::GetByID($QUESTION_ID);

    if ($arQuestion = $res->GetNext())
    {
        echo "Name: ".$arQuestion["NAME"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetCount

CLQuestion::GetCount

int
CLQuestion::GetCount(
 array arFilter = Array()
);

The GetCount method returns the number of questions according to conditions stipulated by the filter.

Parameters

Parameter | Description
arFilter | The array array("filtered field"=>"filter value" [, ...]). Filter description is available in CLQuestion::GetList. By default, questions are not filtered.

Return Values

The method returns the number of lessons.

See Also

  • CLQuestion::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $cnt = CLQuestion::GetCount(Array("ACTIVE" => "Y", "COURSE_ID" => $COURSE_ID));

    echo "Number of questions: ".$cnt;
}
?>

<?
if (CModule::IncludeModule("learning"))
{
    $LESSON_ID = 426;

    $cnt = CLQuestion::GetCount(Array("LESSON_ID" => $LESSON_ID));

    echo "Number of questions: ".$cnt;
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CLQuestion::GetList

CDBResult
CLQuestion::GetList(
 array arOrder = Array("TIMESTAMP_X"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns the list of questions filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the question ID;
  • NAME - the question name;
  • ACTIVE - active state flag;
  • SORT - sort index;
  • SELF - self-check question;
  • POINT - score;
  • TYPE - the type of the question;
  • TIMESTAMP_X - the date when the question was modified.
Sort order can be one of the following:
  • asc - ascending;
  • desc - descending.

    Optional. The default value is descending.
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the question ID;
  • NAME - the question name (wildcards allowed [%_]);
  • SORT - sort index;
  • ACTIVE - active state flag (Y|N);
  • LESSON_ID - the lesson ID;
  • POINT - the score;
  • COURSE_ID - the course ID;
  • QUESTION_TYPE - the question type (S - single choice, M - multiple choice);
  • SELF - defines whether the self-check question.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CLQuestion::GetByID
  • Question fields

    Example

<?

if (CModule::IncludeModule("learning"))
{
    $LESSON_ID = 426;

    $res = CLQuestion::GetList(
        Array("TIMESTAMP_X" => "ASC", "SORT"=>"ASC"),
        Array("LESSON_ID" => $LESSON_ID)
    );

    while ($arQuestion = $res->GetNext())
    {
        echo "Question name: ".$arQuestion["NAME"]."<br>";
    }
}
?>

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $res = CLQuestion::GetList(
        Array("SORT"=>"ASC"),
        Array("ACTIVE" => "Y", "COURSE_ID" => $COURSE_ID)
    );

    while ($arQuestion = $res->GetNext())
    {
        echo "Question name: ".$arQuestion["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $res = CLQuestion::GetList(
        Array("SORT"=>"ASC"),
        Array("?NAME" => "Site")
    );

    while ($arQuestion = $res->GetNext())
    {
        echo "Question name: ".$arQuestion["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $res = CLQuestion::GetList(
        Array("NAME" => "ASC", "SORT"=>"ASC"),
        Array("COURSE_ID" => $COURSE_ID, "!SELF" => "Y")
    );

    while ($arQuestion = $res->GetNext())
    {
        echo "Question name: ".$arQuestion["NAME"]."<br>";
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CLQuestion::Update

bool
CLQuestion::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of a question identified by the ID.

Parameters

Parameter | Description
ID | The question ID.
arFields | An array in the format Array("field"=>"value", ...). The array contains values of all question fields. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Question fields
  • CLQuestion::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $QUESTION_ID = 600;

    $arFields = Array(
        "ACTIVE" => "N",
        "NAME" => "New name of question",
        "SORT" => "555",
    );

    $question = new CLQuestion;
    $success = $question->Update($QUESTION_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CStudent

The CStudent class is used with student accounts.
Method | Description
GetList | Returns a selection of filtered student accounts.
GetByID | Returns a student account identified by the USER_ID.
Add | Adds a new student account.
Update | Modifies the parameters of a student account.
Delete | Deletes an existing student account.
GenerateTranscipt | Returns a random numeric ID.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CStudent::Add

int
CStudent::Add(
 array arFields
);

The Add method adds a new student account.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all fields of a student account. Required fields must be present.

Return Values

The method returns the ID of the added student account (which is the same as the user ID) on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CStudent::Update
  • Student account fields

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $arFields = Array(
        "USER_ID" => 151,
        "RESUME" => "My resume"
    );

    $student = new CStudent;
    $ID = $student->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CStudent::Delete

bool
CStudent::Delete(
 int USER_ID
);

The Delete method deletes a student account of a specified user.

Parameters

Parameter | Description
USER_ID | The user ID.

Return Values

The method returns true on success, or false otherwise.

See Also

  • CStudent::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $USER_ID = 3;
    if ($USER->IsAdmin())
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if (!CStudent::Delete($USER_ID))
        {
            echo "Error!";
            $DB->Rollback();
        }
        else
            $DB->Commit();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GenerateTranscipt

CStudent::GenerateTranscipt

int
CStudent::GenerateTranscipt(
 int TranscriptLength = 8
);

The GenerateTranscipt method returns a random numeric identifier.

Parameters

Parameter | Description
TranscriptLength | The length of the numeric identifier. The default value is 8.

Return Values

The method returns a random number.

See Also

  • CStudent::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    echo CStudent::GenerateTranscipt();
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CStudent::GetByID

CDBResult
CStudent::GetByID(
 int USER_ID
);

The GetByID method returns a student account of a specified user.

Parameters

Parameter | Description
USER_ID | The user ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Student account fields
  • CStudent::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $USER_ID = 3;

    $res = CStudent::GetByID($USER_ID);

    if ($arStudent = $res->GetNext())
    {
        echo "CP: ".$arStudent["RESUME"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CStudent::GetList

CDBResult
CStudent::GetList(
 array arOrder = Array("ID"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns a selection of student accounts filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • USER_ID - the user ID;
  • PUBLIC_PROFILE - whether the profile is public or not (Y/N);
Optional sort order can be one of the following:
  • asc - ascending;
  • desc - descending (default);
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • USER_ID - the user ID;
  • PUBLIC_PROFILE - whether the profile is public or not (Y/N);
  • TRANSCRIPT - random numeric identifier;
  • RESUME - the student resume (wildcards allowed [%_]).
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CStudent::GetByID
  • Student fields

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $USER_ID = 1; $TRANSCRIPT = 46785643;
    $res = CStudent::GetList(Array(), Array("USER_ID" => $USER_ID, "TRANSCRIPT" => $TRANSCRIPT));

    while ($arProfile = $res->GetNext())
    {
        echo $arProfile["RESUME"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CStudent::Update

bool
CStudent::Update(
 int   USER_ID,
 array arFields
);

The Update method modifies the parameters of a student account of a specified user.

Parameters

Parameter | Description
USER_ID | The user ID.
arFields | An array in the format Array("field"=>"value", ...). The array contains values of all fields of the student account. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Student account fields
  • CStudent::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $USER_ID = 151;

    $arFields = Array(
        "RESUME" => "My new CP",
    );

    $student = new CStudent;
    $success = $student->Update($USER_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CTest

The CTest class is used with examination tests.
Method | Description
GetList | Returns a selection of tests.
GetByID | Returns a test by its ID.
Add | Adds a new test.
Update | Modifies test parameters.
Delete | Deletes a test.
GetCount | Returns the number of tests satisfying the filter.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CTest::Add

int
CTest::Add(
 array arFields
);

The Add method adds a new test.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all test fields. Required fields must be present.

Return Values

The method returns the ID of an added test on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CTest::Update
  • Test fields

    Example

<?
if (CModule::IncludeModule("learning"))
{

    $COURSE_ID = 97;

    $arFields = Array(
        "COURSE_ID" => $COURSE_ID,
        "NAME" => "New test!",
        "INCLUDE_SELF_TEST" => "Y"
    );

    $test = new CTest;
    $ID = $test->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CTest::Delete

bool
CTest::Delete(
 int ID
);

The Delete method deletes a test identified by the ID.

Parameters

Parameter | Description
ID | The test ID.

Return Values

The method returns true on success, or false otherwise.

Example

<?
if (CModule::IncludeModule("learning"))
{

    $TEST_ID = 99;
    $COURSE_ID = 97;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if (!CTest::Delete($TEST_ID))
        {
            echo "Error!";
            $DB->Rollback();
        }
        else
            $DB->Commit();
    }
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CTest::GetByID

CDBResult
CTest::GetByID(
 int ID
);

The GetByID method returns a specified test record. The current user access permissions are respected.

Parameters

Parameter | Description
ID | The test ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Test fields
  • CTest::GetList

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_ID = 32;

    $res = CTest::GetByID($TEST_ID);

    if ($arTest = $res->GetNext())
    {
        echo "Test name: ".$arTest["NAME"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetCount

CTest::GetCount

int
CTest::GetCount(
 array arFilter = Array()
);

The GetCount method returns the number of tests satisfying the filter.

Parameters

Parameter | Description
arFilter | The array array("filtered field"=>"filter value" [, ...]). Filter description is available in CTest::GetList. By default, tests are not filtered.

Return Values

The method returns the number of tests.

See Also

  • CTest::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $cnt = CTest::GetCount(Array("ACTIVE" => "Y", "COURSE_ID" => $COURSE_ID));

    echo "Number of tests: ".$cnt;
}
?>

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $cnt = CTest::GetCount(Array("CHECK_PERMISSIONS" => "N", "COURSE_ID" => $COURSE_ID));

    echo "Number of tests: ".$cnt;
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CTest::GetList

CDBResult
CTest::GetList(
 array arOrder = Array("TIMESTAMP_X"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns a selection of tests filtered by arFilter and sorted in the arOrder order. The current user access permissions are respected.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the test ID;
  • SORT - sort index;
  • NAME - the test name;
  • SORT - sort index;
  • TIMESTAMP_X - the date when the test was modified;
Optional sort order can be one of the following:
  • asc - ascending;
  • desc - descending (default).
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the test ID;
  • SORT - sort index;
  • COURSE_ID - the course ID;
  • ATTEMPT_LIMIT - number of attempts;
  • TIME_LIMIT - testing session time limit (in minutes);
  • NAME - the test name (wildcards allowed [%_]);
  • DESCRIPTION - the test description (wildcards allowed [%_]);
  • ACTIVE - active state flag (Y|N);
  • APPROVED - whether test results are checked automatically (Y|N);
  • INCLUDE_SELF_TEST - whether self-check questions are included in the test (Y/N);
  • RANDOM_QUESTIONS - indicates that the questions are displayed in random order (Y|N);
  • RANDOM_ANSWERS - indicates the random order of answers (Y/N);
  • QUESTIONS_FROM - indicates which questions are included in test: A - of the whole course, C - of each chapter, L - of each lesson;
  • PASSAGE_TYPE - the test process design:
0 - a student cannot switch to the next question without answering the current one and cannot change their answers;
1 - a student can switch to the next question without answering the current one but cannot change their answers;
3 - a student can switch to the next question without answering the current one and can change their answers;
  • MIN_PERMISSION - minimum access permission level. "R" by default. See CCourse::SetPermission for available access permissions;
  • CHECK_PERMISSIONS - the level of access permission will be checked. If set to "N", the check is not performed.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CTest::GetByID
  • Test fields

Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;
    $res = CTest::GetList(
        Array("SORT"=>"ASC"),
        Array("ACTIVE" => "Y", "COURSE_ID" => $COURSE_ID)
    );

    while ($arTest = $res->GetNext())
    {
        echo "Test name: ".$arTest["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $res = CTest::GetList(
        Array("SORT"=>"ASC"),
        Array("?NAME" => "Site")
    );

    while ($arTest = $res->GetNext())
    {
        echo "Test name: ".$arTest["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $res = CTest::GetList(
        Array("NAME" => "ASC", "SORT"=>"ASC"),
        Array("COURSE_ID" => $COURSE_ID, "APPROVED" => "Y")
    );

    while ($arTest = $res->GetNext())
    {
        echo "Test name: ".$arTest["NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 97;

    $res = CTest::GetList(
        Array("TIMESTAMP_X" => "ASC", "SORT"=>"ASC"),
        Array("CHECK_PERMISSIONS" => "N", "COURSE_ID" => $COURSE_ID)
    );

    while ($arTest = $res->GetNext())
    {
        echo "Test name: ".$arTest["NAME"]."<br>";
    }
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CTest::Update

bool
CTest::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of a specified test.

Parameters

Parameter | Description
ID | The test ID.
arFields | An array in the format Array("field"=>"value", ...). The array contains values of all test fields. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Test fields
  • CTest::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{

    $TEST_ID = 99;

    $arFields = Array(
        "NAME" => "New name",
        "INCLUDE_SELF_TEST" => "N",
        "QUESTIONS_AMOUNT" => 5
    );

    $test = new CTest;
    $success = $test->Update($TEST_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CTestAttempt

The CTestAttempt class is used to handle attempts.
Method | Description
GetList | Returns a selection of filtered attempts.
GetByID | Returns an attempt by its ID.
Add | Adds a new attempt.
Update | Modifies the parameters of an attempt.
Delete | Deletes an attempt
GetCount | Returns the number of attempts.
AttemptFinished | Moves an attempt to the Complete status and recounts the score.
IsTestCompleted | Checks whether a test is completed.
CreateAttemptQuestions | Creates a plan of questions for the specified attempt.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CTestAttempt::Add

int
CTestAttempt::Add(
 array arFields
);

The Add method adds a new attempt.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all attempt fields. Required fields must be present.

Return Values

The method returns the ID of the added attempt on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CTestAttempt::Update
  • Attempt fields

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_ID = 32;
    $STUDENT_ID = 3;

    $arFields = Array(
        "TEST_ID" => $TEST_ID,
        "STUDENT_ID" => $STUDENT_ID,
        "STATUS" => "B"
    );

    $attempt = new CTestAttempt;
    $ID = $attempt->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


AttemptFinished

CTestAttempt::AttemptFinished

bool
CTestAttempt::AttemptFinished(
 int ATTEMPT_ID
);

The AttemptFinished method moves an attempt to the Complete status and counts the score.

Parameters

Parameter | Description
ATTEMPT_ID | The attempt ID.

Return Values

The method returns true on success, or false otherwise.

See Also

  • CTestAttempt::Update

    • Example

if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 23;
    $oTestAttempt = new CTestAttempt;
    $success = $oTestAttempt->AttemptFinished($ATTEMPT_ID);
    if ($success)
        echo "Attempt has been finished";
    else
        echo "Error!";
}
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CreateAttemptQuestions

CTestAttempt::CreateAttemptQuestions

bool
CTestAttempt::CreateAttemptQuestions(
 int ATTEMPT_ID
);

The CreateAttemptQuestions method creates a plan of questions for the specified attempt.

Parameters

Parameter | Description
ATTEMPT_ID | The attempt ID.

Return Values

The method returns true on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CTestResult::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 563;

    $success = CTestAttempt::CreateAttemptQuestions($ATTEMPT_ID);

    if($success)
    {
        echo "Questions have been created.";
    }
    else
    {
        if($ex = $APPLICATION->GetException())
            echo "Error: ".$ex->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CTestAttempt::Delete

bool
CTestAttempt::Delete(
 int ID
);

The Delete method deletes an attempt identified by the ID.

Parameters

Parameter | Description
ID | The attempt ID.

Return Values

The method returns true on success, or false otherwise.

Example

<?
if (CModule::IncludeModule("learning"))
{
    $COURSE_ID = 83;
    $ATTEMPT_ID = 596;

    if (CCourse::GetPermission($COURSE_ID) >= 'W')
    {
        @set_time_limit(0);
        $DB->StartTransaction();
        if (!CTestAttempt::Delete($ATTEMPT_ID))
        {
            echo "Error!";
            $DB->Rollback();
        }
        else
            $DB->Commit();
    }
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CTestAttempt::GetByID

CDBResult
CTestAttempt::GetByID(
 int ID
);

The GetByID method returns an attempt identified by the ID. The current user access permissions are respected.

Parameters

Parameter | Description
ID | The attempt ID.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • Attempt fields
  • CTestAttempt::GetList

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 590;

    $res = CTestAttempt::GetByID($ATTEMPT_ID);

    if ($arAttempt = $res->GetNext())
    {
        echo "Test name: ".$arAttempt["TEST_NAME"];
        echo "Date start: ".$arAttempt["DATE_START"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetCount

CTestAttempt::GetCount

int
CTestAttempt::GetCount(
 int TEST_ID
 int STUDENT_ID
);

The GetCount method returns the number of attempts done by a student according to the passed arguments.

Parameters

Parameter | Description
TEST_ID | The test ID.
STUDENT_ID | The student ID.

Return Values

The method returns the number of attempts.

See Also

  • CTestAttempt::GetList

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_ID = 33;
    $STUDENT_ID = 165;

    $cnt = CTestAttempt::GetCount($TEST_ID, $STUDENT_ID);

    echo "Number of attempts:".$cnt;

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CTestAttempt::GetList

CDBResult
CTestAttempt::GetList(
 array arOrder = Array("ID"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns a selection of attempts filtered by arFilter and sorted in the arOrder order. The current user access permissions are respected.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the attempt ID;
  • TEST_ID - the test ID;
  • STUDENT_ID - the student ID;
  • DATE_START - the time when an attempt was started;
  • DATE_END - the time when an attempt was completed;
  • STATUS - the attempt status;
  • SCORE - score;
  • MAX_SCORE - maximum score;
  • COMPLETED - indicates that the test is completed;
  • QUESTIONS - the number of questions;
  • USER_NAME - the student name;
  • TEST_NAME - the test name.
Optional sort order can be one of the following:
  • asc - ascending;
  • desc - descending (default).
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the attempt ID;
  • TEST_ID - the test ID;
  • STUDENT_ID - the student ID;
  • SCORE - score;
  • MAX_SCORE - maximum score;
  • QUESTIONS - the number of questions;
  • STATUS - status of the attempt: B - started, D - aborted, F - completed;
  • COMPLETED - indicates whether the test is completed (Y|N);
  • DATE_START - the time when an attempt started;
  • DATE_END - the time when an attempt was completed;
  • USER - the user (searches by values of the ID, LOGIN, NAME, LAST_NAME fields);
  • MIN_PERMISSION - minimum access permission level. "R" by default. See CCourse::SetPermission for available access permissions;
  • CHECK_PERMISSIONS - the level of access permission will be checked. If set to "N", the check is not performed.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CTestAttempt::GetByID
  • Attempt fields

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_ID = 45;
    $res = CTestAttempt::GetList(
        Array("ID" => "ASC"),
        Array("TEST_ID" => $TEST_ID)
    );

    while ($arAttempt = $res->GetNext())
    {
        echo "Attempt ID:".$arAttempt["ID"]."; Date start: ".$arAttempt["DATE_START"]."; Test name: ".$arAttempt["TEST_NAME"]."<br>";
    }
}
?>

<?

if (CModule::IncludeModule("learning"))
{
    $TEST_ID = 45;
    $STUDENT_ID = 3;

    $res = CTestAttempt::GetList(
        Array("SCORE" => "DESC"),
        Array("CHECK_PERMISSIONS" => "N", "TEST_ID" => $TEST_ID, "STUDENT_ID" => $STUDENT_ID)
    );

    while ($arAttempt = $res->GetNext())
    {
        echo "Attempt ID:".$arAttempt["ID"]."; Date start: ".$arAttempt["DATE_START"]."; Test name: ".$arAttempt["TEST_NAME"]."<br>";
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


IsTestCompleted

CTestAttempt::IsTestCompleted

bool
CTestAttempt::IsTestCompleted(
 int ATTEMPT_ID
 int PERCENT
);

The IsTestCompleted checks whether a test is completed.

Parameters

Parameter | Description
ATTEMPT_ID | The attempt ID.
PERCENT | The required percent of correct answers.

Return Values

The method returns true on success, or false otherwise.

Example

<?
if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 563;
    $PERCENT = 30;

    $complete = CTestAttempt::IsTestCompleted($ATTEMPT_ID, $PERCENT);

    if ($complete)
        echo "Test has been completed";
    else
        echo "Try again";
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CTestAttempt::Update

bool
CTestAttempt::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of an attempt identified by the ID.

Parameters

Parameter | Description
ID | The attempt ID.
arFields | An array in the format Array("field"=>"value", ...). The array contains values of all attempt fields. Required fields must be filled.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Attempt fields
  • CTestAttempt::Add

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 596;

    $arFields = Array(
        "STATUS" => "F",
        "DATE_END" => ConvertTimeStamp(false,"FULL")
    );

    $attempt = new CTestAttempt;
    $ID = $attempt->Update($ATTEMPT_ID, $arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CTestResult

The CTestResult class is used with examination schema.
Method | Description
GetList | Returns a selection of examination questions.
GetByID | Returns an examination question by the ID.
Add | Adds a new examination question.
Update | Modifies the parameters of an examination question.
AddResponse | Saves an answer of a student and determines whether the answer is correct.
Delete | Deletes an examination question.
GetCount | Returns a number of examination questions for the specified attempt.
GetProgress | Returns a number of answered questions and questions with no answers.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add

CTestResult::Add

int
CTestResult::Add(
 array arFields
);

The Add method adds a new examination question.

Parameters

Parameter | Description
arFields | The array Array("field"=>"value", ...). Contains values of all fields of examination schema. Required fields must be present.

Return Values

The method returns the ID of the added record on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CTestAttempt::CreateAttemptQuestions
  • CTestResult::Update
  • CTestResult::AddResponse
  • Examination schema fields

    Example

<?
if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 588;
    $QUESTION_ID = 128;

    $arFields = Array(
        "ATTEMPT_ID" => $ATTEMPT_ID,
        "QUESTION_ID" => $QUESTION_ID
    );

    $plan = new CTestResult;
    $ID = $plan->Add($arFields);
    $success = ($ID>0);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


AddResponse

CTestResult::AddResponse

bool
CTestResult::AddResponse(
 int TEST_RESULT_ID
 mixed RESPONSE
);

The AddResponse method saves an answer of a student and determines if the answer is correct.

Parameters

Parameter | Description
TEST_RESULT_ID | The examination question ID.
RESPONSE | The answer ID or an array of ID's.

Return Values

The method returns true on success, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • CTestResult::Update

    • Example

if (CModule::IncludeModule("learning"))
{
    $TEST_TESULT_ID = 2962;
    $RESPONSE = 186; /* or Array(186,187); */

    $res = CTestResult::AddResponse($TEST_RESULT_ID, $RESPONSE);
    if($res)
     echo "Response has been added ";
    else
     echo "Error";
}
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Delete

CTestResult::Delete

bool
CTestResult::Delete(
 int ID
);

The Delete method deletes an examination question identified by the ID.

Parameters

Parameter | Description
ID | The examination question ID.

Return Values

The method returns true on success, or false otherwise.

Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_RESULT_ID = 2967;

    @set_time_limit(0);
    $DB->StartTransaction();
    if (!CTestResult::Delete($TEST_RESULT_ID))
    {
        echo "Error!";
        $DB->Rollback();
    }
    else
        $DB->Commit();

}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CTestResult::GetByID

CDBResult
CTestResult::GetByID(
 int ID
);

The GetByID method obtains an examination question.

Parameters

Parameter | Description
ID | The examination question ID.

Return Values

The method returns a CDBResult object.

See Also

  • CDBResult
  • Examination schema fields
  • CTestResult::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_RESULT_ID = 2894;

    $res = CTestResult::GetByID($TEST_RESULT_ID);

    if ($arResult = $res->GetNext())
    {
        echo " Question name: ".$arResult["QUESTION_NAME"];
        echo " Answered: ".$arResult["ANSWERED"];
        echo " Point: ".$arResult["POINT"];
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetCount

CTestResult::GetCount

int
CTestResult::GetCount(
 int ATTEMPT_ID
);

The GetCount method returns a number of examination questions for the specified attempt.

Parameters

Parameter | Description
ATTEMPT_ID | The attempt ID.

Return Values

The method returns the number of examination questions.

See Also

  • CTestResult::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 588;

    $cnt = CTestResult::GetCount($ATTEMPT_ID);

    echo "Number of questions:".$cnt;

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CTestResult::GetList

CDBResult
CTestResult::GetList(
 array arOrder = Array("ID"=>"DESC"),
 array arFilter = Array()
);

The GetList method returns a list of examination schema questions filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter Description
arOrder An array in the format array("filter field"=>"sort order" [, ...]). The sorting field can have the following values:
  • ID - the examination schema question ID;
  • ATTEMPT_ID - the attempt ID;
  • QUESTION_ID - the question ID:
  • POINT - score;
  • ANSWERED - indicates whether question is answered (Y|N);
  • CORRECT - indicates whether question is answered correctly (Y|N);
  • QUESTION_NAME - the question name;
  • RAND - random order.
Sort order can be one of the following:
  • asc - ascending;
  • desc - descending;
Optional. The default value is descending.
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the examination schema question ID;
  • ATTEMPT_ID - the attempt ID;
  • QUESTION_ID - the question ID;
  • POINT - score;
  • RESPONSE - the student answer (wildcards allowed [%_]);
  • QUESTION_NAME - the question name (wildcards allowed [%_]);
  • ANSWERED - indicates whether question is answered (Y|N);
  • CORRECT - indicates whether question is answered correctly (Y|N).
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
"filter values" is a single value or an array.

Optional. By default, records are not filtered.

Return Values

The method returns an instance of the CDBResult object.

See Also

  • CDBResult
  • CTestResult::GetByID
  • Examination schema questions

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 590;
    $res = CTestResult::GetList(
        Array("ID" => "ASC"),
        Array("ANSWERED" => "N", "ATTEMPT_ID" => $ATTEMPT_ID)
    );

    while ($arQuestionPlan = $res->GetNext())
    {
        echo "Question ID: ".$arQuestionPlan["QUESTION_ID"]."; Correct answer: ".$arQuestionPlan["CORRECT"]."; Question name:".$arQuestionPlan["QUESTION_NAME"]."<br>";
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetProgress

CTestResult::GetProgress

array
CTestResult::GetProgress(
 int ATTEMPT_ID
);

The GetProgress method returns a number of answered questions and questions with no answers.

Parameters

Parameter | Description
ATTEMPT_ID | The attempt ID.

Return Values

The method returns an associated array with the following keys:

  • DONE - the number of answered questions.
  • TODO - the number of questions with no answers.

See Also

  • CTestResult::GetList

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $ATTEMPT_ID = 588;

    $arStat = CTestResult::GetProgress($ATTEMPT_ID);

    echo $arStat["TODO"];
    echo $arStat["DONE"];

}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CTestResult::Update

bool
CTestResult::Update(
 int   ID,
 array arFields
);

The Update method modifies the parameters of an examination schema question identified by the ID.

Parameters

Parameter | Description
ID | The examination schema question ID.
arFields | An array in the format Array("field"=>"value", ...). The array contains values of all fields of an examination schema question. Required fields must be present.

Return Values

The method returns true on successful update, or false otherwise. If an error occurs, the exception will contain the error description.

See Also

  • Examination schema fields
  • CTestResult::Add
  • CTestResult::AddResponse

    • Example

<?
if (CModule::IncludeModule("learning"))
{
    $TEST_TESULT_ID = 2962;

    $arFields = Array(
        "CORRECT" => "Y",
        "POINT" => "20"
    );

    $plan = new CTestResult;
    $success = $plan->Update($TEST_TESULT_ID, $arFields);

    if($success)
    {
        echo "Ok!";
    }
    else
    {
        if($e = $APPLICATION->GetException())
            echo "Error: ".$e->GetString();
    }
}
?>
    © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Notes for developers

Before calling any function of the module, you should ensure it is installed:

<?
if (CModule::IncludeModule("sale"))
{
   //call module functions here
}
?>

Terms

Base currency of the site - a currency used for all purchases on the site. Specified on the e-Store module settings page. The notion of the base currency used in the e-Store module is not the same as that used in the Currency module.

© 2001-2005 Bitrix Bitrix Site Manager


Pay system integration

A pay system is any facility that enable to pay for an order: on-line pay systems, bank transfers etc.

Different pay systems offer different interfaces that a developer uses to integrate in the site for them to interact. The pay system interfaces are usually completely different, e.g. the PayFlow Pro system requires that queries to the pay system are performed via the installable SDK, whereas banks demand printed receipt. Thus, the pay system integration requires special PHP scripts called pay system handlers (or handlers in this topic).

Handlers are specified individually for every payer type of every pay system using the Pay systems form. When an order is about to be paid, the system calls the handler of a selected pay system for a specified payer type. The system calls the handler after saving the order parameters in the database.

The pay system handlers are arbitrary PHP scripts running in the context of the e-Store module. In other words, the Kernel and the e-Store modules are surely connected and available within a handler. Besides, the following variables are also available in a handler:

  • $ORDER_ID - the ID of an order to be paid via this pay system;
  • $arOrder - an array of the order $ORDER_ID parameters.

The handler algorithm and implementation completely depend on the interface of the pay system.

Pay system integration guidelines

  • You have the required handler ready to run
    1. Copy the existing handler or the handler template to the public interface folder (e.g., to /bitrix/php_interface/include/payment/). There is a number of preinstalled presets in /bitrix/modules/sale/payment/.
    2. Modify the handler so that its algorithm fully corresponds the site requirements and the pay system interface. If you create a handler form the preinstalled template, you will find information on typical changes to be made in its comments.

      Typical changes to on-line pay system handlers are providing the correct connection information (for example, login and password) and synchronizing order property codes with those use in the database. These modifications are to be made to all on-line pay system handlers, without exception.

      The pay system connection parameters are provided by the pay system upon registration in the pay system.

      A set of order properties that a customer has to fill in when ordering must be customized by the site administrator. The e-Store module possesses no knowledge about the physical meaning of these properties. At the same time, pay system expect the required property values to bear the strictly defined meaning. So, a handler must map order properties stored in the database to those required by a pay system. You will an example of this below.
    3. In the Create and edit a pay system form (in the administrative section) specify to which payer types this handler is to be made available. You mush also provide a valid path to a handler.
  • You need a new handler
    1. Obtain full information on the pay system interface. You can get it, for example, on the pay system web site or in the pay system techsupport service.
    2. Create a pay system handler in the public section (e.g. in /bitrix/php_interface/include/payment/). If the interface of any existing pay system is similar to that of the new one, you can base your handler on it. You will find the preinstalled handlers in /bitrix/modules/sale/payment/.
    3. Modify the handler so that its algorithm fully corresponds the site requirements and the pay system interface. If you create a handler form the preinstalled template, you will find information on typical changes to be made in its comments.

      Typical changes to on-line pay system handlers are providing the correct connection information (for example, login and password) and synchronizing order property codes with those use in the database. These modifications are to be made to all on-line pay system handlers, without exception.

      The pay system connection parameters are provided by the pay system upon registration in the pay system.

      A set of order properties that a customer has to fill in when ordering must be customized by the site administrator. The e-Store module possesses no knowledge about the physical meaning of these properties. At the same time, pay system expect the required property values to bear the strictly defined meaning. So, a handler must map order properties stored in the database to those required by a pay system. You will an example of this below.
    4. In the Create and edit a pay system form (in the administrative section) specify to which payer types this handler is to be made available. You mush also provide a valid path to a handler.

Typical handlers

A typical handler of an off-line pay system displays a ready-to-print receipt (or other document). These are usually banking receipts or invoices. Such handlers usually provide all necessary layout and print the order parameters in the hard-coded areas.

Example of an off-line handler can be found in /bitrix/modules/sale/payment/bill.php.

A typical handler of an on-line pay system displays an HTML form that in its turn post data to a pay system. Examples of these systems are Assist, AuthorizeNet, Payflow, WorldPay.

Pay system fully define the layout, fields and other parameters of the created HTML form. You can find the description of a form required to build a robust pay system handler, in the pay system documentation.

Example of an on-line handler can be found in /bitrix/modules/sale/payment/authorizenet.php (AuthorizeNet), /bitrix/modules/sale/payment/paypal.php (Paypal) etc.

The parameters required by a pay system are available via the array $arOrder as well as can be taken from an order properties. The following example show how to do it.

// The below code forms an associated array,
// in which the order property mnemonic codes
//     (or ID's if mnemonic code is not available)
// will be assigned to property values supplied at the time of order
// $ORDER_ID - order ID, defined before the handler is called
$arCurOrderProps = array();
$db_res = CSaleOrderPropsValue::GetList(($b=""),
                                        ($o=""),
                                        array("ORDER_ID"=>$ORDER_ID));
while ($ar_res = $db_res->Fetch())
   $arCurOrderProps[(strlen($ar_res["CODE"])>0) ?
                                $ar_res["CODE"] :
                                $ar_res["ID"]] = $ar_res["VALUE"];

// Now build a form required by the pay system,
// having the order properties mapped to parameters
// required by the pay system
if (isset($arCurOrderProps["ADDRESS"])):
   ?><input
      type="hidden"
      name="address"
      value="<?= htmlspecialchars($arCurOrderProps["ADDRESS"]) ?>"><?
endif;
if (isset($arCurOrderProps["ZIP"])):
   ?><input
      type="hidden"
      name="postcode"
      value="<?= htmlspecialchars($arCurOrderProps["ZIP"]) ?>"><?
endif;

// Now we have put a value that a customer provided for a property ADDRESS
// in the field with the name required by the pay system
// to store the customer address.
// We have put a value that a customer provided for a property ZIP
// in the field with the name required by the pay system
// to store the customer zip code.

Usually, on-line pay systems provide the following two integration interfaces.

  1. The form with the order parameters is sent to the pay system server where a user has to fill in additional fields (e.g. credit card number). After that, the actual payment take place.
  2. A user provide all information on the site and a request is sent to the pay system. After the transaction succeeds, the pay system returns with its result.

The first type is the simplest one to implement. The handler creates an HTML form which sends data to the pay system server, and create fields required by the pay system. The required fields are usually described in the pay system help section. An example of this approach is available in the Assist pay system handler (/bitrix/modules/sale/payment/assist.php).

The first type is more difficult to implement. On the other hand, it is much more flexible. You can see an example in the AuthorizeNet pay system handler template (/bitrix/modules/sale/payment/authorizenet.php). In this case, the common handler structure is as follows.

// If we are ready to pay...
if ($_REQUEST["pay_this_order"]=="Y")
{
   // $strPostQueryString will hold the request parameters
   $strPostQueryString = "x_login=".urlencode("login");

   $arCurOrderProps = array();
   $db_res = CSaleOrderPropsValue::GetList(($b=""),
                                           ($o=""),
                                           array("ORDER_ID"=>$ORDER_ID));
   while ($ar_res = $db_res->Fetch())
      $arCurOrderProps[(strlen($ar_res["CODE"])>0) ?
                                   $ar_res["CODE"] :
                                   $ar_res["ID"]] = $ar_res["VALUE"];

   if (isset($arCurOrderProps["ADDRESS"]))
      $strPostQueryString .=
                "&x_address=".urlencode($arCurOrderProps["ADDRESS"]);

    * * *

   if (isset($arCurOrderProps["ZIP"]))
      $strPostQueryString .=
                "&x_ship_to_zip=".urlencode($arCurOrderProps["ZIP"]);

   // Send request to the pay system
   $strResult = QueryGetData("some_url.net",
                             443,
                             "/some_path/file.dll",
                             $strPostQueryString,
                             $errno, $errstr, "POST", "ssl://");

   // $strResult contains the pay system respond,
   // which depends on the pay system.
   // You can process it and store in the order fields.

    * * *

}
else
{
   ?>
   <form action="" method="post">
      Credit card number: <input type="text" name="ccard_num" size="30"><br>
      * * * <br>
      CVV2: <input type="text" name="ccard_code" size="5"><br>
      <input type="hidden" name="CurrentStep" value="<?= $CurrentStep ?>">
      <input type="hidden" name="ORDER_ID" value="<?= $ORDER_ID ?>">
      <input type="hidden" name="pay_this_order" value="Y">
      <input type="submit" value="Proceed">
   </form>
   <?
}

In the latter case (type 2) the e-Store module obtains the pay system result appropriate for further processing.

If the type 1 is the case, it could be more convenient to automatically acquire the pay system result (i.e. whether the order is actually paid); but it is feasible if only the pay system supports this function. You can get more information on the pay system interface peculiarities in its documentation or the pay system support service.

If the pay system provides interface to obtain the order paid status, you can develop a status acquisition script to get the status automatically. The script is called from the Orders form of the administrative section for each order paid with this pay system. Implementation requires the following steps to be performed.

  1. Create a status acquisition script in the public section (e.g. in /bitrix/php_interface/include/payment/). You can use one of the preinstalled scripts from /bitrix/modules/sale/payment/ as a start (e.g. assist_res.php).
  2. Modify the script to conform to the pay system interface.
  3. In the Create and edit a pay system form of the administrative section, specify for which pay system handlers this status acquisition script is effective.

Some pay systems do not provide interface to acquire the status. Instead, it sends e-mails containing the pay transaction result. In this case, you can as well obtain the status automatically via the Mail module. To do so, create the appropriate mail handler and adjust its settings. For more information, please see the Mail module documentation.

If you develop your own ordering component, the pay system handler structure and algorithm are totally arbitrary.

© 2001-2005 Bitrix Bitrix Site Manager


Classes

The following are the classes used with the e-Store module.

Classes

Class | Description
CSaleBasket | Used for handling the shopping basket (shopping cart).
CSaleDelivery | Used to add, delete and modify delivery services. It can also retrieve delivery services appropriate for the given location.
CSaleDiscount | Class is used to manipulate discounts.
CSaleLocation | Used to create, delete and modify delivery locations, as well as to obtain information on the existing locations.
CSaleLocationGroup | Helps manage location groups.
CSaleOrder | Provides complete functionality for handling the e-Store orders.
CSaleOrderProps | Used with order properties which can be controls as well.
CSaleOrderPropsGroup | Encapsulates order properties in groups for proper handling.
CSaleOrderPropsValue | Helps handle parameters (compound values) of an order property values.
CSaleOrderPropsVariant | Used to manage variants of order property values.
CSaleOrderTax | Used to create taxes; apply taxes to orders and to obtain information about taxes.
CSaleOrderUserProps | Used to create, delete, modify customer profiles and to obtain information about them.
CSaleOrderUserPropsValue | Used to manage user (customer) property values.
CSalePaySystem | Used to modify and obtain pay system parameters.
CSalePaySystemAction | Used to obtain or modify parameters of pay system handlers.
CSalePersonType | Used to add, modify or retrieve parameters of a payer type.
CSaleStatus | Used to handle order statuses (or states which can be assigned to an order to indicate its progress).
CSaleTax | Create, modify, delete or retrieve information about the taxes or tax exempts.
CSaleTaxRate | Used to create, obtain, modify and delete tax rates.
CSaleAuxiliary | Helps provide temporary access to the system resources. Generally used for selling content.
CSaleRecurring | Used with subscriptions and subscription renewals.
CSaleUserAccount | Helps manage internal user accounts.
CSaleUserCards | Used to manage customers' credit cards.
CSaleUserTransact | Used with transactions.
© 2001-2005 Bitrix Bitrix Site Manager


CSaleAuxiliary

The CSaleAuxiliary class helps provide temporary access to the system resources. Generally used for selling content.

Methods

Method | Description
DeleteByTime | The method deletes all information about the expired temporary access.
DeleteByUserID | The method deletes all information about temporary access of the specified user.
GetByID | The method returns parameters of the specified temporary access.
GetByParams | The method returns parameters of the specified temporary access for the specified user.
GetList | The method returns a list of records containing information about temporary access.
Update | The method replaces parameters of the record containing information about the specified temporary access with those from the specified array.
Add | The method adds a new record containing information about temporary access to a resource.
CheckAccess | The method checks if the specified visitor can get access to a specified resource.
Delete | The method deletes information about the specified temporary access.


Add

CSaleAuxiliary::Add

int
CSaleAuxiliary::Add(
 array arFields
);

The method Add adds a new record containing information about temporary access to a resource.

Parameters

Parameter Description
arFields Associated array containing parameters of the temporary access. In this array, the keys are the parameter names, and the values are their values. The following keys are possible:
  • USER_ID - the user ID;
  • ITEM - the resource to which the access is allowed;
  • ITEM_MD5 - the resource ID (the string that uniquely identifies the resource);
  • DATE_INSERT - the date when the record was added.

Return Values

The method returns the ID of the added record on success, or false otherwise.


CheckAccess

CSaleAuxiliary::CheckAccess

bool
CSaleAuxiliary::CheckAccess(
 int userID,
 string itemMD5,
 int periodLength,
 string periodType
);

The method CheckAccess checks if the visitor userID can get access to a resource identified by itemMD5. The periodLength of the type periodType define the period of time within which the user is granted access to the resource.

Parameters

Parameter | Description
userID | The user ID.
itemMD5 | The string that uniquely identifies the resource.
periodLength | The period length, within which the user has the access to the resource.
periodType The type of the period length. Possible values:
  • I - minute;
  • H - hour;
  • D - day;
  • W - week;
  • M - month;
  • Q - quarter;
  • S - half year;
  • Y - year.

Return Values

The method returns true if the user can get an access to this resource, or false otherwise.

Example

<?
if (CSaleAuxiliary::CheckAccess($USER->GetID(), "pict.jpg", 2, "D"))
{
    echo '<a href="'.pict.jpg.'">The file is available for download</a>';
}
else
{
    echo "The file is not available for download";
}
?>


Delete

CSaleAuxiliary::Delete

bool
CSaleAuxiliary::Delete(
 int ID
);

The method Delete deletes information about temporary access identified by the ID.

Parameters

Parameter | Description
ID | The record ID.

Return Values

Returns true on success, or false otherwise.


DeleteByTime

CSaleAuxiliary::DeleteByTime

bool
CSaleAuxiliary::DeleteByTime(
 int periodLength,
 sring periodType
);

The method DeleteByTime deletes all information about the expired temporary access.

Parameters

Parameter | Description
periodLength | The period length, within which the user has the access to the resource.
periodType The type of the period length. Possible values:
  • I - minute;
  • H - hour;
  • D - day;
  • W - week;
  • M - month;
  • Q - quarter;
  • S - half year;
  • Y - year.

Return Values

The method returns true on success, or false otherwise.

Example

<?
// Delete all records older than 2 days
CSaleAuxiliary::DeleteByTime(2, "D");
?>


DeleteByUserID

CSaleAuxiliary::DeleteByUserID

bool
CSaleAuxiliary::DeleteByUserID(
 int userID
);

The method DeleteByUserID deletes all information about temporary access of the user userID.

Parameters

Parameter | Description
userID | The user ID.

Return Values

The method returns true on success, or false otherwise.


GetByID

CSaleAuxiliary::GetByID

array
CSaleAuxiliary::GetByID(
 int ID
);

The method GetByID returns parameters of the temporary access identified by the ID.

Parameters

Parameter | Description
ID | The record ID.

Return Values

The method returns an associated array containing parameters of the temporary access with the following keys:
  • ID - the record ID;
  • USER_ID - the user ID;
  • ITEM - the resource to which the access is allowed;
  • ITEM_MD5 - the resource ID (the string that uniquely identifies the resource);
  • TIMESTAMP_X - the date when the record was modified;
  • DATE_INSERT - the date when the record was added.


GetByParams

CSaleAuxiliary::GetByParams

array
CSaleAuxiliary::GetByParams(
 int userID,
 string itemMD5
);

The method GetByParams returns parameters of the temporary access identified by the itemMD5 for the user userID.

Parameters

Parameter | Description
userID | The user ID.
itemMD5 | The resource ID (the string that uniquely identifies the resource).

Return Values

The method returns an associated array containing parameters of the temporary access with the following keys:
  • ID - the record ID;
  • USER_ID - the user ID;
  • ITEM - the resource to which the access is allowed;
  • ITEM_MD5 - the resource ID (the string that uniquely identifies the resource);
  • TIMESTAMP_X - the date when the record was modified;
  • DATE_INSERT - the date when the record was added.


GetList

CSaleAuxiliary::GetList

CDBResult
CSaleAuxiliary::GetList(
 array arOrder = array(),
 array arFilter = array(),
 array arGroupBy = false,
 array arNavStartParams = false,
 array arSelectFields = array()
);

The method GetList returns a list of records containing information about temporary access.

Parameters

Parameter Description
arOrder Associated array used to sort the resulting records. The array has the following format:
array(
"field_name1" => "sort_order1",
"field_name2" => "sort_order2",
. . .
)
The fields field_nameN can be any information field of the temporary access. The sort_orderX can be either "ASC" (ascending) or "DESC" (descending).

If the sorting array has more than one elements, the resulting list is sorted by each element in series (i.e. the list is first sorted by the first element, then the result is sorted by the second element etc).

The default value is an empty array() which means that the result will not be sorted.
arFilter Associated array used to filter the returned records. The array has the following format:
array(
"[modifier1][operator1]field_name1" => "value1",
"[modifier2][operator2]field_name2" => "value2",
. . .
)
Records satisfying the filter conditions are returned as a result, others are truncated.

The following modifiers are possible:
  • ! - negation;
  • + - values null, 0 and empty string also satisfy the filter conditions.
The following operators are possible:
  • >= - the field value is more than or equal to that passed in the filter;
  • > - the field value is more than that passed in the filter;
  • <= - the field value is less than or equal to that passed in the filter;
  • < - the field value is less than that passed in the filter;
  • @ - the field value is stored in the list of comma separated values passed in the filter;
  • ~ - the field value is matched against the wildcard passed to the filter;
  • % - the field value is matched (according to the query language) against the string passed to the filter.
The fields field_nameX can be any field containing information about the temporary access.

Example:
array("USER_ID" => 150)
This filter tells to "return all records with the value 150 in the USER_ID field".

The default value is an empty array() which means that the result will not be filtered.
arGroupBy Associated array used to group the records. The array has the following format:
array("field_name1",
      "grouping_function2" => "field_name2", . . .)
The fields field_nameN can be any field containing information about the temporary access. The grouping_functionX can be one of the following:
  • COUNT - quantity counting;
  • AVG - calculation of the average value;
  • MIN - calculation of the minimum value;
  • MAX - calculation of the maximum value;
  • SUM - calculation of the total value.
If the array is empty, the method will return the number of records satisfying the filter.

The default value is false which means that the result will not be grouped.
arNavStartParams Array of the selection parameters. The following keys are possible in this array:
  • "nTopCount" - number of records returned by the method will be limited to the value of this key;
  • any key that can be passed to CDBResult::NavQuery in the third parameter.
The default value is false which means that no parameter is given.
arSelectFields Array of record fields that will be returned by the method. You may specify the required fields only. If the array contains the value of "*", all available fields will be returned.

The default value is an empty array() which means that all the fields of the main query table will be returned.

Return Values

The method returns a CDBResult class instance, containing the list of associated arrays of the temporary access parameters with the following keys:
  • ID - the record ID;
  • USER_ID - the user ID;
  • ITEM - the resource to which the access is allowed;
  • ITEM_MD5 - the resource ID (the string that uniquely identifies the resource);
  • TIMESTAMP_X - the date when the record was modified;
  • DATE_INSERT - the date when the record was added.

If an empty array is passed as an arGroupBy parameter, the method will return the number of records satisfying the filter.


Update

CSaleAuxiliary::Update

int
CSaleAuxiliary::Update(
 array arFields
);

The method Update replaces parameters of the record containing information about temporary access and identified by the ID, with those from the arFields array.

Parameters

Parameter Description
arFields Associated array containing new parameters of the temporary access. In this array, the keys are the parameter names, and the values are their values. The following keys are possible:
  • USER_ID - the user ID;
  • ITEM - the resource to which the access is allowed;
  • ITEM_MD5 - the resource ID (the string that uniquely identifies the resource);
  • DATE_INSERT - the date when the record was added.

Return Values

The method returns the ID of the modified record on success, or false otherwise.


CSaleBasket

The CSaleBasket class is used for handling the shopping basket (shopping cart).

Methods

Method | Description
Update | Replaces parameters of the specified product with the new ones.
GetByID | Returns an array of parameters of the shopping basket record identified by the ID.
GetList | Returns a set of the basket records. The set returned is filtered by arFilter, sorted by by in the direction order.
GetPropsList | Returns a set of basket properties. The property set returned is filtered by arFilter, sorted by by in the direction order.
UpdatePrice | Updates the basket item using the callback function.
OrderBasket | Attaches product items from the basket to the specified order. This method is called at the time of ordering the basket products.
Add | Adds a product item to the basket unless it is already added, or updates the product properties (increases its quantity) is this product has already been added to the basket.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleBasket::Add

int
CSaleBasket::Add(
  array arFields
);

The method Add adds a product item to the basket unless it is already added, or updates the product properties (increases its quantity) is this product has already been added to the basket.

The array arFields should contain all the product properties required by the e-Store module because this module is independent of the other modules in the system.

You can add products to basket from any page, static or dynamic, from any place in the code (e.g. from the Commercial Catalog). Some modules provide wrapper functions which helps to add products to basket. For example, the Commercial Catalog module exports function Add2Basket($PRICE_ID, $QUANTITY).

Parameters

Parameter Description
arFields Associated array containing new parameters of basket item. The following keys are possible:
  • PRODUCT_ID - the product ID unique within the module;
  • PRODUCT_PRICE_ID - the product auxiliary ID;
  • PRICE - price of a single product item;
  • CURRENCY - currency of the PRICE;
  • WEIGHT - weight of a single product item ;
  • QUANTITY - number of product items. If QUANTITY is null, the product is removed from the basket;
  • LID - the site from which purchase originates;
  • DELAY - flag "save for later purchase" (Y/N);
  • CAN_BUY - flag "can be purchased" (Y/N) - can be set automatically if the actualization callback function is provided;
  • NAME - product name (required);
  • CALLBACK_FUNC - name of the callback function used to maintain the basket actuals (see CSaleBasket::Add for details);
  • MODULE - the module adding the product;
  • NOTES - other special notes;
  • ORDER_CALLBACK_FUNC - name of the ordering process callback function (see CSaleBasket::Add for details);
  • DETAIL_PAGE_URL - URL of the page with the product details;
  • PROPS - array of properties of the product in the basket. Each element of this array is its turn an array of the following format:
    array("NAME" =>  "Property name",
      "CODE" =>  "Property identifier",
      "VALUE" => "Property value",
      "SORT" =>  "Sort weight")

Return Values

Returns the ID of the new basket item.

Example

<?
if (CModule::IncludeModule("sale"))
{
  $arFields = array(
    "PRODUCT_ID" => 51,
    "PRODUCT_PRICE_ID" => 0,
    "PRICE" => 138.54,
    "CURRENCY" => "USD",
    "WEIGHT" => 530,
    "QUANTITY" => 1,
    "LID" => LANG,
    "DELAY" => "N",
    "CAN_BUY" => "Y",
    "NAME" => "Lather suitcase",
    "CALLBACK_FUNC" => "MyBasketCallback",
    "MODULE" => "my_module",
    "NOTES" => "",
    "ORDER_CALLBACK_FUNC" => "MyBasketOrderCallback",
    "DETAIL_PAGE_URL" => "/".LANG."/detail.php?ID=51"
  );

  $arProps = array();

  $arProps[] = array(
    "NAME" => "Colour",
    "CODE" => "color",
    "VALUE" => "Black"
  );

  $arProps[] = array(
    "NAME" => "Size",
    "VALUE" => "1.5 x 2.5"
  );

  $arFields["PROPS"] = $arProps;

  CSaleBasket::Add($arFields);
}
?>

Basket actualization callback function

If the basket actualization callback function is specified, it is called every time the basket is being queried. This allows to properly and fully update parameters of products in the basket. For example, is the product price or availability becomes changed after adding it to the basket, the callback function can properly update parameters of the basket items. The CALLBACK_FUNC field contains only the name of the callback function. Some modules provide the preset callback functions. For example the Commercial Catalog module provides function CatalogBasketCallback($PRODUCT_ID, $QUANTITY = 0).

array
CALLBACK_FUNC(
 int PRODUCT_ID [,
 int QUANTITY]
);

Return Values

The callback function must return an array of the same format as the function CSaleBasket::Add takes on input. If the callback function returns an empty array, the product is considered unavailable.

Parameters

PRODUCT_ID
The ID of the product currently in the basket.
QUANTITY
Number of the product items.

Example

<?
function MyBasketCallback($PRODUCT_ID, $QUANTITY = 0)
{
  $arResult = array();

  $iProductQuantity = GetProductQuantity($PRODUCT_ID);
  if ($iProductQuantity<=0)
    // not in stack, return empty array
    return $arResult;

  $arResult = array(
    "PRODUCT_PRICE_ID" => 0,
    "PRICE" => 125.2,
    "CURRENCY" => "USD",
    "WEIGHT" => 530,
    "NAME" => "Leather suitcase",
    "CAN_BUY" => "Y"
  );

  if (IntVal($QUANTITY)>0 &&
      ($iProductQuantity-$QUANTITY)<0)
  {
    // number of products in stock is less
    // than the basket specifies, so
    // decrease the quantity
    $arResult["QUANTITY"] = $iProductQuantity;
  }

  return $arResult;
}
?>

Ordering callback function

If the ordering callback function is specified, it is called when a product in the basket is being ordered. For example, the callback function can track quantity of the currently in-stock product items and decrease the number of product items in the basket accordingly. The ORDER_CALLBACK_FUNC field contains only the name of the callback function. Some modules provide the preset callback functions. For example the Commercial Catalog module provides function CatalogBasketOrderCallback($PRODUCT_ID, $QUANTITY).

void
ORDER_CALLBACK_FUNC(
 int PRODUCT_ID,
 int QUANTITY
);

Return Values

No return values.

Parameters

PRODUCT_ID
The ID of the product currently in the basket.
QUANTITY
Number of the product items.

Example

<?
function MyBasketOrderCallback($PRODUCT_ID, $QUANTITY)
{
   UpdateProductQuantity($PRODUCT_ID, $QUANTITY);
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleBasket::GetByID

array
CSaleBasket::GetByID(
  int ID
);

The method GetByID returns an array of parameters of the shopping basket record identified by the ID.

Parameters

Parameter | Description
ID | The record ID.

Return Values

The method returns an associated array with the following keys.

Key | Description
ID | The record ID.
PRODUCT_ID | The product ID unique within the module.
PRODUCT_PRICE_ID | The product ID (auxiliary).
PRICE | Price of the product, per unit.
CURRENCY | Currency of the product price.
WEIGHT | Weight of the product unit.
QUANTITY | Number of products.
LID | The site from which the purchase originates.
DELAY | Indicates the product item is saved for later purchase (Y/N).
CAN_BUY | Indicates the product can be purchased (Y/N).
NAME | The product name.
CALLBACK_FUNC | Name of the callback function used to maintain the basket actuals.
MODULE | Module adding the product to the basket.
NOTES | Other special notes.
ORDER_CALLBACK_FUNC | Name of the ordering process callback function.
DETAIL_PAGE_URL | URL of the page with the product details.
FUSER_ID | The internal ID of the basket owner (not the same as the user ID).
ORDER_ID | The ID of the sale order containing this record (product). If a product is in the basket but is not ordered yet, this field is NULL.
DATE_INSERT | The date the product was added.
DATE_UPDATE | The date the record was modified.
DISCOUNT_PRICE | Discount for the product. Valid only upon ordering.

Please note that this method returns data which is actual by the time of the last call of the CALLBACK_FUNC callback function on this record, or by the time the record was added if the callback function was not called or is not specified.

Example

<?
// Display the actual basket of the current user
// (implemented by the API function GetBasketList())

// initialise the basket owner internal ID
CSaleBasket::Init(false);

// Result array
$arRes = array();

// Select all active but not ordered records
// of the current owner for the current site
$db_res = CSaleBasket::GetList(($by="NAME"), ($order="ASC"),
                               array("FUSER_ID"=>$_SESSION["SALE_USER_ID"],
                                     "LID"=>SITE_ID, "ORDER_ID"=>"NULL"));

while ($ar_res = $db_res->GetNext())
{
    // If the callback function is specified...
    if (strlen($ar_res["CALLBACK_FUNC"])>0)
    {
        // Update the basket parameters by calling the callback function
        CSaleBasket::UpdatePrice($ar_res["ID"],
                                 $ar_res["CALLBACK_FUNC"],
                                 $ar_res["MODULE"],
                                 $ar_res["PRODUCT_ID"],
                                 $ar_res["QUANTITY"]);
        // Query an array of newly actual parameters
        $ar_res = CSaleBasket::GetByID($ar_res["ID"]);
    }
    $arRes[] = $ar_res;
}

// Display the actual basket information
echo "<pre>";
print_r($arRes);
echo "</pre>";
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleBasket::GetList

CDBResult
CSaleBasket::GetList(
  string &by,
  string &order,
  array arFilter = array()
);

The method GetList returns a set of the basket records. The set returned is filtered by arFilter, sorted by by in the direction order.

Parameters

Parameter Description
by Name of the field by which the list is to be sorted. The following values are possible:
  • NAME - product name (default);
  • PRODUCT_ID - product ID;
  • PRODUCT_PRICE_ID - product ID (auxiliary);
  • FUSER_ID - internal ID of the basket owner;
  • ORDER_ID - order ID;
  • CURRENCY - currency;
  • DATE_INSERT - the date the product was added;
  • DATE_UPDATE - the date the record was modified;
  • LID - the site from which the purchase originates.
order Sort order. The following values are possible:
  • asc - ascending;
  • desc - descending.
arFilter An array of the format Array("basket element parameter name"=>"filter condition" [, ...]). Filtering field can have the following values:
  • ID - record ID;
  • PRODUCT_ID - product ID;
  • PRODUCT_PRICE_ID - product ID (auxiliary);
  • FUSER_ID - internal ID of the basket owner;
  • ORDER_ID - order ID. If "NULL", only unordered records are selected;
  • CURRENCY - currency;
  • LID - the site from which the purchase originates;
  • DELAY - the product item is saved for later purchase (Y/N);
  • CAN_BUY - the product can be purchased (Y/N). This flag can be set automatically is the basket actualization callback function.

Return Values

Returns an instance of the CDBResult class containing a set of associated arrays with the following keys.

Key | Description
ID | The record ID.
PRODUCT_ID | The product ID unique within the module.
PRODUCT_PRICE_ID | The product ID (auxiliary).
PRICE | Price of the product, per unit.
CURRENCY | Currency of the product price.
WEIGHT | Weight of the product unit.
QUANTITY | Number of products.
LID | The site from which the purchase originates.
DELAY | Indicates the product item is saved for later purchase (Y/N).
CAN_BUY | Indicates the product can be purchased (Y/N).
NAME | The product name.
CALLBACK_FUNC | Name of the callback function used to maintain the basket actuals.
MODULE | Module adding the product to the basket.
NOTES | Other special notes.
ORDER_CALLBACK_FUNC | Name of the ordering process callback function.
DETAIL_PAGE_URL | URL of the page with the product details.
FUSER_ID | The internal ID of the basket owner (not the same as the user ID).
ORDER_ID | The ID of the sale order containing this record (product). If a product is in the basket but is not ordered yet, this field is NULL.
DATE_INSERT | The date the product was added.
DATE_UPDATE | The date the record was modified.
DISCOUNT_PRICE | Discount for the product. Valid only upon ordering.

Example

<?
// Display the actual basket of the current user
// (implemented by the API function GetBasketList())

// initialise the basket owner internal ID
CSaleBasket::Init(false);

// Result array
$arRes = array();

// Select all active but not ordered records
// of the current owner for the current site
$db_res = CSaleBasket::GetList(($by="NAME"), ($order="ASC"),
                               array("FUSER_ID"=>$_SESSION["SALE_USER_ID"],
                                     "LID"=>SITE_ID, "ORDER_ID"=>"NULL"));

while ($ar_res = $db_res->GetNext())
{
    // If the callback function is specified...
   if (strlen($ar_res["CALLBACK_FUNC"])>0)
   {
        // Update the basket parameters by calling the callback function
        CSaleBasket::UpdatePrice($ar_res["ID"],
                                 $ar_res["CALLBACK_FUNC"],
                                 $ar_res["MODULE"],
                                 $ar_res["PRODUCT_ID"],
                                 $ar_res["QUANTITY"]);
        // Query an array of newly actual parameters
        $ar_res = CSaleBasket::GetByID($ar_res["ID"]);
   }
   $arRes[] = $ar_res;
}

// Display the actual basket information
echo "<pre>";
print_r($arRes);
echo "</pre>";
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetPropsList

CSaleBasket::GetPropsList

CDBResult
CSaleBasket::GetPropsList(
  string &by,
  string &order,
  array arFilter = array()
);

The method GetPropsList returns a set of basket properties. The property set returned is filtered by arFilter, sorted by by in the direction order.

Parameters

Parameter Description
by Name of the field by which the records are to be sorted. The following values are possible:
  • SORT - sort weight (default);
  • NAME - property name;
  • VALUE - property value;
  • CODE - property mnemonic code.
order Specifies the sort order. The following values are possible:
  • ASC - ascending (default);
  • DESC - descending
arFilter The filter in the form of associated array whose keys are property names and values are the filter conditions. The following keys are possible:
  • ID - the record ID;
  • BASKET_ID - the ID of the basket element to which this property is bound;
  • CODE - property mnemonic code.

Return Values

Returns an instance of CDBResult containing a set of associated array with the following keys.

Key | Description
ID | The record ID.
BASKET_ID | The ID of the basket element to which this property is bound.
NAME | Property name.
VALUE | Property value.
CODE | Property mnemonic code.
SORT | Property sort weight.

Example

<?
// Print all properties of the basket element with $ID
$db_res = CSaleBasket::GetPropsList(($b="SORT"),
                                    ($o="ASC"),
                                    Array("BASKET_ID" => $ID));
while ($ar_res = $db_res->Fetch())
{
   echo $ar_res["NAME"]."=".$ar_res["VALUE"]."<br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Init

CSaleBasket::Init

CSaleBasket::Init();

The method Init initialises the internal ID of the basket owner. Upon initialisation, the internal ID can be accessed via the session variable: $_SESSION["SALE_USER_ID"].

The internal ID must be initialised prior to its use. Wrapper functions (e.g. GetBasketList) automatically initialises the internal ID of the basket owner.

The system ignores repeated attempts to re-initialise the internal ID of the basket owner.

Example

<?
// Obtain the content of the current user basket on the current site
// (the GetBasketList function performs the full initialisation,
//  including the basket actualization)
CSaleBasket::Init();
$db_res = CSaleBasket::GetList(($b=""),
                               ($o=""),
                               array("FUSER_ID"=>$_SESSION["SALE_USER_ID"],
                                     "LID"=>SITE_ID, "ORDER_ID"=>"NULL"));
?>
© 2001-2005 Bitrix Bitrix Site Manager


OrderBasket

CSaleBasket::OrderBasket

CSaleBasket::OrderBasket(
  int OrderID,
  int FUSER_ID = 0,
  string strLang = SITE_ID,
  array arDiscounts = False
);

The method OrderBasket attaches product items from the basket to the specified order. The method attaches those product items that are currently available and not saved for later purchase. This method is called at the time of ordering the basket products.

Parameters

Parameter | Description
OrderID | The ID of an order to which the products should be attached.
FUSER_ID | The internal ID of the basket owner. If omitted (null) or if the current user is not granted write permission for the e-Store module, the current user internal ID is used instead.
strLang | The site from which the basket is set to be ordered. If omitted, the current site is used.
arDiscounts | Associated array containing the discount values. Each key in the array is the ID of a basket item record. The corresponding value is the value of discount. If omitted (set to false), discounts are not applied.

Example

<?
// Attach records of the current user basket to the order $ORDER_ID
// Set the discount to 5%

$arDiscounts = array();

$arRes = GetBasketList();
for ($i = 0; $i<count($arRes); $i++)
{
   if ($arRes[$i]["DELAY"]=="N" && $arRes[$i]["CAN_BUY"]=="Y")
   {
      $curDiscount = roundEx(DoubleVal($arRes[$i]["PRICE"])*5/100, 2);
      $arDiscounts[IntVal($arRes[$i]["ID"])] = $curDiscount;
   }
}

// Create order considering the discount value
 * * *
// $ORDER_ID contains the order ID

CSaleBasket::OrderBasket($ORDER_ID,
                         $_SESSION["SALE_USER_ID"], SITE_ID, $arDiscounts);
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleBasket::Update

int
CSaleBasket::Update(
  int ID,
  array arFields
);

The method Update replaces parameters of the specified product with the new ones.

Parameters

Parameter | Description
ID | The ID of the basket item.
arFields Associated array containing new parameters of basket item. The following keys are possible:
  • PRODUCT_ID - the product ID unique within the module;
  • PRODUCT_PRICE_ID - the product auxiliary ID;
  • PRICE - price of a single product item;
  • CURRENCY - currency of the PRICE;
  • WEIGHT - weight of a single product item ;
  • QUANTITY - number of product items. If QUANTITY is null, the product is removed from the basket;
  • LID - the site from which purchase originates;
  • DELAY - flag "save for later purchase" (Y/N);
  • CAN_BUY - flag "can be purchased" (Y/N) - can be set automatically if the actualization callback function is provided;
  • NAME - product name (required);
  • CALLBACK_FUNC - name of the callback function used to maintain the basket actuals (see CSaleBasket::Add for details);
  • MODULE - the module adding the product;
  • NOTES - other special notes;
  • ORDER_CALLBACK_FUNC - name of the ordering process callback function (see CSaleBasket::Add for details);
  • DETAIL_PAGE_URL - URL of the page with the product details;
  • PROPS - array of properties of the product in the basket. Each element of this array is its turn an array of the following format:
    array("NAME" =>  "Property name",
      "CODE" =>  "Property identifier",
      "VALUE" => "Property value",
      "SORT" =>  "Sort weight")

Return Values

Returns the ID of the updated basket item.

Example

<?
// Change the quantity of a product $ID
// to 2 pcs and hold the product
$arFields = array(
   "QUANTITY" => 2,
   "DELAY" => "Y"
);
CSaleBasket::Update($ID, $arFields);
?>
© 2001-2005 Bitrix Bitrix Site Manager


UpdatePrice

CSaleBasket::UpdatePrice

CSaleBasket::UpdatePrice(
  int ID,
  string CALLBACK_FUNC = "",
  string MODULE = "",
  int PRODUCT_ID = 0,
  int QUANTITY = 0
);

The method UpdatePrice updates the basket item using the callback function.

Parameters

Parameter | Description
ID | The ID of the basket item.
CALLBACK_FUNC | Name of the callback function used to maintain the basket actuals.
MODULE | Module adding the product to the basket.
PRODUCT_ID | The product ID unique within the module.
QUANTITY | Number of products.

Example

<?
//
// GetBasketList() - the standard e-Store module function
//
function GetBasketList()
{
   CSaleBasket::Init();
   $arRes = array();
   $db_res = CSaleBasket::GetList(($by="NAME"),
                                  ($order="ASC"),
                                  array("FUSER_ID"=>$_SESSION["SALE_USER_ID"],
                                        "LID"=>SITE_ID, "ORDER_ID"=>"NULL"));

   while ($res = $db_res->GetNext())
   {
      if (strlen($res["CALLBACK_FUNC"])>0)
      {
         CSaleBasket::UpdatePrice($res["ID"],
                                  $res["CALLBACK_FUNC"],
                                  $res["MODULE"],
                                  $res["PRODUCT_ID"],
                                  $res["QUANTITY"]);
         $res = CSaleBasket::GetByID($res["ID"]);
      }
      $arRes[] = $res;
   }
   return $arRes;
}

$arBasket = GetBasketList();

echo "<pre>";
print_r($arBasket);
echo "</pre>";
?>
© 2001-2005 Bitrix Bitrix Site Manager


CSaleDelivery

The CSaleDelivery class is used to add, delete and modify delivery services. It can also retrieve delivery services appropriate for the given location.

Methods

Method | Description
GetByID | Returns parameters of the delivery service.
GetLocationList | Returns a filtered list of locations.
Update | Replaces parameters of the delivery service with the new ones.
Delete | Deletes a delivery service.
GetList | Returns a filtered list of delivery services.
Add | Adds a new delivery service.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleDelivery::Add

int
CSaleDelivery::Add(
  array arFields
);

The method Add adds a new delivery service.

Parameters

Parameter Description
arFields Associated array containing the delivery service parameters. In this array, the keys are the parameter names, and the values are the delivery parameter values. The following keys are possible:
  • NAME - name of the delivery service (required; specified in the language of the site to which this delivery service is bound);
  • LID - the site to which this delivery service is bound;
  • PERIOD_FROM - minimum time of delivery;
  • PERIOD_TO - maximum time of delivery;
  • PERIOD_TYPE - time of delivery measurement unit: H - hours, D - days, M - months;
  • WEIGHT_FROM - minimum order weight that this delivery service can handle (measurement unit must be common within the site);
  • WEIGHT_TO - maximum order weight that this delivery service can handle (measurement unit must be common within the site);
  • ORDER_PRICE_FROM - minimum order price that this delivery service can handle;
  • ORDER_PRICE_TO - maximum order price that this delivery service can handle;
  • ORDER_CURRENCY - currency in which both ORDER_PRICE_FROM and ORDER_PRICE_TO are specified;
  • ACTIVE - delivery service active state flag (Y/N);
  • PRICE - cost of delivery;
  • CURRENCY - currency of the cost;
  • SORT - sort weight;
  • DESCRIPTION - delivery service description;
  • LOCATIONS - array of arrays in the format:
    array("LOCATION_ID"=>"location_ID or location_group_ID",
      "LOCATION_TYPE"=>"L - location or G - group")
    This array defines locations and group of locations allowed by this delivery service.

Return Values

Returns the new record ID on success or false otherwise.

Example

<?
$arFields = array(
   "NAME" => "By courier",
   "LID" => "en",
   "PERIOD_FROM" => 1,
   "PERIOD_TO" => 3,
   "PERIOD_TYPE" => "D",
   "WEIGHT_FROM" => 0,
   "WEIGHT_TO" => 2500,
   "ORDER_PRICE_FROM" => 0,
   "ORDER_PRICE_TO" => 10000,
   "ORDER_CURRENCY" => "EUR",
   "ACTIVE" => "Y",
   "PRICE" => 58,
   "CURRENCY" => "RUR",
   "SORT" => 100,
   "DESCRIPTION" => "Delivers within 3 to 10 business days".
                    "after the order acceptance.",
   "LOCATIONS" => array(
      array("LOCATION_ID"=>1, "LOCATION_TYPE"=>"L"),
      array("LOCATION_ID"=>3, "LOCATION_TYPE"=>"G")
      )
);

$ID = CSaleDelivery::Add($arFields);
if ($ID<=0)
   echo "Error adding a delivery service";
?>
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleDelivery::Delete

bool
CSaleDelivery::Delete(
  int ID
);

The method Delete deletes a delivery service.

Parameters

Parameter | Description
ID | The ID of the delivery service to be deleted.

Return Values

Returns true on success or false otherwise.

Example

<?
CSaleDelivery::Delete(8);
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleDelivery::GetByID

array
CSaleDelivery::GetByID(
  int ID
);

The method GetByID returns parameters of the delivery service.

Parameters

Parameter | Description
ID | The ID of the delivery service whose parameters are to be returned.

Return Values

Returns the associated array with the following keys.

Key | Description
ID | The delivery service ID.
NAME | Name of the delivery service.
LID | The ID of the site to which this service is bound.
PERIOD_FROM | Minimum time of delivery.
PERIOD_TO | Maximum time of delivery.
PERIOD_TYPE | Time of delivery measurement unit: H - hours, D - days, M - months.
WEIGHT_FROM | Minimum order weight that this delivery service can handle (measurement unit must be common within the site).
WEIGHT_TO | Maximum order weight that this delivery service can handle (measurement unit must be common within the site).
ORDER_PRICE_FROM | Minimum order price that this delivery service can handle.
ORDER_PRICE_TO | Maximum order price that this delivery service can handle.
ORDER_CURRENCY | Currency in which both ORDER_PRICE_FROM and ORDER_PRICE_TO are specified.
ACTIVE | Delivery service active state flag (Y/N).
PRICE | Cost of delivery.
CURRENCY | Currency of the cost.
SORT | Sort weight.
DESCRIPTION | Delivery service description.

Example

<?
// $DELIVERY_ID - delivery service ID

$arDeliv = CSaleDelivery::GetByID($DELIVERY_ID);
if ($arDeliv)
{
   echo "Delivery with \"".
        $arDeliv["NAME"]."\" costs ".
        CurrencyFormat($arDeliv["PRICE"],
        $arDeliv["CURRENCY"]);
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleDelivery::GetList

CDBResult
CSaleDelivery::GetList(
  array arOrder = Array("SORT"=>"ASC",
                        "NAME"=>"ASC"),
  array arFilter = Array()
);

The method GetList returns a filtered list of delivery services.

Parameters

Parameter Description
arOrder Associated array containing parameter used to sort the returned list. The list is sorted by all array entries consecutively. The array keys are the delivery service parameter names. The corresponding values are the sort direction identifiers.

The following keys are possible:
  • NAME - name of the delivery service;
  • ID - the delivery service ID;
  • LID - the site to which this delivery service is bound;
  • PERIOD_FROM - minimum time of delivery;
  • PERIOD_TO - maximum time of delivery;
  • PERIOD_TYPE - time of delivery measurement unit: H - hours, D - days, M - months;
  • PRICE - cost of delivery;
  • CURRENCY - currency of the cost ;
  • SORT - sort weight.
The following values are possible:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the delivery service parameter names, and values are the conditions.

The following keys are possible:
  • ID - the delivery service ID;
  • LID - the site to which this delivery service is bound;
  • PERIOD_FROM - minimum time of delivery;
  • PERIOD_TO - maximum time of delivery;
  • PERIOD_TYPE - time of delivery measurement unit: H - hours, D - days, M - months;
  • WEIGHT_FROM - minimum order weight that this delivery service can handle (measurement unit must be common within the site);
  • WEIGHT_TO - maximum order weight that this delivery service can handle (measurement unit must be common within the site);
  • WEIGHT - this value must be from WEIGHT_FROM to WEIGHT_TO (measurement unit must be common within the site);
  • ORDER_PRICE - this value must be from ORDER_PRICE_FROM to ORDER_PRICE_TO (specified in the base currency of the site identified by LID);
  • ORDER_PRICE_FROM - minimum order price that this delivery service can handle;
  • ORDER_PRICE_TO - maximum order price that this delivery service can handle;
  • ORDER_CURRENCY - currency in which values ORDER_... are specified;
  • ACTIVE - delivery service active state flag (Y/N) ;
  • LOCATION - this value (location code) should be one of those that this delivery service allows.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The delivery service ID.
NAME | Name of the delivery service.
LID | The ID of the site to which this service is bound.
PERIOD_FROM | Minimum time of delivery.
PERIOD_TO | Maximum time of delivery.
PERIOD_TYPE | Time of delivery measurement unit: H - hours, D - days, M - months.
WEIGHT_FROM | Minimum order weight that this delivery service can handle (measurement unit must be common within the site).
WEIGHT_TO | Maximum order weight that this delivery service can handle (measurement unit must be common within the site).
ORDER_PRICE_FROM | Minimum order price that this delivery service can handle.
ORDER_PRICE_TO | Maximum order price that this delivery service can handle.
ORDER_CURRENCY | Currency in which both ORDER_PRICE_FROM and ORDER_PRICE_TO are specified.
ACTIVE | Delivery service active state flag (Y/N).
PRICE | Cost of delivery.
CURRENCY | Currency of the cost.
SORT | Sort weight.
DESCRIPTION | Delivery service description.

Example

<?
// Select active delivery services
// firstly sorted by the sort weight and secondly by name.
// The selected services are available for the current site,
// can handle orders with weight $ORDER_WEIGHT and
// cost $ORDER_PRICE (in the current site currency),
// can deliver to $DELIVERY_LOCATION

$db_dtype = CSaleDelivery::GetList(
    Array("SORT"=>"ASC", "NAME"=>"ASC"),
    Array("LID"=>SITE_ID,
          "WEIGHT"=>$ORDER_WEIGHT,
          "ORDER_PRICE"=>$ORDER_PRICE,
          "ACTIVE"=>"Y",
          "LOCATION"=>$DELIVERY_LOCATION)
);

if ($ar_dtype = $db_dtype->Fetch())
{
   echo "The following delivery services are available:<br>";
   do
   {
      echo $ar_dtype["NAME"].
           " - cost ".
           CurrencyFormat($ar_dtype["PRICE"],
                          $ar_dtype["CURRENCY"])."<br>";
   }
   while ($ar_dtype = $db_dtype->Fetch())
}
else
{
   else "Cannot find an appropriate delivery service<br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetLocationList

CSaleDelivery::GetLocationList

CDBResult
CSaleDelivery::GetLocationList(
  array arFilter = Array()
);

The method GetLocationList returns a filtered list of locations.

Parameters

Parameter Description
arFilter The filter is an associated array whose keys are the parameter names, and values are the conditions.

The following keys are possible:
  • DELIVERY_ID - the delivery service ID;
  • LOCATION_ID - the location ID or the location group ID;
  • LOCATION_TYPE - type of location (L - single location, G - group of locations).

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
DELIVERY_ID | The delivery service ID.
LOCATION_ID | The location ID or the location group ID.
LOCATION_TYPE | Type of location (L - single location, G - group of locations).
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleDelivery::Update

int
CSaleDelivery::Update(
  int ID,
  array arFields
);

The method Update replaces parameters of the delivery service with the new ones.

Parameters

Parameter | Description
ID | The ID of the delivery service whose parameters are to be updated.
arFields Associated array containing new parameters of the delivery service. In this array, the keys are the parameter names, and the values are the delivery parameter values. The following keys are possible:
  • NAME - name of the delivery service (required; specified in the language of the site to which this delivery service is bound);
  • LID - the site to which this delivery service is bound;
  • PERIOD_FROM - minimum time of delivery;
  • PERIOD_TO - maximum time of delivery;
  • PERIOD_TYPE - time of delivery measurement unit: H - hours, D - days, M - months;
  • WEIGHT_FROM - minimum order weight that this delivery service can handle (measurement unit must be common within the site);
  • WEIGHT_TO - maximum order weight that this delivery service can handle (measurement unit must be common within the site);
  • ORDER_PRICE_FROM - minimum order price that this delivery service can handle;
  • ORDER_PRICE_TO - maximum order price that this delivery service can handle;
  • ORDER_CURRENCY - currency in which both ORDER_PRICE_FROM and ORDER_PRICE_TO are specified;
  • ACTIVE - delivery service active state flag (Y/N) ;
  • PRICE - cost of delivery;
  • CURRENCY - currency of the cost ;
  • SORT - sort weight;
  • DESCRIPTION - delivery service description;
  • LOCATIONS - array of arrays in the format:
    array("LOCATION_ID"=>"location_ID or location_group_ID",
      "LOCATION_TYPE"=>"L - location or G - group")
    This array defines locations and group of locations allowed by this delivery service.

Return Values

Returns the ID of the updated record on success or false otherwise.

Example

<?
$arFields = array(
   "NAME" => "By courier",
   "LID" => "en",
   "PERIOD_FROM" => 1,
   "PERIOD_TO" => 3,
   "PERIOD_TYPE" => "D",
   "WEIGHT_FROM" => 0,
   "WEIGHT_TO" => 2500,
   "ORDER_PRICE_FROM" => 0,
   "ORDER_PRICE_TO" => 10000,
   "ORDER_CURRENCY" => "EUR",
   "ACTIVE" => "Y",
   "PRICE" => 58,
   "CURRENCY" => "RUR",
   "SORT" => 100,
   "DESCRIPTION" => "Delivers within 3 to 10 business days".
                    "after the order acceptance.",
   "LOCATIONS" => array(
      array("LOCATION_ID"=>1, "LOCATION_TYPE"=>"L"),
      array("LOCATION_ID"=>3, "LOCATION_TYPE"=>"G")
      )
);

if (!CSaleDelivery::Update($ID, $arFields))
   echo "Error updating the delivery service";
?>
© 2001-2005 Bitrix Bitrix Site Manager


CSaleDiscount

The CSaleDiscount class is used to manipulate discounts.

Methods

Method | Description
GetList | Returns a sorted and filtered list of discounts.
GetByID | Returns the discount parameters.
Update | Updates parameters of the discount.
Delete | Deletes a discount.
Add | Adds a new discount.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleDiscount::Add

int
CSaleDiscount::Add(
  array arFields
);

The method Add adds a new discount.

Parameters

Parameter Description
arFields Associated array whose keys are the discount parameter names, and the values are the parameter values.

The following keys are possible:
  • LID - the ID of the site to which this discount is bound;
  • PRICE_FROM - minimum total order price to which this discount is applicable;
  • PRICE_TO - maximum total order price to which this discount is applicable;
  • CURRENCY - currency in which all money values are specified in this record;
  • DISCOUNT_VALUE - discount value;
  • DISCOUNT_TYPE - type of the discount value (P - percentage, V - absolute value);
  • ACTIVE - flag indicating the discount is active (Y/N);
  • SORT - sort weight. If more than one discount can be applied to an order price, the discount with the less SORT is taken first.

Return Values

Returns the ID of the new discount or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleDiscount::Delete

bool
CSaleDiscount::Delete(
  int ID
);

The method Delete deletes a discount.

Parameters

Parameter | Description
ID | The discount ID to be deleted.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleDiscount::GetByID

array
CSaleDiscount::GetByID(
  int ID
);

The method GetByID returns the discount parameters.

Parameters

Parameter | Description
ID | The ID of the discount whose parameters are to be returned.

Return Values

Associated array of the discount parameters; has the following keys.

Key | Description
ID | The discount ID.
LID | The ID of the site to which this discount is bound.
PRICE_FROM | Minimum total order price to which this discount is applicable.
PRICE_TO | Maximum total order price to which this discount is applicable.
CURRENCY | Currency in which all money values are specified in this record.
DISCOUNT_VALUE | Discount value.
DISCOUNT_TYPE | Type of the discount value (P - percentage, V - absolute value).
ACTIVE | Flag indicating the discount is active (Y/N).
SORT | Sort weight. If more than one discount can be applied to an order price, the discount with the less SORT is taken first.
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleDiscount::GetList

CDBResult
CSaleDiscount::GetList(
  string &by,
  string &order,
  array arFilter = Array()
);

The method GetList returns a sorted and filtered list of discounts.

Parameters

Parameter Description
by Specifies the name of the parameter by which the result is to be sorted. Can be one of the following values:
  • ID - the discount ID (default);
  • LID - the ID of the site to which this discount is bound;
  • ACTIVE - flag indicating the discount is active (Y/N);
  • SORT - sort weight.
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the discount parameter names, and values are the conditions.

The following keys are possible:
  • LID - the ID of the site to which this discount is bound;
  • ACTIVE - flag indicating the discount is active (Y/N);
  • PRICE - this value ranges from PRICE_FROM to PRICE_TO of the returned discounts, specified in the base currency of the site LID;
  • PRICE_FROM - this value specifies the minimum order price to which the discount is applicable, specified in the base currency of the site LID;
  • PRICE_TO - this value specifies the minimum order price to which the discount is applicable, specified in the base currency of the site LID.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The discount ID.
LID | The ID of the site to which this discount is bound.
PRICE_FROM | Minimum total order price to which this discount is applicable.
PRICE_TO | Maximum total order price to which this discount is applicable.
CURRENCY | Currency in which all money values are specified in this record.
DISCOUNT_VALUE | Discount value.
DISCOUNT_TYPE | Type of the discount value (P - percentage, V - absolute value).
ACTIVE | Flag indicating the discount is active (Y/N).
SORT | Sort weight. If more than one discount can be applied to an order price, the discount with the less SORT is taken first.

Example

<?
// Get the value of the active discount for the current site
// and the order price $ORDER_PRICE in the base currency of the site
$db_res = CSaleDiscount::GetList(($by="SORT"),
                                 ($order="ASC"),
                                 Array("LID"=>SITE_ID,
                                       "ACTIVE"=>"Y",
                                       "PRICE"=>$ORDER_PRICE));
if ($ar_res = $db_res->Fetch())
{
   echo "Discount is ";
   if ($ar_res["DISCOUNT_TYPE"] == "P")
   {
      echo $ar_res["DISCOUNT_VALUE"]."%";
   }
   else
   {
      echo CurrencyFormat($ar_res["DISCOUNT_VALUE"], $ar_res["CURRENCY"]);
   }
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleDiscount::Update

int
CSaleDiscount::Update(
  int ID,
  array arFields
);

The method Update updates parameters of the discount.

Parameters

Parameter | Description
ID | The discount ID.
arFields Associated array whose keys are the names of the discount parameters to be updated, and values are the new parameter values. You can specify keys that require update only; other parameters remain will untouched.

The following keys are possible:
  • LID - the ID of the site to which this discount is bound;
  • PRICE_FROM - minimum total order price to which this discount is applicable;
  • PRICE_TO - maximum total order price to which this discount is applicable;
  • CURRENCY - currency in which all money values are specified in this record;
  • DISCOUNT_VALUE - discount value;
  • DISCOUNT_TYPE - type of the discount value (P - percentage, V - absolute value);
  • ACTIVE - flag indicating the discount is active (Y/N);
  • SORT - sort weight. If more than one discount can be applied to an order price, the discount with the less SORT is taken first.

Return Values

Returns the ID of the updated discount or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleLocation

The CSaleLocation class is used to create, delete and modify delivery locations, as well as to obtain information on the existing locations.

Methods

Method | Description
GetCountryByID | Returns language-independent parameters of a country.
GetCountryLangByID | Returns the language dependent parameters of a country.
GetCityByID | Returns the language-independent parameters of a city.
GetCityLangByID | Returns language dependent parameters of a city.
UpdateCountry | Replaces the country parameters with the new ones from the supplied array.
DeleteCountry | Deletes the country. All location bound to this country remain untouched.
UpdateCity | Replaces the city parameters with the new ones from the supplied array.
DeleteCity | Deletes the existing city. Location to which this city is bound is not changed.
UpdateLocation | Replaces the location parameters with the new ones from the supplied array.
Add | Adds a new location, optionally including the country and the city.
Update | Replaces the location parameters with the new ones from the supplied array.
Delete | Deletes the existing location.
GetList | Returns a sorted and filtered list of locations.
GetByID | Returns parameters of a specified location.
GetCountryList | Returns a filtered and sorted list of countries.
AddCountry | Adds a new country.
AddCity | Adds a new city.
AddLocation | Adds a new location given the existing city and country ID's.
DeleteAll | Deletes all locations from the database.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleLocation::Add

int
CSaleLocation::Add(
  array arFields
);

The method Add adds a new location, optionally including the country and the city.

Parameters

Parameter Description
arFields Associated array of the location parameters. The following keys are possible:
  • SORT - sort weight;
  • COUNTRY_ID - the ID of the country currently existing in the system. If the country has not been previously created, the COUNTRY key must be specified;
  • COUNTRY - array of the country parameters; if the country has been previously created and COUNTRY_ID contains a valid ID, this array is not used;
  • WITHOUT_CITY - flag (Y/N) specifying the location without a city (country only). If "N", the CITY key must be specified;
  • CITY - array containing the city parameters. Not used if WITHOUT_CITY is "Y".
The COUNTRY array must have the following keys specified:
  • NAME - the country name (language-independent);
  • SHORT_NAME - country name abbreviation (language-independent);
  • <language ID> - the key is the language name. The value is an associated array in the format:
    array("LID" => "language ID",
      "NAME" => "country name in this language",
      "SHORT_NAME" => "country name abbreviation
                       in this language").
    Such pair must be specified for every language in the system.
The CITY array must have the following keys specified:
  • NAME - the city name (language-independent);
  • SHORT_NAME - city name abbreviation (language-independent);
  • <language ID> - the key is the language name. The value is an associated array in the format:
    array("LID" => "language ID",
      "NAME" => "country name in this language",
      "SHORT_NAME" => "country name abbreviation
                       in this language").
    Such pair must be specified for every language in the system.

Return Values

Returns the new location ID on success, or false otherwise.

Example

<?
$arFields = array(
   "SORT" => 100,
   "COUNTRY_ID" => 0,
   "WITHOUT_CITY" => "N"
);

$arCountry = array(
   "NAME" => "France",
   "SHORT_NAME" => "FR",
   "fr" => array(
      "LID" => "fr",
      "NAME" => "France",
      "SHORT_NAME" => "FR"
      )
   "en" => array(
      "LID" => "en",
      "NAME" => "France",
      "SHORT_NAME" => "FR"
      ),
);

$arFields["COUNTRY"] = $arCountry;

$arCity = array(
   "NAME" => "Paris",
   "SHORT_NAME" => "Paris",
   "fr" => array(
      "LID" => "fr",
      "NAME" => "Paris",
      "SHORT_NAME" => "Paris"
      ),
   "en" => array(
      "LID" => "en",
      "NAME" => "Paris",
      "SHORT_NAME" => "Paris"
      )
);

$arFields["CITY"] = $arCity;

$ID = CSaleLocation::Add($arFields);
if (IntVal($ID)<=0)
   echo "Error adding location";
?>
© 2001-2005 Bitrix Bitrix Site Manager


AddCity

CSaleLocation::AddCity

int
CSaleLocation::AddCity(
  array arFields
);

The method AddCity adds a new city.

Parameters

Parameter Description
arFields Associated array with parameters of the city to be added. The following keys are possible:
  • NAME - the city name (language-independent);
  • SHORT_NAME - city name abbreviation (language-independent);
  • <language ID> - the key is the language name. The value is an associated array in the format:
    array("LID" => "language ID",
      "NAME" => "city name in this language",
      "SHORT_NAME" => "city name abbreviation
                       in this language").
    Such pair must be specified for every language in the system.

Return Values

Returns the new city ID on success, or false otherwise.

Example

<?
$arCity = array(
   "NAME" => "Paris",
   "SHORT_NAME" => "Paris",
   "fr" => array(
      "LID" => "fr",
      "NAME" => "Paris",
      "SHORT_NAME" => "Paris"
      ),
   "en" => array(
      "LID" => "en",
      "NAME" => "Paris",
      "SHORT_NAME" => "Paris"
      )
);

$ID = CSaleLocation::AddCity($arCity);
if (IntVal($ID)<=0)
   echo "Error adding city";
?>
© 2001-2005 Bitrix Bitrix Site Manager


AddCountry

CSaleLocation::AddCountry

int
CSaleLocation::AddCountry(
  array arFields
);

The method AddCountry adds a new country.

Parameters

Parameter Description
arFields Associated array with parameters of the country to be added. The following keys are possible:
  • NAME - the country name (language-independent);
  • SHORT_NAME - country name abbreviation (language-independent);
  • <language ID> - the key is the language name. The value is an associated array in the format:
    array("LID" => "language ID",
      "NAME" => "country name in this language",
      "SHORT_NAME" => "country name abbreviation
                       in this language").
    Such pair must be specified for every language in the system.

Return Values

Returns the new country ID on success or false otherwise.

Example

<?
$arCountry = array(
   "NAME" => "France",
   "SHORT_NAME" => "FR",
   "fr" => array(
      "LID" => "fr",
      "NAME" => "France",
      "SHORT_NAME" => "FR"
      )
   "en" => array(
      "LID" => "en",
      "NAME" => "France",
      "SHORT_NAME" => "FR"
      ),
);

$ID = CSaleLocation::AddCountry($arCountry);
if (IntVal($ID)<=0)
   echo "Error adding country";
?>
© 2001-2005 Bitrix Bitrix Site Manager


AddLocation

CSaleLocation::AddLocation

int
CSaleLocation::AddLocation(
  array arFields
);

The method AddLocation adds a new location given the existing city and country ID's.

Parameters

Parameter Description
arFields Assosiated array of the location parameters. The following keys are possible:
  • SORT - sort weight;
  • COUNTRY_ID - the country ID;
  • CITY_ID - the city ID.

Return Values

Returns the new location ID on success, or false otherwise.

Example

<?
// Add a location: country with ID of 2 and city with ID of 10
$ID = CSaleLocation::AddLocation(
      array(
         "COUNTRY_ID" => 2,
         "CITY_ID" => 10
         )
      );
?>
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleLocation::Delete

bool
CSaleLocation::Delete(
  int ID
);

The method Delete deletes the existing location. The method also deletes the location city, the location country (if the latter is not a member of any other location). All links of the deleted location to location groups and delivery services are also deleted.

Parameters

Parameter | Description
ID | The ID of the location to be deleted.

Return Values

Returns true on success, or false otherwise.

Example

<?
if (!CSaleLocation::Delete(12))
   echo "Error deleting location";
?>
© 2001-2005 Bitrix Bitrix Site Manager


DeleteAll

CSaleLocation::DeleteAll

CSaleLocation::DeleteAll();

The method DeleteAll deletes all locations from the database.

© 2001-2005 Bitrix Bitrix Site Manager


DeleteCity

CSaleLocation::DeleteCity

bool
CSaleLocation::DeleteCity(
  int ID
);

The method DeleteCity deletes the existing city. Location to which this city is bound is not changed.

Parameters

Parameter | Description
ID | The ID of the city to be deleted.

Return Values

Returns true on success, or false otherwise.

Example

<?
if (!CSaleLocation::DeleteCity(12))
   echo "Error deleting city";
?>
© 2001-2005 Bitrix Bitrix Site Manager


DeleteCountry

CSaleLocation::DeleteCountry

bool
CSaleLocation::DeleteCountry(
  int ID
);

The method DeleteCountry deletes the country. All location bound to this country remain untouched.

Parameters

Parameter | Description
ID | The ID of the country to be deleted.

Return Values

Returns true on success, or false otherwise.

Example

<?
if (!CSaleLocation::DeleteCountry(12))
   echo "Error deleting country";
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleLocation::GetByID

array
CSaleLocation::GetByID(
 int ID,
 string strLang = LANGUAGE_ID
);

The method GetByID returns parameters of a specified location. The returned information includes country and city parameters. Language-dependent parameters are returned for the language specified in the second parameter.

Parameters

Parameter | Description
ID | The location ID.
strLang | The ID of the language in which the language-dependent parameters will be returned. By default, the current language is used.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The location ID.
COUNTRY_ID | The country ID.
CITY_ID | The city ID.
SORT | Sort weight.
COUNTRY_NAME_ORIG | Language-independent country name.
COUNTRY_SHORT_NAME | Short language-independent country name abbreviation.
COUNTRY_NAME_LANG | Language-dependent country name.
CITY_NAME_ORIG | Language-independent city name.
CITY_SHORT_NAME | Short language-independent city name abbreviation.
CITY_NAME_LANG | Language-dependent city name.
COUNTRY_NAME | Language-dependent country name (if exists, or language-independent country name otherwise).
CITY_NAME | Language-dependent country name (if exists, or language-independent country name otherwise).

Example

<?
$arLocs = CSaleLocation::GetByID(22, LANGUAGE_ID);
echo $arLocs["COUNTRY_NAME"]." - ".$arLocs["CITY_NAME"];
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetCityByID

CSaleLocation::GetCityByID

array
CSaleLocation::GetCityByID(
  int ID
);

The method GetCityByID returns the language-independent parameters of a city.

Parameters

Parameter | Description
ID | The city ID

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The city ID.
NAME | Language-independent city name.
SHORT_NAME | Short language-independent city name.
© 2001-2005 Bitrix Bitrix Site Manager


GetCityLangByID

CSaleLocation::GetCityLangByID

array
CSaleLocation::GetCityLangByID(
  int ID,
  string strLang = LANGUAGE_ID
);

The method GetCityLangByID returns language dependent parameters of a city.

Parameters

Parameter | Description
ID | The city ID.
strLang | The ID of the language in which the language-dependent parameters will be returned. By default, the current language is used.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The record ID.
CITY_ID | The city ID.
LID | Language.
NAME | Language-dependent city name.
SHORT_NAME | Short language-dependent city name abbreviation.

© 2001-2005 Bitrix Bitrix Site Manager


GetCountryByID

CSaleLocation::GetCountryByID

array
CSaleLocation::GetCountryByID(
  int ID
);

The method GetCountryByID returns language-independent parameters of a country.

Parameters

Parameter | Description
ID | The country ID.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The country ID.
NAME | Language-independent country name.
SHORT_NAME | Short language-independent name of the country.

© 2001-2005 Bitrix Bitrix Site Manager


GetCountryLangByID

CSaleLocation::GetCountryLangByID

array
CSaleLocation::GetCountryLangByID(
  int ID,
  string strLang = LANGUAGE_ID
);

The method GetCountryLangByID returns the language dependent parameters of a country.

Parameters

Parameter | Description
ID | The country ID.
strLang | The ID of the language in which the language-dependent parameters will be returned. By default, the current language is used.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The record ID.
CITY_ID | The country ID.
LID | Language.
NAME | Language-dependent country name
SHORT_NAME | Short language-dependent country name abbreviation.

© 2001-2005 Bitrix Bitrix Site Manager


GetCountryList

CSaleLocation::GetCountryList

CDBResult
CSaleLocation::GetCountryList(
  array arOrder = Array("NAME_LANG"=>"ASC"),
  array arFilter = Array(),
  string strLang = LANGUAGE_ID
);

The method GetCountryList returns a filtered and sorted list of countries. Language-dependent parameters are returned for the language specified in the second parameter.

Parameters

Parameter | Description
arOrder Assosiated array defining the record sorting. Sorting is performed consequently on each pair "key - value". Keys are the parameter names. Values are sort direction constants.

The following keys are possible:
  • NAME_LANG - language dependent country name;
  • ID - the country ID;
  • NAME - language independent country name;
  • SHORT_NAME - language independent country name abbreviation.
Possible values:
  • ASC - ascending;
  • DESC - descending
arFilter Assosiated array used to filter records. Only the records which satisfy the filter are included in the returned list. Keys are the parameter names, and the values are conditions.

The following keys are possible:
  • ID - the country ID;
  • NAME - language independent country name
strLang | The ID of the language in which the language-dependent parameters will be returned. By default, the current language is used.

Return Values

Returns a CDBResult instance containing a set of associated arrays with the following keys.

Key | Description
ID | The country ID.
NAME_ORIG | Language-independent country name
SHORT_NAME | Short language-independent name of the country
NAME | Language dependent country name
NAME_LANG | Language dependent country name if it exists. Otherwise, language-independent name of the country.
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleLocation::GetList

CDBResult
CSaleLocation::GetList(
 array arOrder =
       Array("SORT" => "ASC",
             "COUNTRY_NAME_LANG" => "ASC",
             "CITY_NAME_LANG" => "ASC"),
 array arFilter = Array(),
 string strLang = LANGUAGE_ID
);

The method GetList returns an optionally sorted and filtered list of locations. The list returned also contains parameters of the location countries and cities. Language-dependent parameters are returned for the language specified in the third parameter.

Parameters

Parameter | Description
arOrder Associated array used to sort records. The sorting is performed consequently on each pair "key-value". Keys are the parameter names. Values are sort direction constants.

The following keys are possible:
  • SORT - sort weight;
  • COUNTRY_ID - the country ID;
  • ID - the location ID;
  • CITY_ID - the city ID;
  • COUNTRY_NAME - language independent country name;
  • CITY_NAME - language independent city name;
  • COUNTRY_NAME_LANG - language dependent country name;
  • CITY_NAME_LANG - language dependent city name.
Possible values:
  • ASC - ascending;
  • DESC - descending.
arFilter Associated array used to filter records. Only the records which satisfy the filter are included in the returned list. Keys are the parameter names, and the values are conditions.

The following keys are possible:
  • COUNTRY_ID - the country ID;
  • ID - the location ID;
  • CITY_ID - the city ID;
  • COUNTRY - the country name;
  • CITY - the city name.
strLang | The ID of the language in which the language-dependent parameters will be returned. By default, the current language is used.

Return Values

Returns a CDBResult instance containing a set of associated arrays with the following keys.

Key | Description
ID | The location ID.
COUNTRY_ID | The country ID.
CITY_ID | The city ID.
SORT | Sort weight.
COUNTRY_NAME_ORIG | Language-independent country name.
COUNTRY_SHORT_NAME | Short language-independent country name abbreviation.
COUNTRY_NAME_LANG | Language-dependent country name.
CITY_NAME_ORIG | Language-independent city name.
CITY_SHORT_NAME | Short language-independent city name abbreviation.
CITY_NAME_LANG | Language-dependent city name.
COUNTRY_NAME | Language-dependent country name (if exists, or language-independent country name otherwise).
CITY_NAME | Language-dependent country name (if exists, or language-independent country name otherwise).

Example

<?// Display a drop-down list of locations?>

<select name="LOCATION">
   <?
   $db_vars = CSaleLocation::GetList(Array("SORT"=>"ASC",
                                           "COUNTRY_NAME_LANG"=>"ASC",
                                           "CITY_NAME_LANG"=>"ASC"),
                                           array(), LANGUAGE_ID);
   while ($vars = $db_vars->Fetch()):
      ?>
      <option value="<?= $vars["ID"]
        ?>"><?= htmlspecialchars($vars["COUNTRY_NAME"]." - ".
         $vars["CITY_NAME"])?></option>
      <?
   endwhile;
   ?>
</select>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleLocation::Update

int
CSaleLocation::Update(
  int ID,
  array arFields
);

The method Update replaces the location parameters with the new ones from the supplied array. The location country and city are updates as well.

Parameters

Parameter | Description
ID | The location ID.
arFields Assosiated array of the location parameters. The following keys are possible:
  • SORT - sort weight;
  • COUNTRY_ID - the ID of the country currently existing in the system. If the country has not been previously created, the COUNTRY key must be specified;
  • COUNTRY - array contaning the country parameters (must be specified if the key COUNTRY_ID is not set or the key CHANGE_COUNTRY is set to "Y");
  • CHANGE_COUNTRY - specifies (Y/N) whether the country parameters should be changed (keys COUNTRY_ID and COUNTRY must be specified);
  • WITHOUT_CITY - specifies (Y/N) that the location has no city (country only). If set to "N", the CITY key must be specified;
  • CITY_ID - the city ID. If the city does not exist, this key must be set to null and the CITY key must be specified);
  • CITY - array with the city parameters (if WITHOUT_CITY is set to "Y", this key is optional).
The COUNTRY array must have the following keys specified:
  • NAME - the country name (language-independent);
  • SHORT_NAME - country name abbreviation (language-independent);
  • <language ID> - the key is the language name. The value is an associated array in the format:
    array("LID" => "language ID",
      "NAME" => "country name in this language",
      "SHORT_NAME" => "country name abbreviation in this language").
    Such pair must be specified for every language in the system.
The CITY array must have the following keys specified:
  • NAME - the city name (language-independent);
  • SHORT_NAME - city name abbreviation (language-independent);
  • <language ID> - the key is the language name. The value is an associated array in the format:
    array("LID" => "language ID",
      "NAME" => "city name in this language",
      "SHORT_NAME" => "city name abbreviation in this language").
    Such pair must be specified for every language in the system.

Return Values

Returns the modified location ID on success, or false otherwise.

Example

<?
$arFields = array(
   "SORT" => 100,
   "COUNTRY_ID" => 8,
   "WITHOUT_CITY" => "N"
);

$arCity = array(
   "NAME" => "Paris",
   "SHORT_NAME" => "Paris",
   "fr" => array(
      "LID" => "fr",
      "NAME" => "Paris",
      "SHORT_NAME" => "Paris"
      ),
   "en" => array(
      "LID" => "en",
      "NAME" => "Paris",
      "SHORT_NAME" => "Paris"
      )
);

$arFields["CITY"] = $arCity;

if (!CSaleLocation::Update(6, $arFields))
   echo "error updating location";
?>
© 2001-2005 Bitrix Bitrix Site Manager


UpdateCity

CSaleLocation::UpdateCity

int
CSaleLocation::UpdateCity(
  int ID,
  array arFields
);

The method UpdateCity replaces the city parameters with the new ones from the supplied array.

Parameters

Parameter | Description
ID | The city ID.
arFields Associated array with parameters of the city to be updated. The following keys are possible:
  • NAME - the city name (language-independent);
  • SHORT_NAME - city name abbreviation (language-independent);
  • <language ID> - the key is the language name. The value is an associated array in the format:
    array("LID" => "language ID",
      "NAME" => "city name in this language",
      "SHORT_NAME" => "city name abbreviation in this language").
    Such pair must be specified for every language in the system.

Return Values

Returns the modified city ID on success, or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


UpdateCountry

CSaleLocation::UpdateCountry

int
CSaleLocation::UpdateCountry(
  int ID,
  array arFields
);

The method UpdateCountry replaces the country parameters with the new ones from the supplied array.

Parameters

Parameter | Description
ID | The country ID.
arFields Associated array with parameters of the country to be updated. The following keys are possible:
  • NAME - the country name (language-independent);
  • SHORT_NAME - country name abbreviation (language-independent);
  • <language ID> - the key is the language name. The value is an associated array in the format:
    array("LID" => "language ID",
      "NAME" => "country name in this language",
      "SHORT_NAME" => "country name abbreviation in this language").
    Such pair must be specified for every language in the system.

Return Values

Returns the modified country ID on success, or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


UpdateLocation

CSaleLocation::UpdateLocation

int
CSaleLocation::UpdateLocation(
  int ID,
  array arFields
);

The method UpdateLocation replaces the location parameters with the new ones from the supplied array.

Parameters

Parameter | Description
ID | The location ID.
arFields Assosiated array of the location parameters. The following keys are possible:
  • SORT - sort weight;
  • COUNTRY_ID - the country ID;
  • CITY_ID - the city ID. If the proposed city does not currently exist, this key must be set to null, and the CITY key should be specified instead.

Return Values

Returns the modified location ID on success, or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleLocationGroup

The CSaleLocationGroup class helps manage location groups.

Methods

Method | Description
Add | Adds a new group of locations.
Delete | Deletes a location group. Locations of this group remain untouched.
GetLocationList | Returns a filtered list of locations that are members of specified location groups.
GetGroupLangByID | Returns the language-dependent parameters of the location group.
GetList | Returns a filtered and sorted list of location groups.
GetByID | Returns parameters of the location group.
Update | Replaces parameters of the location group with the new ones.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleLocationGroup::Add

int
CSaleLocationGroup::Add(
  array arFields
);

The method Add adds a new group of locations.

Parameters

Parameter Description
arFields Associated array whose keys are the location group parameter names, and the values are the parameter values.

The following keys are possible:
  • SORT - sort weight;
  • LOCATION_ID - array of the ID's of locations to be added to the group;
  • LANG - array of language-dependent parameters of the group. Each entry has the following format: array("LID"=>"parameter's language", "NAME"=>"Group name")

Return Values

Returns the ID of the new group on success or false otherwise.

Example

<?
$arFields = array(
   "SORT" => 150,
   "LOCATION_ID" => array(12, 34, 35, 36, 37),
   "LANG" => array(
      array("LID" => "en", "NAME" => "Group 1")
      array("LID" => "fr", "NAME" => "Groupe 1"),
   )
);

$ID = CSaleLocationGroup::Add($arFields);
if (IntVal($ID)<=0)
   echo "Error adding a group";
?>
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleLocationGroup::Delete

bool
CSaleLocationGroup::Delete(
  int ID
);

The method Delete deletes a location group. Locations of this group remain untouched.

Parameters

Parameter | Description
ID | The location group ID.

Return Values

Returns true on success or false otherwise.

Example

<?
if (!CSaleLocationGroup::Delete(2))
   echo "Error deleting a location group";
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleLocationGroup::GetByID

array
CSaleLocationGroup::GetByID(
  int ID,
  string strLang = LANGUAGE_ID
);

The method GetByID returns parameters of the location group. The method allows to specify the language in which the language-dependent parameters are to be returned.

Parameters

Parameter | Description
ID | The location group ID.
strLang | The ID of the language in which the language-dependent parameters are to be returned. By default, the current language is used.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The location group ID.
SORT | Sort weight.
NAME | Group name.
LID | Language in which the name is returned.
© 2001-2005 Bitrix Bitrix Site Manager


GetGroupLangByID

CSaleLocationGroup::GetGroupLangByID

array
CSaleLocationGroup::GetGroupLangByID(
  int ID,
  string strLang = LANGUAGE_ID
);

The method GetGroupLangByID returns the language-dependent parameters of the location group.

Parameters

Parameter | Description
ID | The location group ID.
strLang | The ID of the language in which the language-dependent parameters are to be returned. By default, the current language is used.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The record ID.
LOCATION_GROUP_ID | The location group ID.
NAME | Group name.
LID | Language in which the name is returned.

Example

<?
$arGroupLang = CSaleLocationGroup::GetGroupLangByID(2, "en");
echo $arGroupLang["NAME"];
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleLocationGroup::GetList

CDBResult
CSaleLocationGroup::GetList(
  array arOrder = Array("NAME"=>"ASC"),
  array arFilter = Array(),
  string strLang = LANGUAGE_ID
);

The method GetList returns a filtered and sorted list of location groups.

Parameters

Parameter | Description
arOrder Associated array specifying how the resulting list is to be sorted. Each pair of keys and values are applied consecutively. The keys are the field names by which the list is sorted. The corresponding values define the sort order.

The following keys can be used:
  • ID - the location group ID;
  • NAME - group name;
  • SORT - sort weight.
The following values are possible:
  • ASC - ascending order;
  • DESC - descending order.
arFilter The filter is an associated array whose keys are the group parameter names, and values are the conditions.

The following keys are possible:
  • ID - the location group ID.
strLang | The ID of the language in which the language-dependent parameters are to be returned. By default, the current language is used.

Return Values

Returns an instance of CDBResult containing associated arrays with the following keys.

Key | Description
ID | The location group ID.
SORT | Sort weight.
NAME | Group name.
LID | Language in which the name is returned.

Example

<select name="LOCATION2" size="5" multiple>
   <?
   $db_vars =
        CSaleLocationGroup::GetList(Array("NAME"=>"ASC"),
                                    array(),
                                    LANGUAGE_ID);
   while ($vars = $db_vars->Fetch()):
      ?>
      <option value="<?= $vars["ID"]?>"><?=
       htmlspecialchars($vars["NAME"])?></option>
      <?
   endwhile;
   ?>
</select>
© 2001-2005 Bitrix Bitrix Site Manager


GetLocationList

CSaleLocationGroup::GetLocationList

CDBResult
CSaleLocationGroup::GetLocationList(
  array arFilter = Array()
);

The method GetLocationList returns a filtered list of locations that are members of specified location groups.

Parameters

Parameter Description
arFilter The filter is an associated array whose keys are the record parameter names, and values are the conditions.

The following keys are possible:
  • LOCATION_ID - the location ID;
  • LOCATION_GROUP_ID - the location group ID.

Return Values

Returns an instance of CDBResult containing associated arrays with the following keys.

Key | Description
LOCATION_ID | The location ID.
LOCATION_GROUP_ID | The location group ID.

Example

<?
// Select all locations of the group 2
$db_res = CSaleLocationGroup::GetLocationList(array("LOCATION_GROUP_ID"=>2));
while ($ar_res = $db_res->Fetch())
{
   echo $ar_res["LOCATION_ID"].", ";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleLocationGroup::Update

int
CSaleLocationGroup::Update(
  int ID,
  array arFields
);

The method Update replaces parameters of the location group with the new ones.

Parameters

Parameter | Description
ID | The location group ID.
arFields Associated array containing new parameters of the location group. In this array, the keys are the parameter names, and the values are the new values. The following keys are possible:
  • SORT - sort weight;
  • LOCATION_ID - array of location ID's that are members of this group;
  • LANG - array of language-dependent parameters of the group. Each entry of this array has the following format: array("LID"=>"parameter language", "NAME"=>"Group name")

Return Values

Returns the ID of the updated group on success or false otherwise.

Example

<?
$arFields = array(
   "SORT" => 150,
   "LOCATION_ID" => array(12, 34, 35, 36, 37),
   "LANG" => array(
      array("LID" => "en", "NAME" => "Group 1")
      array("LID" => "fr", "NAME" => "Groupe 1"),
   )
);

if (!CSaleLocationGroup::Update(2, $arFields))
   echo "Error updating a group";
?>
© 2001-2005 Bitrix Bitrix Site Manager


CSaleOrder

The CSaleOrder class provides complete functionality for handling the e-Store orders.

Methods

Method | Description
GetList | Retrieves an optionally sorted and filtered list of orders.
GetByID | Returns the order parameters.
PayOrder | Changes the value of the PAYED field (sets the order as paid).
DeliverOrder | Modifies the value of the ALLOW_DELIVERY field.
CancelOrder | Modifies the value of the CANCELED field of the specified order.
StatusOrder | Changes the value of the STATUS_ID (order status).
CommentsOrder | Sets a new value (text) of the order COMMENTS field.
Delete | Deletes an order.
Add | Creates a new order based on the supplied parameters.
Update | Replaces parameters of an order with the new ones.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleOrder::Add

int
CSaleOrder::Add(
  array arFields
);

The method Add creates a new order based on the supplied parameters.

Parameters

Parameter Description
arFields Associated array of an order parameters whose keys are the order parameter names, and values are the parameter values. The following values are possible:
  • LID - the ID of the site from which an order originates;
  • PERSON_TYPE_ID - payer type of the visitor who made the order (customer);
  • PAYED - specifies whether the order is paid (Y/N);
  • DATE_PAYED - the date of the order payment;
  • EMP_PAYED_ID - the ID of the user (web shop member) who has set the PAYED flag;
  • CANCELED - specifies whether the order is canceled (Y/N);
  • DATE_CANCELED - the date of the order cancellation;
  • EMP_CANCELED_ID - the ID of the user (web shop member) who has set the CANCELED flag;
  • REASON_CANCELED - text description of the order cancellation reason;
  • STATUS_ID - the order status ID;
  • EMP_STATUS_ID - the ID of the user (web shop member) who has set the current STATUS_ID;
  • PRICE_DELIVERY - cost of the order delivery;
  • ALLOW_DELIVERY - specifies whether the order can be shipped (Y/N);
  • DATE_ALLOW_DELIVERY - the date when the order was subjected for shipment;
  • EMP_ALLOW_DELIVERY_ID - the ID of the user (web shop member) who has set the current ALLOW_DELIVERY status;
  • PRICE - total order price;
  • CURRENCY - currency of the order price;
  • DISCOUNT_VALUE - total discount value;
  • USER_ID - the user ID of the customer;
  • PAY_SYSTEM_ID - pay system to handle the payment;
  • DELIVERY_ID - the ID of a delivery service that will handle the order shipment;
  • USER_DESCRIPTION - customer's order description;
  • ADDITIONAL_INFO - additional information on the order;
  • COMMENTS - auxiliary comments;
  • TAX_VALUE - total amount of tax;
  • STAT_GID - the event parameter for use in the Statistics module;
  • PS_STATUS - specifies that the order has been successfully paid (Y/N). Available only for those pay systems which can automatically notify of their orders state;
  • PS_STATUS_CODE - code of the pay system status (depends on the pay system);
  • PS_STATUS_DESCRIPTION - description of the pay system order payment result;
  • PS_STATUS_MESSAGE - message returned from the pay system;
  • PS_SUM - amount of money which was actually paid via the pay system;
  • PS_CURRENCY - payment currency;
  • PS_RESPONSE_DATE - the date when the pay system status was received.

Return Values

Returns the ID of the created order on success, or false otherwise.

Example

<?
$arFields = array(
   "LID" => "en",
   "PERSON_TYPE_ID" => 1,
   "PAYED" => "N",
   "CANCELED" => "N",
   "STATUS_ID" => "N",
   "PRICE" => 279.32,
   "CURRENCY" => "USD",
   "USER_ID" => IntVal($USER->GetID()),
   "PAY_SYSTEM_ID" => 3,
   "PRICE_DELIVERY" => 11.37,
   "DELIVERY_ID" => 2,
   "DISCOUNT_VALUE" => 1.5,
   "TAX_VALUE" => 0.0,
   "USER_DESCRIPTION" => ""
);

// add Guest ID
if (CModule::IncludeModule("statistic"))
   $arFields["STAT_GID"] = CStatistic::GetEventParam();

$ORDER_ID = CSaleOrder::Add($arFields);
$ORDER_ID = IntVal($ORDER_ID);
?>
© 2001-2005 Bitrix Bitrix Site Manager


CancelOrder

CSaleOrder::CancelOrder

int
CSaleOrder::CancelOrder(
  int ID,
  string Val,
  string Descr = ""
);

The method CancelOrder modifies the value of the CANCELED field of the specified order. Besides, it sets the fields DATE_CANCELED (date when the order was canceled) and EMP_CANCELED_ID (the ID of a user (web shop member) who sets this flag). Order cancellation description also can be specified.

Parameters

Parameter | Description
ID | The order ID.
Val | New value of the order cancellation flag (Y/N).
Descr | Text description of the order cancellation reason.

Return Values

Returns the order ID on success, or false otherwise.

Example

<?
CSaleOrder::CancelOrder(25, "Y", "Decided not to buy");
?>
© 2001-2005 Bitrix Bitrix Site Manager


CommentsOrder

CSaleOrder::CommentsOrder

int
CSaleOrder::CommentsOrder(
  int ID,
  string Val
);

The method CommentsOrder sets a new value (text) of the order COMMENTS field.

Parameters

Parameter | Description
ID | The order ID.
Val | The new comment text.

Return Values

Returns the order ID on success, or false otherwise.

Example

<?
if (!CSaleOrder::CommentsOrder(12, "Do not pay until paid!"))
   echo "Error setting the order comment";
?>
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleOrder::Delete

bool
CSaleOrder::Delete(
  int ID
);

The method Delete deletes an order.

Parameters

Parameter | Description
ID | The order ID.

Return Values

Returns the order ID on success, or false otherwise.

Example

<?
CSaleOrder::Delete(23);
?>
© 2001-2005 Bitrix Bitrix Site Manager


DeliverOrder

CSaleOrder::DeliverOrder

int
CSaleOrder::DeliverOrder(
  int ID,
  string Val
);

The method DeliverOrder modifies the value of the ALLOW_DELIVERY field. Besides, it sets the fields DATE_ALLOW_DELIVERY (date when the order shipment was allowed) and EMP_ALLOW_DELIVERY_ID (the ID of a user (web shop member) who sets this flag).

Parameters

Parameter | Description
ID | The order ID.
Val | New value of the order cancellation flag (Y/N).

Return Values

Returns the order ID on success, or false otherwise.

Example

<?
if (!CSaleOrder::DeliverOrder(23, "Y"))
   echo "Error updating order 23";
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleOrder::GetByID

array
CSaleOrder::GetByID(
  int ID
).

The method GetByID returns parameters of an order.

Parameters

Parameter | Description
ID | The order ID.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The order ID.
LID | The ID of the site from which an order originates.
PERSON_TYPE_ID | Payer type of the visitor who made The order (customer).
PAYED | Specifies whether the order is paid (Y/N).
DATE_PAYED | The date of the order payment.
EMP_PAYED_ID | The ID of the user (web shop member) who has set The PAYED flag.
CANCELED | Specifies whether the order is canceled (Y/N).
DATE_CANCELED | The date of the order cancellation.
EMP_CANCELED_ID | The ID of the user (web shop member) who has set the CANCELED flag.
REASON_CANCELED | Text description of the order cancellation reason.
STATUS_ID | The order status ID.
DATE_STATUS | The date the order status changed.
EMP_STATUS_ID | The ID of The user (web shop member) who has set The current STATUS_ID.
PRICE_DELIVERY | Cost of The order delivery.
ALLOW_DELIVERY | Specifies whether the order can be shipped (Y/N).
DATE_ALLOW_DELIVERY | The date when the order was subjected for shipment.
EMP_ALLOW_DELIVERY_ID | The ID of the user (web shop member) who has set the current ALLOW_DELIVERY status.
PRICE | Total order price.
CURRENCY | Currency of the order price.
DISCOUNT_VALUE | Total discount value.
USER_ID | The user ID of the customer.
PAY_SYSTEM_ID | Pay system to handle the payment.
DELIVERY_ID | The ID of a delivery service that will handle the order shipment.
DATE_INSERT | The date the order was created.
DATE_UPDATE | The date the order was last modified.
USER_DESCRIPTION | Customer's order description.
ADDITIONAL_INFO | Additional information on the order.
PS_STATUS | Specifies that the order has been successfully paid (Y/N). Available only for those pay systems which can automatically notify of their orders state.
PS_STATUS_CODE | Code of the pay system status (depends on the pay system).
PS_STATUS_DESCRIPTION | Description of the pay system order payment result.
PS_STATUS_MESSAGE | Message returned from the pay system.
PS_SUM | Amount of money which was actually paid via the pay system.
PS_CURRENCY | Payment currency.
PS_RESPONSE_DATE | The date when the pay system status was received.
COMMENTS | Auxiliary comments.
TAX_VALUE | Total amount of tax.
STAT_GID | The event parameter for use in the Statistics module.
DATE_INSERT_FORMAT | The date the order was created (in the current site format).

Example

<?
if (!($arOrder = CSaleOrder::GetByID($ORDER_ID)))
{
   echo "Cannot find order with ID=".$ORDER_ID;
}
else
{
   echo "<pre>";
   print_r($arOrder);
   echo "</pre>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleOrder::GetList

CDBResult
CSaleOrder::GetList(
  array arOrder = Array("ID"=>"DESC"),
  array arFilter = Array()
);

The method GetList retrieves an optionally sorted and filtered list of orders.

Parameters

Parameter Description
arOrder Associated array specifying how the returned order list is to be sorted. Each pair "key-value" is applied consequently. The keys are the sorting field names. The values are the sort order definitions.

The following keys are possible:
  • ID - the order ID;
  • LID - the ID of the site from which an order originates;
  • PAYED - specifies whether the order is paid (Y/N);
  • DATE_PAYED - the date of the order payment;
  • CANCELED - specifies whether the order is canceled (Y/N);
  • DATE_CANCELED - the date of the order cancellation;
  • STATUS_ID - the order status ID;
  • PAY_SYSTEM_ID - pay system to handle the payment;
  • DATE_STATUS - the date the order status changed;
  • PRICE - total order price;
  • CURRENCY - currency of the order price;
  • DATE_INSERT - the date the order was created;
  • DATE_UPDATE - the date the order was last modified.
Possible values:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the order parameter names, and values are the conditions to apply to parameter values.

The following keys are possible:
  • ID - the order ID;
  • DATE_INSERT - the date the order was created;
  • LID - the ID of the site from which an order originates;
  • PERSON_TYPE_ID - payer type of the visitor who made the order (customer);
  • PAYED - specifies whether the order is paid (Y/N);
  • PS_STATUS - specifies that the order has been successfully paid (Y/N). Available only for those pay systems which can automatically notify of their orders state;
  • CANCELED - specifies whether the order is canceled (Y/N);
  • STATUS_ID - the order status ID;
  • ALLOW_DELIVERY - specifies whether the order can be shipped (Y/N);
  • DATE_STATUS - the date the order status changed;
  • CURRENCY - currency of the order price;
  • PRICE - total order price;
  • USER_ID - the customer user ID;
  • PAY_SYSTEM_ID - pay system to handle the payment;
  • DELIVERY_ID - the ID of a delivery service that will handle the order shipment;
  • BUYER - the customer login, first and last names, e-mail address.
The filter conditions allow comparison operators. To use them, insert an operator in the beginning of the desired filter key. The following operators are supported: !, >=, >, <=, <.

The default operator is =.

Return Values

Returns a CDBResult instance containing array with the following keys.

Key | Description
ID | The order ID.
LID | The ID of the site from which an order originates.
PERSON_TYPE_ID | Payer type of the visitor who made The order (customer).
PAYED | Specifies whether the order is paid (Y/N).
DATE_PAYED | The date of the order payment.
EMP_PAYED_ID | The ID of the user (web shop member) who has set The PAYED flag.
CANCELED | Specifies whether the order is canceled (Y/N).
DATE_CANCELED | The date of the order cancellation.
EMP_CANCELED_ID | The ID of the user (web shop member) who has set the CANCELED flag.
REASON_CANCELED | Text description of the order cancellation reason.
STATUS_ID | The order status ID.
DATE_STATUS | The date the order status changed.
EMP_STATUS_ID | The ID of The user (web shop member) who has set The current STATUS_ID.
PRICE_DELIVERY | Cost of The order delivery.
ALLOW_DELIVERY | Specifies whether the order can be shipped (Y/N).
DATE_ALLOW_DELIVERY | The date when the order was subjected for shipment.
EMP_ALLOW_DELIVERY_ID | The ID of the user (web shop member) who has set the current ALLOW_DELIVERY status.
PRICE | Total order price.
CURRENCY | Currency of the order price.
DISCOUNT_VALUE | Total discount value.
USER_ID | The user ID of the customer.
PAY_SYSTEM_ID | Pay system to handle the payment.
DELIVERY_ID | The ID of a delivery service that will handle the order shipment.
DATE_INSERT | The date the order was created.
DATE_UPDATE | The date the order was last modified.
USER_DESCRIPTION | Customer's order description.
ADDITIONAL_INFO | Additional information on the order.
PS_STATUS | Specifies that the order has been successfully paid (Y/N). Available only for those pay systems which can automatically notify of their orders state.
PS_STATUS_CODE | Code of the pay system status (depends on the pay system).
PS_STATUS_DESCRIPTION | Description of the pay system order payment result.
PS_STATUS_MESSAGE | Message returned from the pay system.
PS_SUM | Amount of money which was actually paid via the pay system.
PS_CURRENCY | Payment currency.
PS_RESPONSE_DATE | The date when the pay system status was received.
COMMENTS | Auxiliary comments.
TAX_VALUE | Total amount of tax.
STAT_GID | The event parameter for use in the Statistics module.
DATE_INSERT_FORMAT | The date the order was created (in the current site format).
DATE_UPDATE_FORMAT | The date the order was last modified (in the current site format).
DATE_STATUS_FORMAT | The date the order status was last modified (in the current site format).
DATE_CANCELED_FORMAT | The date the order cancellation flag was last modified (in the current site format).
DATE_PAYED_FORMAT | The date the order payment flag was last modified (in the current site format).
PS_RESPONSE_DATE_FORMAT | The date the pay system status was last received (in the current site format).
DATE_ALLOW_DELIVERY_FORMAT | The date the order shipment flag was last received (in the current site format).

Example

<?
// Print dates of all orders the current user
// made within the month, sorted by the order date
$arFilter = Array(
    "USER_ID" => $USER->GetID(),
    ">=DATE_INSERT" =>
        date($DB->DateFormatToPHP(CSite::GetDateFormat("SHORT")),
             mktime(0, 0, 0, date("n"), 1, date("Y")))
   );

$db_sales = CSaleOrder::GetList(array("DATE_INSERT" => "ASC"),
                                $arFilter);
while ($ar_sales = $db_sales->Fetch())
{
   echo $ar_sales["DATE_INSERT_FORMAT"]."<br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


PayOrder

CSaleOrder::PayOrder

int
CSaleOrder::PayOrder(
  int ID,
  string Val
);

The method PayOrder changes the value of the PAYED field (sets the order as paid). Besides, it sets the fields DATE_PAYED (date when the order was paid) and EMP_PAYED_ID (the ID of a user (web shop member) who sets this flag).

Parameters

Parameter | Description
ID | The order ID.
Val | New value of the order payment flag (Y/N).

Return Values

Returns the order ID on success, or false otherwise.

Example

<?
if (!CSaleOrder::PayOrder($ID, "Y"))
{
   echo "Error updating order";
}
else
{
   // Register the purchase event
   if (CModule::IncludeModule("statistic"))
   {
      if (method_exists("CStatEvent", "AddByEvents"))
      {
         $arOrder_tmp = CSaleOrder::GetByID($ID);
         $orderPrice_tmp = DoubleVal($arOrder_tmp["PRICE"]);
         CStatEvent::AddByEvents("sale2order",
                                 "payment",
                                 $ID,
                                 "",
                                 $arOrder_tmp["STAT_GID"],
                                 $orderPrice_tmp,
                                 $arOrder_tmp["CURRENCY"]);
      }
   }
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


StatusOrder

CSaleOrder::StatusOrder

int
CSaleOrder::StatusOrder(
  int ID,
  string Val
);

The method StatusOrder changes the value of the STATUS_ID (order status). Besides, it sets the fields DATE_STATUS (date when the order was paid) and EMP_STATUS_ID (the ID of a user (web shop member) who sets this flag).

Parameters

Parameter | Description
ID | The order ID.
Val | New order status code.

Return Values

Returns the order ID on success, or false otherwise.

Example

<?
if (!CSaleOrder::StatusOrder($ID, "F"))
   echo "Error updating order status";
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleOrder::Update

int
CSaleOrder::Update(
  int ID,
  array arFields
);

The method Update replaces parameters of an order with the new ones.

Parameters

Parameter | Description
ID | The order ID.
arFields Associated array of the order new parameters whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • LID - the ID of the site from which an order originates;
  • PERSON_TYPE_ID - payer type of the visitor who made the order (customer);
  • PAYED - specifies whether the order is paid (Y/N);
  • DATE_PAYED - the date of the order payment;
  • EMP_PAYED_ID - the ID of the user (web shop member) who has set the PAYED flag;
  • CANCELED - specifies whether the order is canceled (Y/N);
  • DATE_CANCELED - the date of the order cancellation;
  • EMP_CANCELED_ID - the ID of the user (web shop member) who has set the CANCELED flag;
  • REASON_CANCELED - text description of the order cancellation reason;
  • STATUS_ID - the order status ID;
  • EMP_STATUS_ID - the ID of the user (web shop member) who has set the current STATUS_ID;
  • PRICE_DELIVERY - cost of the order delivery;
  • ALLOW_DELIVERY - specifies whether the order can be shipped (Y/N);
  • DATE_ALLOW_DELIVERY - the date when the order was subjected for shipment;
  • EMP_ALLOW_DELIVERY_ID - the ID of the user (web shop member) who has set the current ALLOW_DELIVERY status;
  • PRICE - total order price;
  • CURRENCY - currency of the order price;
  • DISCOUNT_VALUE - total discount value;
  • USER_ID - the user ID of the customer (must be specified);
  • PAY_SYSTEM_ID - pay system to handle the payment;
  • DELIVERY_ID - the ID of a delivery service that will handle the order shipment;
  • DATE_INSERT - the date the order was created;
  • USER_DESCRIPTION - customer's order description;
  • ADDITIONAL_INFO - additional information on the order;
  • COMMENTS - auxiliary comments;
  • TAX_VALUE - total amount of tax;
  • STAT_GID - the event parameter for use in the Statistics module;
  • PS_STATUS - specifies that the order has been successfully paid (Y/N). Available only for those pay systems which can automatically notify of their orders state;
  • PS_STATUS_CODE - code of the pay system status (depends on the pay system);
  • PS_STATUS_DESCRIPTION - description of the pay system order payment result;
  • PS_STATUS_MESSAGE - message returned from the pay system;
  • PS_SUM - amount of money which was actually paid via the pay system;
  • PS_CURRENCY - payment currency;
  • PS_RESPONSE_DATE - the date when the pay system status was received.

Return Values

Returns the ID of the modified order on success, or false otherwise.

Example

<?
$arOrder = CSaleOrder::GetByID($ID);
if ($arOrder)
{
    $arFields = array(
       "PAYED" => "Y",
       "DATE_PAYED" =>
           Date(CDatabase::DateFormatToPHP(CLang::GetDateFormat("FULL", LANG))),
       "USER_ID" => $arOrder["USER_ID"],
       "EMP_PAYED_ID" => $USER->GetID()
    );
    CSaleOrder::Update($ID, $arFields);
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


CSaleOrderProps

The CSaleOrderProps class is used with order properties which can be controls as well.

Methods

Method | Description
Add | Creates a new order property based on the supplied parameters.
GetList | Returns an optionally sorted and filtered list of order properties.
GetByID | Retrieves parameters of the specified property.
Update | Replaces values of the specified property with the new ones.
Delete | Deletes a specified property.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleOrderProps::Add

int
CSaleOrderProps::Add(
  array arFields
);

The method Add creates a new order property based on the supplied parameters.

Parameters

Parameter Description
arFields Associated array of an order parameters whose keys are the order parameter names, and values are the parameter values. The following values are possible:
  • PERSON_TYPE_ID - the payer type ID;
  • NAME - the property name (the payer type is dependent on a site while the latter depends on the language used. This implies that the property name should be specified in the corresponding language);
  • TYPE - property type:
    • CHECKBOX - check box button;
    • TEXT - single line text;
    • SELECT - drop-down list;
    • MULTISELECT - multiple selection list;
    • TEXTAREA - multiple line text field;
    • LOCATION - location;
    • RADIO - radio button;
  • REQUIED - specifies the field is required (Y/N);
  • DEFAULT_VALUE - the default value;
  • SORT - sort weight;
  • USER_PROPS - specifies the field is included in the customer profile (Y/N);
  • IS_LOCATION - specifies the field value is to be used as a customer location when calculating the delivery price (only for LOCATION fields) (Y/N);
  • PROPS_GROUP_ID - the property group ID;
  • SIZE1 - field width;
  • SIZE2 - field height;
  • DESCRIPTION - field description;
  • IS_EMAIL - denotes the field value should be used as a customer's e-mail address (Y/N);
  • IS_PROFILE_NAME - denotes the field value should be used as a customer's profile name (Y/N);
  • IS_PAYER - denotes the field value should be used as a payer name (Y/N);
  • IS_LOCATION4TAX - specifies the use of the property value as a customer location for the tax calculations (only for LOCATION fields) (Y/N);
  • CODE - property mnemonic code.

Return Values

The ID of the added order property.

Example

<?
$arFields = array(
    "PERSON_TYPE_ID" => 2,
    "NAME" => "Includes",
    "TYPE" => "RADIO",
    "REQUIED" => "Y",
    "DEFAULT_VALUE" => "F",
    "SORT" => 100,
    "CODE" => "COMPLECT",
    "USER_PROPS" => "N",
    "IS_LOCATION" => "N",
    "IS_LOCATION4TAX" => "N",
    "PROPS_GROUP_ID" => 1,
    "SIZE1" => 0,
    "SIZE2" => 0,
    "DESCRIPTION" => "",
    "IS_EMAIL" => "N",
    "IS_PROFILE_NAME" => "N",
    "IS_PAYER" => "N"
);

// If the property ID is set, change the property, otherwise add a new one
if ($ID>0)
{
    if (!CSaleOrderProps::Update($ID, $arFields))
    {
        echo "Error modifying property";
    }
    else
    {
        // Update the property value mnemonic code (redundant data for speed-up)
        $db_order_props_tmp = CSaleOrderPropsValue::GetList(($b="NAME"),
                                                            ($o="ASC"),
                                                            Array("ORDER_PROPS_ID"=>$ID));
        while ($ar_order_props_tmp = $db_order_props_tmp->Fetch())
        {
            CSaleOrderPropsValue::Update($ar_order_props_tmp["ID"],
                                         array("CODE" => "COMPLECT"));
        }
    }
}
else
{
    $ID = CSaleOrderProps::Add($arFields);
    if ($ID<=0)
        echo "Error adding property";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleOrderProps::Delete

bool
CSaleOrderProps::Delete(
  int ID
);

The method Delete deletes a specified property. Currently existing values of this property are unbound from the deleted property. All dependencies currently existing in a customer profile are removed as well.

Parameters

Parameter | Description
ID | The ID of the property to be deleted.

Return Values

Returns true on success or false otherwise.

Example

<?
if (!CSaleOrderProps::Delete(12))
   echo "error deleting property";
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleOrderProps::GetByID

array
CSaleOrderProps::GetByID(
  int ID
);

The method GetByID retrieves parameters of the specified property.

Parameters

Parameter | Description
ID | The ID of the property whose properties are to be retrieved.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The property ID.
PERSON_TYPE_ID | Payer type.
NAME | The property name.
TYPE Property type:
  • CHECKBOX - check box button;
  • TEXT - single line text;
  • SELECT - drop-down list;
  • MULTISELECT - multiple selection list;
  • TEXTAREA - multiple line text field;
  • LOCATION - location;
  • RADIO - radio button;
REQUIED | Specifies the field is required (Y/N).
DEFAULT_VALUE | Default value.
SORT | Sort weight.
USER_PROPS | Specifies the field is included in the customer profile (Y/N)
IS_LOCATION | Specifies the field value is to be used as a customer location when calculating the delivery price (only for LOCATION fields) (Y/N).
PROPS_GROUP_ID | The property group ID.
SIZE1 | Field width.
SIZE2 | Field height.
DESCRIPTION | Property description.
IS_EMAIL | Denotes the field value should be used as a customer's e-mail address (Y/N).
IS_PROFILE_NAME | Denotes the field value should be used as a customer's profile name (Y/N).
IS_PAYER | Denotes the field value should be used as a payer name (Y/N).
IS_LOCATION4TAX | Specifies the use of the property value as a customer location for the tax calculations (only for LOCATION fields) (Y/N).
CODE | Property mnemonic code.

Example

<?
if ($arOrderProps = CSaleOrderProps::GetByID($ID))
{
   echo "<pre>";
   print_r($arOrderProps);
   echo "</pre>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleOrderProps::GetList

CDBResult
CSaleOrderProps::GetList(
  string &by,
  string &order,
  array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of order properties.

Parameters

Parameter Description
by Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • SORT - sort weight (default);
  • NAME - the property name;
  • ID - the property ID;
  • PERSON_TYPE_ID - payer type;
  • TYPE - property type;
  • REQUIED - specifies the field is required (Y/N);
  • USER_PROPS - specifies the property is included in the customer profile (Y/N);
  • CODE - mnemonic property code;
  • PROPS_GROUP_ID - the property group ID.
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the discount parameter names, and values are the conditions.

The following keys are possible:
  • PERSON_TYPE_ID - payer type;
  • ID - the property ID;
  • TYPE - property type;
  • CODE - mnemonic property code;
  • REQUIED - specifies the field is required (Y/N);
  • USER_PROPS - specifies the property is included in the customer profile (Y/N);
  • IS_LOCATION - specifies the field value is to be used as a customer location when calculating the delivery price (only for LOCATION fields) (Y/N);
  • IS_LOCATION4TAX - specifies the use of the property value as a customer location for the tax calculations (only for LOCATION fields) (Y/N);
  • IS_PAYER - denotes the field value should be used as a payer name (Y/N);
  • IS_EMAIL - denotes the field value should be used as a customer's e-mail address (Y/N);
  • IS_PROFILE_NAME - denotes the field value should be used as a customer's profile name (Y/N);
  • PROPS_GROUP_ID - the property group ID.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The property ID.
PERSON_TYPE_ID | Payer type.
NAME | The property name.
TYPE Property type:
  • CHECKBOX - check box button;
  • TEXT - single line text;
  • SELECT - drop-down list;
  • MULTISELECT - multiple selection list;
  • TEXTAREA - multiple line text field;
  • LOCATION - location;
  • RADIO - radio button;
REQUIED | Specifies the field is required (Y/N).
DEFAULT_VALUE | Default value.
SORT | Sort weight.
USER_PROPS | Specifies the field is included in the customer profile (Y/N)
IS_LOCATION | Specifies the field value is to be used as a customer location when calculating the delivery price (only for LOCATION fields) (Y/N).
PROPS_GROUP_ID | The property group ID.
SIZE1 | Field width.
SIZE2 | Field height.
DESCRIPTION | Property description.
IS_EMAIL | Denotes the field value should be used as a customer's e-mail address (Y/N).
IS_PROFILE_NAME | Denotes the field value should be used as a customer's profile name (Y/N).
IS_PAYER | Denotes the field value should be used as a payer name (Y/N).
IS_LOCATION4TAX | Specifies the use of the property value as a customer location for the tax calculations (only for LOCATION fields) (Y/N).
CODE | Property mnemonic code.

Example

<?
// Display a form for inputting the order properties for prop. group with ID==5
// included in the profile
// for payer type with ID==2
$db_props = CSaleOrderProps::GetList(($by="SORT"),
                                     ($order="ASC"),
                                     Array("PERSON_TYPE_ID"=>2,
                                           "PROPS_GROUP_ID"=>5,
                                           "USER_PROPS"=>"Y"));
if ($props = $db_props->Fetch())
{
    echo "Specify the order parameters:<br>";
    do
    {
        echo $props["NAME"];
        if ($props["REQUIED"]=="Y" ||
            $props["IS_EMAIL"]=="Y" ||
            $props["IS_PROFILE_NAME"]=="Y" ||
            $props["IS_LOCATION"]=="Y" ||
            $props["IS_LOCATION4TAX"]=="Y" ||
            $props["IS_PAYER"]=="Y")
        {
            echo "*";
        }
        echo ": ";

        if ($props["TYPE"]=="CHECKBOX")
        {
            echo '<input type="checkbox"
                   class="inputcheckbox"
                   name="ORDER_PROP_'.$props["ID"].'"
                   value="Y"'.(($props["DEFAULT_VALUE"]=="Y")?"
                   checked":"").'>';
        }
        elseif ($props["TYPE"]=="TEXT")
        {
            echo '<input type="text"
                   class="inputtext"
                   size="'.((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:30).'"
                   maxlength="250"
                   value="'.htmlspecialchars($props["DEFAULT_VALUE"]).'"
                   name="ORDER_PROP_'.$props["ID"].'">";
        }
        elseif ($props["TYPE"]=="SELECT")
        {
            echo '<select
                   name="ORDER_PROP_'.$props["ID"].'"
                   size="'.((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:1).'">';
            $db_vars = CSaleOrderPropsVariant::GetList(($by="SORT"),
                                                       ($order="ASC"),
                                                       Array("ORDER_PROPS_ID" =>
                                                                   $props["ID"]));
            while ($vars = $db_vars->Fetch())
            {
                echo '<option
                       value="'.$vars["VALUE"].'"'.
                       (($vars["VALUE"]==$props["DEFAULT_VALUE"])?" selected":"").
                       '>'.htmlspecialchars($vars["NAME"]).'</option>';
            }
            echo '</select>';
        }
        elseif ($props["TYPE"]=="MULTISELECT")
        {
            echo '<select
                   multiple
                   name="ORDER_PROP_'.
                   $props["ID"].'[]" size="'.
                   ((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:5).'">';
            $arDefVal = Split(",", $props["DEFAULT_VALUE"]);
            for ($i = 0; $i<count($arDefVal); $i++)
                $arDefVal[$i] = Trim($arDefVal[$i]);

            $db_vars = CSaleOrderPropsVariant::GetList(($by="SORT"),
                                                       ($order="ASC"),
                                                       Array("ORDER_PROPS_ID" =>
                                                                    $props["ID"]));
            while ($vars = $db_vars->Fetch())
            {
                echo '<option
                       value="'.$vars["VALUE"].'"'.
                       (in_array($vars["VALUE"], $arDefVal)?" selected":"").'>'.
                       htmlspecialchars($vars["NAME"]).'</option>';
            }
            echo '</select>';
        }
        elseif ($props["TYPE"]=="TEXTAREA")
        {
            echo '<textarea rows="'.
                   ((IntVal($props["SIZE2"])>0)?$props["SIZE2"]:4).
                   '" cols="'.((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:40).
                   '" name="ORDER_PROP_'.$props["ID"].'">'.
                   htmlspecialchars($props["DEFAULT_VALUE"]).'</textarea>';
        }
        elseif ($props["TYPE"]=="LOCATION")
        {
            echo '<select
                   name="ORDER_PROP_'.$props["ID"].
                   '" size="'.((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:1).'">';
            $db_vars = CSaleLocation::GetList(Array("SORT"=>"ASC",
                                                    "COUNTRY_NAME_LANG"=>"ASC",
                                                    "CITY_NAME_LANG"=>"ASC"),
                                                    array(), LANGUAGE_ID);
            while ($vars = $db_vars->Fetch())
            {
                echo '<option
                       value="'.$vars["ID"].'"".
                       ((IntVal($vars["ID"])==IntVal($props["DEFAULT_VALUE"]))?" selected":"").
                       '>'.htmlspecialchars($vars["COUNTRY_NAME"].
                       " - ".$vars["CITY_NAME"]).'</option>';
            }
            echo '</select>';
        }
        elseif ($props["TYPE"]=="RADIO")
        {
            $db_vars = CSaleOrderPropsVariant::GetList(($by="SORT"),
                                                       ($order="ASC"),
                                                       Array("ORDER_PROPS_ID"=>
                                                                    $props["ID"]));
            while ($vars = $db_vars->Fetch())
            {
                echo '<input
                       type="radio"
                       name="ORDER_PROP_'.$props["ID"].'" value="'.
                       $vars["VALUE"].'"'.
                       (($vars["VALUE"]==$props["DEFAULT_VALUE"])?" checked":"").
                       '>'.htmlspecialchars($vars["NAME"]).'<br>';
            }
        }

        if (strlen($props["DESCRIPTION"])>0)
        {
            echo "<br><small>".$props["DESCRIPTION"]."</small>";
        }

        echo "<br>";
    }
    while ($props = $db_props->Fetch());
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleOrderProps::Update

int
CSaleOrderProps::Update(
  int ID,
  array arFields
);

The method Update replaces values of the specified property with the new ones.

Parameters

Parameter | Description
ID | The ID of the property whose values are to be updated.
arFields Associated array of the order new parameters whose keys are the order parameter names, and values are the parameter values. The following values are possible:
  • PERSON_TYPE_ID - the payer type ID;
  • NAME - the property name (the payer type is dependent on a site while the latter depends on the language used. This implies that the property name should be specified in the corresponding language);
  • TYPE - property type:
    • CHECKBOX - check box button;
    • TEXT - single line text;
    • SELECT - drop-down list;
    • MULTISELECT - multiple selection list;
    • TEXTAREA - multiple line text field;
    • LOCATION - location;
    • RADIO - radio button;
  • REQUIED - specifies the field is required (Y/N);
  • DEFAULT_VALUE - the default value;
  • SORT - sort weight;
  • USER_PROPS - specifies the field is included in the customer profile (Y/N);
  • IS_LOCATION - specifies the field value is to be used as a customer location when calculating the delivery price (only for LOCATION fields) (Y/N);
  • PROPS_GROUP_ID - the property group ID;
  • SIZE1 - field width;
  • SIZE2 - field height;
  • DESCRIPTION - field description;
  • IS_EMAIL - denotes the field value should be used as a customer's e-mail address (Y/N);
  • IS_PROFILE_NAME - denotes the field value should be used as a customer's profile name (Y/N);
  • IS_PAYER - denotes the field value should be used as a payer name (Y/N);
  • IS_LOCATION4TAX - specifies the use of the property value as a customer location for the tax calculations (only for LOCATION fields) (Y/N);
  • CODE - property mnemonic code.

Return Values

The ID of the modified order property.

Example

<?
$arFields = array(
   "PERSON_TYPE_ID" => 2,
   "NAME" => "Includes",
   "TYPE" => "RADIO",
   "REQUIED" => "Y",
   "DEFAULT_VALUE" => "F",
   "SORT" => 100,
   "CODE" => "COMPLECT",
   "USER_PROPS" => "N",
   "IS_LOCATION" => "N",
   "IS_LOCATION4TAX" => "N",
   "PROPS_GROUP_ID" => 1,
   "SIZE1" => 0,
   "SIZE2" => 0,
   "DESCRIPTION" => "",
   "IS_EMAIL" => "N",
   "IS_PROFILE_NAME" => "N",
   "IS_PAYER" => "N"
);

// If the prop ID is set, update it; otherwise create new
if ($ID>0)
{
   if (!CSaleOrderProps::Update($ID, $arFields))
   {
      echo "Error updating property";
   }
   else
   {
      // Update mnemonic code (redundant data for speed-up)
      $db_order_props_tmp =
        CSaleOrderPropsValue::GetList(($b="NAME"),
                                      ($o="ASC"),
                                      Array("ORDER_PROPS_ID"=>$ID));
      while ($ar_order_props_tmp = $db_order_props_tmp->Fetch())
      {
         CSaleOrderPropsValue::Update($ar_order_props_tmp["ID"],
                                      array("CODE" => "COMPLECT"));
      }
   }
}
else
{
   $ID = CSaleOrderProps::Add($arFields);
   if ($ID<=0)
      echo "error updating property";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


CSaleOrderPropsGroup

The CSaleOrderPropsGroup class encapsulates order properties in groups for proper handling.

Methods

Method | Description
GetList | Returns an optionally sorted and filtered list of an order property group.
GetByID | Returns parameters of a specified property group.
Update | Replaces values of the specified property group with the new ones.
Add | Creates new order property group.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleOrderPropsGroup::Add

int
CSaleOrderPropsGroup::Add(
  array arFields
);

The method Add adds a new order property group. Groups are used solely for arranging (grouping) properties.

Parameters

Parameter Description
arFields Associated array of an order property group parameters whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • PERSON_TYPE_ID - the payer type ID;
  • NAME - group name (the payer type is dependent on a site while the latter depends on the language used. This implies that the name should be specified in the corresponding language);
  • SORT - sort weight.

Return Values

Returns the new group ID or False otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleOrderPropsGroup::Delete

bool
CSaleOrderPropsGroup::Delete(
  int ID
);

The method Delete deletes a specified property group. The method also deletes all properties of this group and other auxiliary data.

Values of properties of this group which are bound to any orders become unbound from the deleted properties. If you want to delete a group only, first unlink all properties from it.

Parameters

Parameter | Description
ID | The ID of the property group to be deleted.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleOrderPropsGroup::GetByID

array
CSaleOrderPropsGroup::GetByID(
  int ID
);

The method GetByID returns parameters of a specified property group.

Parameters

Parameter | Description
ID | The ID of the property group whose parameters should be returned..

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The property group ID.
PERSON_TYPE_ID | The payer type ID.
NAME | Group name.
SORT | Sort weight.

Example

<?
if ($arPropsGroup = CSaleOrderPropsGroup::GetByID(3))
   echo $arPropsGroup["NAME"];
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleOrderPropsGroup::GetList

CDBResult
CSaleOrderPropsGroup::GetList(
  string &by,
  string &order,
  array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of order property groups.

Parameters

Parameter Description
by Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • SORT - sort weight (default);
  • NAME - name;
  • PERSON_TYPE_ID - the payer type ID.
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the parameter names, and values are the conditions.

The following keys are possible:
  • PERSON_TYPE_ID - the payer type ID;
  • ID - the property group ID.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The property group ID.
PERSON_TYPE_ID | The payer type ID.
NAME | Group name.
SORT | Sort weight.

Example

<?
// Display all groups for payer $PERSON_TYPE
$db_propsGroup = CSaleOrderPropsGroup::GetList(($by="SORT"),
                                               ($order="ASC"),
                                               Array("PERSON_TYPE_ID"=>$PERSON_TYPE));
while ($propsGroup = $db_propsGroup->Fetch())
{
   echo $propsGroup["NAME"]."<br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleOrderPropsGroup::Update

int
CSaleOrderPropsGroup::Update(
  int ID,
  array arFields
);

The method Update replaces values of the specified property group with the new ones.

Parameters

Parameter | Description
ID | The property group ID whose values are to be modified..
arFields Associated array of an order property group parameters whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • PERSON_TYPE_ID - the payer type ID;
  • NAME - group name (the payer type is dependent on a site while the latter depends on the language used. This implies that the name should be specified in the corresponding language);
  • SORT - sort weight.

Return Values

Returns the ID of an updated group or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleOrderPropsValue

The CSaleOrderPropsValue class helps handle parameters (compound values) of an order property values.

Methods

Method | Description
Add | Adds a new property value to an order given the specified parameters.
GetList | Returns an optionally sorted and filtered list of order property values.
GetByID | Returns parameters of a specified order property value.
Update | Replaces the values of the specified property value with the new ones.
GetOrderProps | Returns a set of property values of a specified order. In addition, some bound values are returned as well.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleOrderPropsValue::Add

int
CSaleOrderPropsValue::Add(
  array arFields
);

The method Add adds a new property value to an order given the specified parameters.

Parameters

Parameter Description
arFields Associated array of a property value parameters whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • ORDER_ID - the order ID (required);
  • ORDER_PROPS_ID - the property ID;
  • NAME - the property name;
  • VALUE - property value (required);
  • CODE - property mnemonic code.

Return Values

Returns the ID of an added property value on success or false otherwise.

Example

<?
$arFields = array(
   "ORDER_ID" => 124859,
   "ORDER_PROPS_ID" => 15,
   "NAME" => "Delivery address",
   "CODE" => "ADDRESS",
   "VALUE" => "Madison Ave 15"
);

CSaleOrderPropsValue::Add($arFields);
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleOrderPropsValue::GetByID

array
CSaleOrderPropsValue::GetByID(
 int ID
);

The method GetByID returns parameters of a specified order property value.

Parameters

Parameter | Description
ID | The order property value ID whose parameters are to be retrieved.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The order property value ID.
ORDER_ID | The order ID.
ORDER_PROPS_ID | The order property ID.
NAME | The order property name.
VALUE | Order property value.
CODE | Property mnemonic code.

© 2001-2005 Bitrix Bitrix Site Manager
>


GetList

CSaleOrderPropsValue::GetList

CDBResult
CSaleOrderPropsValue::GetList(
 string &by,
 string &order,
 array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of order property values.

Parameters

Parameter Description
by Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • VALUE - value (default);
  • ORDER_ID - the order ID;
  • NAME - property name;
  • CODE - property mnemonic code.
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the parameter names, and values are the conditions.

The following keys are possible:
  • ORDER_ID - the order ID;
  • ORDER_PROPS_ID - the order property ID;
  • CODE - order property mnemonic code.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The order property value ID.
ORDER_ID | The order ID.
ORDER_PROPS_ID | The order property ID.
NAME | The order property name.
VALUE | Order property value.
CODE | Property mnemonic code.

Example

<?
// Obtain the customer name
// (value provided in the $ORDER_ID
//  order property field with IS_PAYER flag set)
$PAYER_NAME = "";
$db_order = CSaleOrder::GetList(Array("DATE_UPDATE"=>"DESC"),
                                Array("ID" => $ORDER_ID));
if ($arOrder = $db_order->Fetch())
{
   $db_props = CSaleOrderProps::GetList(($by="SORT"),
                                        ($order="ASC"),
                                        Array("PERSON_TYPE_ID" =>
                                                  $arOrder["PERSON_TYPE_ID"],
                                              "IS_PAYER"=>"Y"));
   if ($arProps = $db_props->Fetch())
   {
      $db_vals = CSaleOrderPropsValue::GetList(($by="SORT"),
                                               ($order="ASC"),
                                               Array("ORDER_ID" => $ORDER_ID,
                                                     "ORDER_PROPS_ID" =>
                                                         $arProps["ID"]));
      if ($arVals = $db_vals->Fetch())
          $PAYER_NAME = $arVals["VALUE"];
   }
}
echo $PAYER_NAME;
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetOrderProps

CSaleOrderPropsValue::GetOrderProps

CDBResult
CSaleOrderPropsValue::GetOrderProps(
 int ORDER_ID
);

The method GetOrderProps returns a set of property values of a specified order. In addition, some bound values are returned as well.

Parameters

Parameter | Description
ORDER_ID | The order ID.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the keys describing the order property values. These and some additional keys are summarized in the table below.

The returned set is sorted consequently by: the order property group sort weight; the order property group name; order property sort index; the order property name.

Key | Description
ID | The order property value ID.
ORDER_ID | The order ID.
ORDER_PROPS_ID | The order property ID.
NAME | The order property name.
VALUE | Order property value.
CODE | Property mnemonic code.
PROPERTY_NAME | The order property name.
TYPE | Order property type.
PROPS_GROUP_ID | The order property group ID.
GROUP_NAME | The order property group name.
IS_LOCATION | Specifies the field value is to be used as a customer location when calculating the delivery price (Y/N).
IS_EMAIL | Denotes the field value should be used as a customer's e-mail address (Y/N).
IS_PROFILE_NAME | Denotes the field value should be used as a customer's profile name (Y/N).
IS_PAYER | Denotes the field value should be used as a payer name (Y/N).

Example

<?
// Display all properties of an order $ID; group by property groups
$db_props = CSaleOrderPropsValue::GetOrderProps($ID);
$iGroup = -1;
while ($arProps = $db_props->Fetch())
{
   if ($iGroup!=IntVal($arProps["PROPS_GROUP_ID"]))
   {
      echo "<b>".$arProps["GROUP_NAME"]."</b><br>";
      $iGroup = IntVal($arProps["PROPS_GROUP_ID"]);
   }

   echo $arProps["NAME"].": ";

   if ($arProps["TYPE"]=="CHECKBOX")
   {
      if ($arProps["VALUE"]=="Y")
         echo "Yes";
      else
         echo "No";
   }
   elseif ($arProps["TYPE"]=="TEXT" || $arProps["TYPE"]=="TEXTAREA")
   {
      echo htmlspecialchars($arProps["VALUE"]);
   }
   elseif ($arProps["TYPE"]=="SELECT" || $arProps["TYPE"]=="RADIO")
   {
      $arVal =
         CSaleOrderPropsVariant::GetByValue($arProps["ORDER_PROPS_ID"],
                                            $arProps["VALUE"]);
      echo htmlspecialchars($arVal["NAME"]);
   }
   elseif ($arProps["TYPE"]=="MULTISELECT")
   {
      $curVal = split(",", $arProps["VALUE"]);
      for ($i = 0; $i<count($curVal); $i++)
      {
         $arVal =
            CSaleOrderPropsVariant::GetByValue($arProps["ORDER_PROPS_ID"],
                                               $curVal[$i]);
         if ($i>0) echo ", ";
         echo htmlspecialchars($arVal["NAME"]);
      }
   }
   elseif ($arProps["TYPE"]=="LOCATION")
   {
      $arVal = CSaleLocation::GetByID($arProps["VALUE"], LANGUAGE_ID);
      echo htmlspecialchars($arVal["COUNTRY_NAME"]." - ".
           $arVal["CITY_NAME"]);
   }

   echo "<br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


Update

CSaleOrderPropsValue::Update

int
CSaleOrderPropsValue::Update(
 int ID,
 array arFields
);

The method Update replaces the values of the specified property value with the new ones.

Parameters

Parameter | Description
ID | The order property value ID.
arFields Associated array of the new property value parameters whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • ORDER_ID - the order ID (required);
  • ORDER_PROPS_ID - the property ID;
  • NAME - the property name;
  • VALUE - property value (required);
  • CODE - property mnemonic code.

Return Values

Returns the ID of an updated value or false otherwise.

Example

<?
CSaleOrderPropsValue::Update(8, array("CODE"=>"ADDRESS"));
?>
© 2001-2005 Bitrix Bitrix Site Manager


CSaleOrderPropsVariant

The CSaleOrderPropsVariant class is used to manage variants of order property values.

Methods

Method | Description
GetList | Returns an optionally sorted and filtered list of order property value variants.
GetByValue | Retrieves parameters of the specified order property variant by the specified order property ID and a value.
GetByID | Returns parameters of the specified order property variant.
Update | Replaces the variant parameters with the new ones from the supplied array.
Delete | Deletes a specified variant.
DeleteAll | Deletes all variants of the specified order property.
Add | Creates a new variant (choice) that can be used to select a value with controls like radio button group (RADIO) and list (SELECT, MULTISELECT).
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleOrderPropsVariant::Add

int
CSaleOrderPropsVariant::Add(
  array arFields
);

The method Add creates a new variant (choice) that can be used to select a value with controls like radio button group (RADIO) and list (SELECT, MULTISELECT).

Parameters

Parameter Description
arFields Associated array containing parameters of the new order property value whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • ORDER_PROPS_ID - the order property ID;
  • NAME - variant name;
  • VALUE - variant value;
  • SORT - sort weight for positioning in lists;
  • DESCRIPTION - variant description.

Return Values

Returns the ID of the new variant on success or false otherwise.

Example

<?
$arFieldsV = array(
   "ORDER_PROPS_ID" => 12,
   "VALUE" => "F",
   "NAME" => "Full package",
   "SORT" => 100,
   "DESCRIPTION" => "Order is not shipped until it is complete."
);

if (!CSaleOrderPropsVariant::Add($arFieldsV))
   echo "error adding variant";
?>
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleOrderPropsVariant::Delete

bool
CSaleOrderPropsVariant::Delete(
  int ID
);

The method Delete deletes a specified variant.

Parameters

Parameter | Description
ID | The ID of the variant to be deleted.

Return Values

Returns true on success or false otherwise.

Example

<?
CSaleOrderPropsVariant::Delete(12);
?>
© 2001-2005 Bitrix Bitrix Site Manager


DeleteAll

CSaleOrderPropsVariant::DeleteAll

bool
CSaleOrderPropsVariant::DeleteAll(
  int ID
);

The method DeleteAll deletes all variants of the specified order property.

Parameters

Parameter | Description
ID | The ID of the order property to be deleted.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleOrderPropsVariant::GetByID

array
CSaleOrderPropsVariant::GetByID(
 int ID
);

The method GetByID returns parameters of the specified order property variant.

Parameters

Parameter | Description
ID | The ID of the order property whose information is to be retrieved.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The ID of the order property variant.
ORDER_PROPS_ID | The order property ID.
NAME | Variant name.
VALUE | Variant value.
SORT | Variant sort weight.
DESCRIPTION | Variant description as it is displayed to a visitor.

© 2001-2005 Bitrix Bitrix Site Manager


GetByValue

CSaleOrderPropsVariant::GetByValue

array
CSaleOrderPropsVariant::GetByValue(
  int PropID,
  string Value
);

The method GetByValue retrieves parameters of the specified order property variant by the specified order property ID and a value.

Parameters

Parameter | Description
PropID | The order property ID.
Value | Property value.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The ID of the order property variant.
ORDER_PROPS_ID | The order property ID.
NAME | Variant name.
VALUE | Variant value.
SORT | Variant sort weight.
DESCRIPTION | Variant description as it is displayed to a visitor.

Example

<?
$arVal = CSaleOrderPropsVariant::GetByValue(12, "F");
echo $arVal["NAME"];
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleOrderPropsVariant::GetList

CDBResult
CSaleOrderPropsVariant::GetList(
  string &by,
  string &order,
  array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of order property value variants.

Parameters

Parameter Description
by Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • SORT - sort weight (default);
  • ORDER_PROPS_ID - the order property ID;
  • NAME - value name.
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the parameter names, and values are the conditions.

The following keys are possible:
  • ORDER_PROPS_ID - the order property ID;
  • VALUE - variant value;
  • ID - the variant ID.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The ID of the order property variant.
ORDER_PROPS_ID | The order property ID.
NAME | Variant name.
VALUE | Variant value.
SORT | Variant sort weight.
DESCRIPTION | Variant description as it is displayed to a visitor.

Example

<?
// Display a form for inputting order properties for property group with ID=5
// which are in the customer profile. Use the payer type ID=2

$db_props = CSaleOrderProps::GetList(($by="SORT"),
                                     ($order="ASC"),
                                     Array("PERSON_TYPE_ID"=>2,
                                           "PROPS_GROUP_ID"=>5,
                                           "USER_PROPS"=>"Y"));
if ($props = $db_props->Fetch())
{
   echo "Please fill in the order properties:<br>";
   do
   {
      echo $props["NAME"];
      if ($props["REQUIED"]=="Y" ||
          $props["IS_EMAIL"]=="Y" ||
          $props["IS_PROFILE_NAME"]=="Y" ||
          $props["IS_LOCATION"]=="Y" ||
          $props["IS_LOCATION4TAX"]=="Y" ||
          $props["IS_PAYER"]=="Y")
      {
         echo "*";
      }
      echo ": ";

      if ($props["TYPE"]=="CHECKBOX")
      {
         echo '<input type="checkbox"
                class="inputcheckbox"
                name="ORDER_PROP_'.$props["ID"].
              '" value="Y"'.
                (($props["DEFAULT_VALUE"]=="Y")?" checked":"").'>';
      }
      elseif ($props["TYPE"]=="TEXT")
      {
         echo '<input
                type="text"
                class="inputtext"
                size="'.((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:30).
              '" maxlength="250" value="'.
                htmlspecialchars($props["DEFAULT_VALUE"]).
                '" name="ORDER_PROP_'.$props["ID"].'">";
      }
      elseif ($props["TYPE"]=="SELECT")
      {
         echo '<select
                name="ORDER_PROP_'.$props["ID"].
              '" size="'.
                ((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:1).'">';

         $db_vars = CSaleOrderPropsVariant::GetList(($by="SORT"),
                                                    ($order="ASC"),
                                                    Array("ORDER_PROPS_ID"=>$props["ID"]));
         while ($vars = $db_vars->Fetch())
         {
            echo '<option
                   value="'.$vars["VALUE"].'"'.
                   (($vars["VALUE"]==$props["DEFAULT_VALUE"])?" selected":"").
                   '>'.htmlspecialchars($vars["NAME"]).'</option>';
         }
         echo '</select>';
      }
      elseif ($props["TYPE"]=="MULTISELECT")
      {
         echo '<select
                multiple name="ORDER_PROP_'.
                $props["ID"].'[]" size="'.
                ((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:5).'">';

         $arDefVal = Split(",", $props["DEFAULT_VALUE"]);
         for ($i = 0; $i<count($arDefVal); $i++)
            $arDefVal[$i] = Trim($arDefVal[$i]);

         $db_vars = CSaleOrderPropsVariant::GetList(($by="SORT"),
                                                    ($order="ASC"),
                                                    Array("ORDER_PROPS_ID"=>$props["ID"]));
         while ($vars = $db_vars->Fetch())
         {
            echo '<option
                   value="'.$vars["VALUE"].'"'.
                   (in_array($vars["VALUE"], $arDefVal)?" selected":"").
                   '>'.htmlspecialchars($vars["NAME"]).'</option>';
         }
         echo '</select>';
      }
      elseif ($props["TYPE"]=="TEXTAREA")
      {
         echo '<textarea
                rows="'.((IntVal($props["SIZE2"])>0)?$props["SIZE2"]:4).
                '" cols="'.((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:40).
                '" name="ORDER_PROP_'.$props["ID"].'">'.
                htmlspecialchars($props["DEFAULT_VALUE"]).'</textarea>';
      }
      elseif ($props["TYPE"]=="LOCATION")
      {
         echo '<select
                name="ORDER_PROP_'.$props["ID"].'" size="'.
                ((IntVal($props["SIZE1"])>0)?$props["SIZE1"]:1).'">';
         $db_vars = CSaleLocation::GetList(Array("SORT"=>"ASC",
                                                 "COUNTRY_NAME_LANG"=>"ASC",
                                                 "CITY_NAME_LANG"=>"ASC"),
                                           array(), LANGUAGE_ID);
         while ($vars = $db_vars->Fetch())
         {
            echo '<option
                   value="'.$vars["ID"].'"".
                   ((IntVal($vars["ID"])==
                       IntVal($props["DEFAULT_VALUE"]))?" selected":"").
                   '>'.htmlspecialchars($vars["COUNTRY_NAME"].
                   " - ".$vars["CITY_NAME"]).'</option>';
         }
         echo '</select>';
      }
      elseif ($props["TYPE"]=="RADIO")
      {
         $db_vars = CSaleOrderPropsVariant::GetList(($by="SORT"),
                                                    ($order="ASC"),
                                                    Array("ORDER_PROPS_ID"=>$props["ID"]));
         while ($vars = $db_vars->Fetch())
         {
            echo '<input type="radio"
                   name="ORDER_PROP_'.$props["ID"].
                   '" value="'.$vars["VALUE"].'"'.
                   (($vars["VALUE"]==$props["DEFAULT_VALUE"])?" checked":"").
                   '>'.htmlspecialchars($vars["NAME"]).'<br>';
         }
      }

      if (strlen($props["DESCRIPTION"])>0)
      {
         echo "<br><small>".$props["DESCRIPTION"]."</small>";
      }

      echo "<br>";
   }
   while ($props = $db_props->Fetch());
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleOrderPropsVariant::Update

int
CSaleOrderPropsVariant::Update(
 int ID,
 array arFields
);

The method Update replaces the variant parameters with the new ones from the supplied array.

Parameters

Parameter | Description
ID | The ID of the order property value whose information is to be updated.
arFields Associated array containing new parameters of the order property value variant whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • ORDER_PROPS_ID - the order property ID;
  • NAME - variant name;
  • VALUE - variant value;
  • SORT - sort weight for positioning in lists;
  • DESCRIPTION - variant description.

Return Values

Returns the ID of the updated variant on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleOrderTax

The CSaleOrderTax class is used to create taxes; apply taxes to orders and to obtain information about taxes.

Methods

Method | Description
Add | Adds a new amount of tax to an order.
CountTaxes | Calculates the total amount of specified taxes applied to a product with the specified price.
Delete | Deletes the specified tax amount.
DeleteEx | Deletes all taxes from the specified order.
GetByID | Retrieves parameters of the specified tax amount.
GetList | Returns an optionally sorted and filtered list of tax amounts.
Update | Replaces the tax amount parameters with the new ones from the supplied array.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleOrderTax::Add

int
CSaleOrderTax::Add(
  array arFields
);

The method Add adds a new amount of tax to an order.

Parameters

Parameter Description
arFields Associated array containing parameters of the new record whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • ORDER_ID - the order ID (required);
  • TAX_NAME - tax name;
  • VALUE - amount of tax (percentage);
  • VALUE_MONEY - total calculated amount of this tax;
  • APPLY_ORDER - order in which the tax is applied;
  • CODE - mnemonic tax code;
  • IS_PERCENT - must be set to "Y";
  • IS_IN_PRICE - product price includes the tax amount (Y/N).

Return Values

Returns the ID of the new tax amount on success or false otherwise.

Example

<?
$arFields = array(
   "ORDER_ID" => 12789,
   "TAX_NAME" => "VAT",
   "IS_PERCENT" => "Y",
   "VALUE" => 3.5,
   "VALUE_MONEY" => 6948.55,
   "APPLY_ORDER" => 300,
   "IS_IN_PRICE" => "N",
   "CODE" => "NDS"
);

CSaleOrderTax::Add($arFields);
?>
© 2001-2005 Bitrix Bitrix Site Manager


CountTaxes

CSaleOrderTax::CountTaxes

float
CSaleOrderTax::CountTaxes(
  float Price,
  array &arTaxList,
  string DefCurrency
);

The method CountTaxes calculates the total amount of specified taxes applied to a product with the specified price.

Parameters

Parameter | Description
Price | The product total value.
arTaxList Array of taxes in the form of array of associated arrays:
array("APPLY_ORDER"=>application_order,
      "VALUE"=>tax_rate_percentage,
      "IS_IN_PRICE"=>"included_in_price(Y/N)")
DefCurrency | Default order currency.

Return Values

Returns the total amount of taxes applied to a product. Upon return, the arTaxList contains a new key TAX_VAL containing the absolute amount of this tax applied.

Example

<?
// Create an array of active taxes for the current site,
// payer type 2 and location 48

$arTaxList = array();

$arTaxFilter = array(
   "LID" => SITE_ID,
   "PERSON_TYPE_ID" => 2,
   "ACTIVE" => "Y",
   "LOCATION" => 48
);

$db_tax_rate_tmp = CSaleTaxRate::GetList(array("APPLY_ORDER"=>"ASC"),
                                         $arTaxFilter);
while ($ar_tax_rate_tmp = $db_tax_rate_tmp->Fetch())
{
   $arTaxList[] = $ar_tax_rate_tmp;
}

// Calculate the amount of all taxes for a product at the cost of 38.95
$TAX_PRICE_tmp = CSaleOrderTax::CountTaxes(38.95, $arTaxList, "USD");

echo "Total tax: ".$TAX_PRICE_tmp."<br>";
echo "including: ";
for ($i = 0; $i<count($arTaxList); $i++)
{
   echo $arTaxList[$di]["NAME"]." - ".$arTaxList[$di]["TAX_VAL"]."<br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleOrderTax::Delete

bool
CSaleOrderTax::Delete(
  int ID
);

The method Delete deletes the specified tax amount.

Parameters

Parameter | Description
ID | The ID of the tax amount to be deleted.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


DeleteEx

CSaleOrderTax::DeleteEx

bool
CSaleOrderTax::DeleteEx(
  int ORDER_ID
);

The method DeleteEx deletes all taxes from the specified order.

Parameters

Parameter | Description
ORDER_ID | The ID of an order whose taxes are to be removed.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CSaleOrderTax::GetByID

array
CSaleOrderTax::GetByID(
  int ID
);

The method GetByID retrieves parameters of the specified tax amount.

Parameters

Parameter | Description
ID | The ID of the tax amount whose parameters are to be retrieved.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The tax amount ID.
ORDER_ID | The order ID.
TAX_NAME | Tax name.
VALUE | Tax rate.
VALUE_MONEY | Amount of tax.
APPLY_ORDER | Order in which this tax is applied relative to other ones.
CODE | Mnemonic tax code.
IS_IN_PRICE | Specifies (Y/N) that the tax in included in the product price.
IS_PERCENT | Always "Y".
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleOrderTax::GetList

CDBResult
CSaleOrderTax::GetList(
  array arOrder = Array("TAX_NAME"=>"ASC"),
  array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of tax amounts.

Parameters

Parameter Description
arOrder Associated array used to sort records. The sorting is performed consequently on each pair "key-value". Keys are the parameter names. Values are sort direction constants.

The following keys are possible:
  • TAX_NAME - tax name;
  • ID - the tax amount ID;
  • ORDER_ID - the order ID;
  • CODE - mnemonic tax code;
  • IS_IN_PRICE - specifies (Y/N) that the tax in included in the product price;
  • APPLY_ORDER - order in which this tax is applied relative to other ones.
Possible values:
  • ASC - ascending;
  • DESC - descending.
arFilter Assosiated array used to filter records. Only the records which satisfy the filter are included in the returned list. Keys are the parameter names, and the values are conditions.

The following keys are possible:
  • ID - the tax amount ID;
  • ORDER_ID - the order ID;
  • CODE - mnemonic tax code;
  • IS_IN_PRICE - specifies (Y/N) that the tax in included in the product price.

Return Values

Returns a CDBResult instance containing a set of associated arrays with the following keys.

Key | Description
ID | The tax amount ID.
ORDER_ID | The order ID.
TAX_NAME | Tax name.
VALUE | Tax rate.
VALUE_MONEY | Amount of tax.
APPLY_ORDER | Order in which this tax is applied relative to other ones.
CODE | Mnemonic tax code.
IS_IN_PRICE | Specifies (Y/N) that the tax in included in the product price.
IS_PERCENT | Always "Y".

Example

<?
$arTaxList = array();
// Select all tax amounts for order $ORDER_ID
$db_tax_list = CSaleOrderTax::GetList(array("APPLY_ORDER"=>"ASC"),
                                      Array("ORDER_ID"=>$ORDER_ID));

$iNds = -1;
$i = 0;
while ($ar_tax_list = $db_tax_list->Fetch())
{
   $arTaxList[$i] = $ar_tax_list;
   // find VAT by its mnemonic code
   if ($arTaxList[$i]["CODE"] == "VAT")
      $iNds = $i;

   $i++;
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleOrderTax::Update

int
CSaleOrderTax::Update(
 int ID,
 array arFields
);

The method Update replaces the tax amount parameters with the new ones from the supplied array.

Parameters

Parameter | Description
ID | The ID of the tax amount whose parameters are to be modified.
arFields Associated array containing new parameters of the tax amount whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • ORDER_ID - the order ID (required);
  • TAX_NAME - tax name;
  • VALUE - amount of tax (percentage);
  • VALUE_MONEY - total calculated amount of this tax;
  • APPLY_ORDER - order in which the tax is applied;
  • CODE - mnemonic tax code;
  • IS_PERCENT - must be set to "Y";
  • IS_IN_PRICE - product price includes the tax amount (Y/N).

Return Values

Returns the ID of the updated tax amount on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleOrderUserProps

The CSaleOrderUserProps class is used to create, delete, modify customer profiles and to obtain information about them.

Methods

Method | Description
Add | Creates a new customer profile given the supplied parameters.
GetList | Returns an optionally sorted and filtered list of customer profiles.
GetByID | Returns parameters of a customer profile.
Delete | Delete the profile of a specified customer. This deletes all properties as well.
ClearEmpty | Erases all empty profiles from the database. Empty profiles are those not containing properties.
Update | Replaces the customer profile parameters with the new ones from the supplied array.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleOrderUserProps::Add

int
CSaleOrderUserProps::Add(
 array arFields
);

The method Add creates a new customer profile given the supplied parameters.

Parameters

Parameter Description
arFields Associated array containing parameters of the new profile whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • NAME - user profile name;
  • USER_ID - the ID of a user for whom the profile is to be created;
  • PERSON_TYPE_ID - the payer type ID;
  • DATE_UPDATE - the date of the last modification.

Return Values

Returns the ID of the new profile on success or false otherwise.

Example

<?
$arFields = array(
   "NAME" => "Profile 1",
   "USER_ID" => $USER->GetID(),
   "PERSON_TYPE_ID" => 2
);
$USER_PROPS_ID = CSaleOrderUserProps::Add($arFields);
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


ClearEmpty

CSaleOrderUserProps::ClearEmpty

CSaleOrderUserProps::ClearEmpty();

The method ClearEmpty erases all empty profiles from the database. Empty profiles are those not containing properties.

© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSaleOrderUserProps::Delete

bool
CSaleOrderUserProps::Delete(
 int ID
);

The method Delete delete the profile of a specified customer. This deletes all properties as well.

Parameters

Parameter | Description
ID | The ID of the customer profile to be deleted.

Return Values

Returns true on success or false otherwise.

Example

<?
CSaleOrderUserProps::Delete(12);
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


GetByID

CSaleOrderUserProps::GetByID

array
CSaleOrderUserProps::GetByID(
 int ID
);

The method GetByID returns parameters of a customer profile.

Parameters

Parameter | Description
ID | The ID of the customer profile whose properties are to be returned.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The customer ID.
NAME | Profile name.
USER_ID | The ID of a user for whom the profile belongs.
PERSON_TYPE_ID | The payer type ID.
DATE_UPDATE | The date of the last modification.

Example

<?
if ($ar = CSaleOrderUserProps::GetByID(12))
{
   echo "<pre>";
   print_r($ar);
   echo "</pre>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


GetList

CSaleOrderUserProps::GetList

CDBResult
CSaleOrderUserProps::GetList(
 string &by,
 string &order,
 array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of customer profiles.

Parameters

Parameter Description
by Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • DATE_UPDATE - the date of the last modification (default);
  • NAME - customer profile name;
  • ID - the customer profile ID.
order Sort order. Can be one of the following:
  • ASC - ascending (default);
  • DESC - descending.
arFilter The filter is an associated array whose keys are the discount parameter names, and values are the conditions.

The following keys are possible:
  • ID - the customer profile ID;
  • USER_ID - the ID of a user for whom the profile belongs;
  • PERSON_TYPE_ID - the payer type ID.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The customer ID.
NAME | Profile name.
USER_ID | The ID of a user for whom the profile belongs.
PERSON_TYPE_ID | The payer type ID.
DATE_UPDATE | The date of the last modification.

Example

<?
// Select all customer profiles of the current user
// sort the list by the modification date
$db_sales = CSaleOrderUserProps::GetList(($b="DATE_UPDATE"),
                                         ($o="DESC"),
                                         Array("USER_ID" => $USER->GetID()));
while ($ar_sales = $db_sales->Fetch())
{
   echo $ar_sales["NAME"]."<br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleOrderUserProps::Update

int
CSaleOrderUserProps::Update(
 int ID,
 array arFields
);

The method Update replaces the customer profile parameters with the new ones from the supplied array.

Parameters

Parameter | Description
ID | The customer profile ID.
arFields Associated array containing new parameters of the profile whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • NAME - user profile name;
  • USER_ID - the ID of a user for whom the profile is to be created;
  • PERSON_TYPE_ID - the payer type ID;
  • DATE_UPDATE - the date of the last modification.

Return Values

Returns the ID of the updated profile on success or false otherwise.

Example

<?
// Change the profile name
$arFields = array(
   "NAME" => "Profile 24"
);
if (!CSaleOrderUserProps::Update(258, $arFields))
   echo "error updating profile";
?>
© 2001-2005 Bitrix Bitrix Site Manager


CSaleOrderUserPropsValue

The CSaleOrderUserPropsValue class is used to manage user (customer) property values.

Methods

Method | Description
GetByID | Retrieves parameters of the specified customer profile property.
Delete | Deletes a property from the customer profile.
DeleteAll | Deletes all properties from the customer profile.
GetList | Returns an optionally sorted and filtered list of customer profile properties.
Add | Adds a new property to the customer profile.
© 2001-2005 Bitrix Bitrix Site Manager
/html>


Add

CSaleOrderUserPropsValue::Add

int
CSaleOrderUserPropsValue::Add(
 array arFields
);

The method Add adds a new property to the customer profile.

Parameters

Parameter Description
arFields Associated array of a new property parameters whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • USER_PROPS_ID - the customer profile ID;
  • ORDER_PROPS_ID - the order property ID;
  • NAME - order property name;
  • VALUE - the order property value as stored in a profile.

Return Values

Returns the ID of an added customer profile property on success, or false otherwise.

Example

<?
$arFields = array(
   "USER_PROPS_ID" => 1258,
   "ORDER_PROPS_ID" => 12,
   "NAME" => "ZIP code",
   "VALUE" => "23605"
);
CSaleOrderUserPropsValue::Add($arFields);
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


Delete

CSaleOrderUserPropsValue::Delete

bool
CSaleOrderUserPropsValue::Delete(
 int ID
);

The method Delete deletes a property from the customer profile.

Parameters

Parameter | Description
ID | The customer profile property to be deleted.

Return Values

Returns true on success or false - otherwise.

Example

<?
CSaleOrderUserPropsValue::Delete(17);
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


DeleteAll

CSaleOrderUserPropsValue::DeleteAll

bool
CSaleOrderUserPropsValue::DeleteAll(
 int ID
);

The method DeleteAll deletes all properties from the customer profile.

Parameters

Parameter | Description
ID | The customer profile ID whose properties are to be all deleted.

Return Values

Returns true on success or false - otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


GetByID

CSaleOrderUserPropsValue::GetByID

array
CSaleOrderUserPropsValue::GetByID(
 int ID
);

The method GetByID retrieves parameters of the specified customer profile property.

Parameters

Parameter | Description
ID | The customer profile property ID whose information is to be retrieved.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The customer profile property ID.
USER_PROPS_ID | The customer profile ID.
ORDER_PROPS_ID | The order property ID.
NAME | Order property name.
VALUE | The order property value as stored in a profile

© 2001-2005 Bitrix Bitrix Site Manager
>


GetList

CSaleOrderUserPropsValue::GetList

CDBResult
CSaleOrderUserPropsValue::GetList(
 string &by,
 string &order,
 array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of customer profile properties.

Parameters

Parameter Description
by Specifies the name of a customer profile parameter by which the sorting is to be performed.

The following values are possible:
  • SORT - property sort weight (default);
  • NAME - property name;
  • VALUE - property value
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the parameter names, and values are the conditions.

The following keys are possible:
  • USER_PROPS_ID - the customer profile ID;
  • ORDER_PROPS_ID - the order property ID;
  • CODE - order property mnemonic code.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The customer profile property ID.
USER_PROPS_ID | The customer profile ID.
ORDER_PROPS_ID | The order property ID.
USER_VALUE_NAME | Name of an order property as stored in the customer profile.
VALUE | Value of the order property as stored in the customer profile.
TYPE | Order property type.
SORT | Order property sort weight.
VARIANT_NAME | The name of the order property variant as stored in the customer profile.
CODE | Order property mnemonic code.

Example

<?
// Display all properties from the customer profile $ID
$db_propVals = CSaleOrderUserPropsValue::GetList(($b="SORT"),
                                                 ($o="ASC"),
                                                 Array("USER_PROPS_ID"=>$ID));
while ($arPropVals = $db_propVals->Fetch())
{
   echo $arPropVals["USER_VALUE_NAME"]."=".$arPropVals["VALUE"]."<br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


CSalePaySystem

The CSalePaySystem class is used to modify and obtain pay system parameters.

Methods

Method | Description
Update | Replaces the pay system parameters with the new ones from the supplied array.
Delete | Deletes the specified pay system.
GetList | Returns an optionally sorted and filtered list of pay systems.
GetByID | Returns parameters of the specified pay system.
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSalePaySystem::Delete

bool
CSalePaySystem::Delete(
 int ID
);

The method Delete deletes the specified pay system. If any orders exist which require this pay system, the pay system will not be deleted.

Parameters

Parameter | Description
ID | The ID of the pay system to be deleted.

Return Values

Returns true on success or false otherwise.

Example

<?
CSalePaySystem::Delete(25);
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


GetByID

CSalePaySystem::GetByID

array
CSalePaySystem::GetByID(
 int ID,
 int PERSON_TYPE_ID = 0
);

The method GetByID returns parameters of the specified pay system. If the parameter PERSON_TYPE_ID is specified, the method returns parameters of the corresponding pay system handler.

Parameters

Parameter | Description
ID | The ID of the pay system whose information is to be returned.
PERSON_TYPE_ID | The payer type ID. If set to other than null, the method returns parameters of the corresponding pay system handler. Otherwise, only the pay system parameters are returned.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The pay system ID.
LID | The ID of the site owning this pay system.
CURRENCY | Currency handled by the pay system.
NAME | The name of the pay system
ACTIVE | Specifies the pay system is active (Y/N).
SORT | Sort weight.
DESCRIPTION | Pay system description.
PSA_ID | The ID of the pay system handler (returned if PERSON_TYPE_ID is not null).
PSA_NAME | Handler name (returned if PERSON_TYPE_ID is not null).
PSA_ACTION_FILE | Name of the script file containing handler (returned if PERSON_TYPE_ID is not null).
PSA_RESULT_FILE | Name of the script file containing the pay system result handler (returned if PERSON_TYPE_ID is not null).
PSA_NEW_WINDOW | Specifies the script is to be executed in the new window (Y/N) (returned if PERSON_TYPE_ID is not null).

Example

<?
// Display the pay system $PAY_SYSTEM_ID handler name
// for payer $PERSON_TYPE
if ($arPaySys = CSalePaySystem::GetByID($PAY_SYSTEM_ID, $PERSON_TYPE))
{
   echo $arPaySys["PSA_NAME"];
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSalePaySystem::GetList

CDBResult
CSalePaySystem::GetList(
 array arOrder = Array("SORT"=>"ASC", "NAME"=>"ASC"),
 array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of pay systems.

Parameters

Parameter Description
arOrder Associated array used to sort records. The sorting is performed consequently on each pair "key-value". Keys are the parameter names. Values are sort direction constants.

The following keys are possible:
  • SORT - sort weight;
  • NAME - the pay system name;
  • PSA_NAME - the pay system handler name;
  • LID - the pay system site ID;
  • ID - the pay system ID;
  • ACTIVE - flag (Y/N) indicating the pay system is active;
  • CURRENCY - the pay system currency.
Possible values:
  • ASC - ascending;
  • DESC - descending.
arFilter Associated array used to filter records. Only the records which satisfy the filter are included in the returned list. Keys are the parameter names, and the values are conditions.

The following keys are possible:
  • ID - the pay system ID;
  • LID - the pay system site ID;
  • CURRENCY - the pay system currency;
  • ACTIVE - flag (Y/N) indicating the pay system is active;
  • NAME - the pay system name;
  • PERSON_TYPE_ID - the payer type ID. If set to other than null, the method returns parameters of the corresponding pay system handler as well.

Return Values

Returns a CDBResult instance containing a set of associated arrays with the following keys.

Key | Description
ID | The pay system ID.
LID | The ID of the site owning this pay system.
CURRENCY | Currency handled by the pay system.
NAME | The name of the pay system
ACTIVE | Specifies the pay system is active (Y/N).
SORT | Sort weight.
DESCRIPTION | Pay system description.
PSA_ID | The ID of the pay system handler (returned if PERSON_TYPE_ID is not null).
PSA_NAME | Handler name (returned if PERSON_TYPE_ID is not null).
PSA_ACTION_FILE | Name of the script file containing handler (returned if PERSON_TYPE_ID is not null).
PSA_RESULT_FILE | Name of the script file containing the pay system result handler (returned if PERSON_TYPE_ID is not null).
PSA_NEW_WINDOW | Specifies the script is to be executed in the new window (Y/N) (returned if PERSON_TYPE_ID is not null).

Example

<?
// Display all active pay systems of the current site
// for the payer type 2
// we want pay systems that can handle GBP
$db_ptype = CSalePaySystem::GetList($arOrder = Array("SORT"=>"ASC",
                                                     "PSA_NAME"=>"ASC"),
                                    Array("LID"=>SITE_ID,
                                          "CURRENCY"=>"RUR",
                                          "ACTIVE"=>"Y",
                                          "PERSON_TYPE_ID"=>2));
$bFirst = True;
while ($ptype = $db_ptype->Fetch())
{
   ?><input
      type="radio"
      name="PAY_SYSTEM_ID"
      value="<?echo $ptype["ID"] ?>"<?if ($bFirst) echo " checked";?>><b>
      <?echo $ptype["PSA_NAME"] ?></b><br><?
   $bFirst = False;
   if (strlen($ptype["DESCRIPTION"])>0)
      echo $ptype["DESCRIPTION"]."<br>";
   ?><hr size="1" width="90%"><?
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSalePaySystem::Update

int
CSalePaySystem::Update(
 int ID,
 array arFields
);

The method Update replaces the pay system parameters with the new ones from the supplied array.

Parameters

Parameter | Description
ID | The ID of the pay system to be updated.
arFields Associated array containing new parameters of the pay system whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • LID - the pay system site ID;
  • CURRENCY - the pay system currency;
  • NAME - the pay system name;
  • ACTIVE - flag (Y/N) indicating the pay system is active;
  • SORT - sort weight;
  • DESCRIPTION - the pay system description.

Return Values

Returns the ID of the updated pay system or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSalePaySystemAction

The CSalePaySystemAction class is used to obtain or modify parameters of pay system handlers.

Methods

Method | Description
GetList | Retrieves an optionally sorted and filtered list of pay system handlers.
GetByID | Retrieves the pay system handler parameters given its ID.
Update | Replaces parameters of the specified handler with the new ones.
Delete | Deletes the specified pay system handler.
© 2001-2005 Bitrix Bitrix Site Manager


Delete

CSalePaySystemAction::Delete

bool
CSalePaySystemAction::Delete(
 int ID
);

The method Delete deletes the specified pay system handler.

Parameters

Parameter | Description
ID | The pay system handler ID.

Return Values

Returns true on success or false otherwise.

Example

<?
CSalePaySystemAction::Delete(12);
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


GetByID

CSalePaySystemAction::GetByID

array
CSalePaySystemAction::GetByID(
 int ID
);

The method GetByID retrieves the pay system handler parameters given its ID.

Parameters

Parameter | Description
ID | The pay system handler ID.

Return Values

Returns an associated array containing the pay system handler parameters. The array has the following keys.

Key | Description
ID | The pay system handler ID.
PAY_SYSTEM_ID | The pay system ID.
PERSON_TYPE_ID | The payer type ID.
NAME | The pay system name.
ACTION_FILE | Name of the file containing the pay system script.
RESULT_FILE | Name of the file containing a script used to retrieve the pay system result.
NEW_WINDOW | Specifies whether a new window should be opened for this pay system (Y/N).

© 2001-2005 Bitrix Bitrix Site Manager
>


GetList

CSalePaySystemAction::GetList

CDBResult
CSalePaySystemAction::GetList(
 string by = "NAME",
 string order = "ASC",
 array arFilter = Array()
);

The method GetList retrieves an optionally sorted and filtered list of pay system handlers.

Parameters

Parameter Description
by Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • NAME - handler name (default);
  • PAY_SYSTEM_ID - the pay system ID;
  • PERSON_TYPE_ID - the payer type ID;
  • ID - the pay system handler ID.
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the parameter names, and values are the conditions.

The following keys are possible:
  • ID - the pay system handler ID;
  • PAY_SYSTEM_ID - the pay system ID;
  • PERSON_TYPE_ID - the payer type ID;
  • NEW_WINDOW - specifies whether a new window should be opened for this pay system (Y/N).

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The pay system handler ID.
PAY_SYSTEM_ID | The pay system ID.
PERSON_TYPE_ID | The payer type ID.
NAME | The pay system name.
ACTION_FILE | Name of the file containing the pay system script.
RESULT_FILE | Name of the file containing a script used to retrieve the pay system result.
NEW_WINDOW | Specifies whether a new window should be opened for this pay system (Y/N).

© 2001-2005 Bitrix Bitrix Site Manager


Update

CSalePaySystemAction::Update

int
CSalePaySystemAction::Update(
 int ID,
 array arFields
);

The method Update replaces parameters of the specified handler with the new ones.

Parameters

Parameter | Description
ID | The pay system handler ID.
arFields Associated array containing new parameters of the pay system handler whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • PAY_SYSTEM_ID - the pay system ID;
  • PERSON_TYPE_ID - the payer type ID;
  • NAME - handler name (default);
  • ACTION_FILE - name of the file containing the pay system script;
  • RESULT_FILE - name of the file containing a script used to retrieve the pay system result;
  • NEW_WINDOW - specifies whether a new window should be opened for this pay system (Y/N).

Return Values

Returns the ID of updated handler or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSalePersonType

The CSalePersonType class is used to add, modify or retrieve parameters of a payer type.

Method

Method | Description
GetList | Returns an optionally sorted and filtered list of payer types.
GetByID | Returns parameters of the specified payer type.
Update | Replaces parameters of the specified payer type with the new ones.
Delete | Deletes a payer type.
Add | Adds anew payer type given the specified parameters.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSalePersonType::Add

Int
CSalePersonType::Add(
 array arFields
);

The method Add adds anew payer type given the specified parameters.

Parameters

Parameter Description
arFields Associated array containing parameters of the new payer type whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • LID - the ID of the site owning the new payer type;
  • NAME - the payer type name;
  • SORT - the payer type sort weight.

Return Values

Returns the ID of the new payer type on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


Delete

CSalePersonType::Delete

bool
CSalePersonType::Delete(
 int ID
);

The method Delete deletes a payer type. This also deletes all dependent data. Payer types that has any dependent orders cannot be deleted.

Parameters

Parameter | Description
ID | The ID of the payer type to be deleted.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


GetByID

CSalePersonType::GetByID

array
CSalePersonType::GetByID(
 int ID
);

The method GetByID returns parameters of the specified payer type.

Parameters

Parameter | Description
ID | The ID of the payer type whose properties are to be retrieved.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The payer type ID.
LID | The ID of the site owning the new payer type.
NAME | The payer type name.
SORT | The payer type sort weight.

Example

<?
if ($arPersType = CSalePersonType::GetByID($PERSON_TYPE_ID))
{
   echo "<pre>";
   print_r($arPersType);
   echo "</pre>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


GetList

CSalePersonType::GetList

CDBResult
CSalePersonType::GetList(
 string &by,
 string &order,
 array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of payer types.

Parameters

Parameter Description
by Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • SORT - the payer type sort weight (default);
  • LID - the ID of the site owning the new payer type;
  • NAME - the payer type name;
  • ID - the payer type ID.
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
arFilter The filter is an associated array whose keys are the parameter names, and values are the conditions.

The following keys are possible:
  • LID - the ID of the site owning the new payer type;
  • NAME - the payer type name;
  • ID - the payer type ID

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The payer type ID.
LID | The ID of the site owning the new payer type.
NAME | The payer type name.
SORT | The payer type sort weight.

Example

<?
// Display radio buttons allowing to select the payer type for the current site.
$db_ptype = CSalePersonType::GetList(($by="SORT"),
                                     ($order="ASC"),
                                     Array("LID"=>SITE_ID));
$bFirst = True;
while ($ptype = $db_ptype->Fetch())
{
   ?><input
      type="radio"
      name="PERSON_TYPE"
      value="<?echo $ptype["ID"] ?>"
      <?if ($bFirst) echo " checked";?>><?echo $ptype["NAME"] ?><br><?
   $bFirst = False;
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSalePersonType::Update

int
CSalePersonType::Update(
 int ID,
 array arFields
);

The method Update replaces parameters of the specified payer type with the new ones.

Parameters

Parameter | Description
ID | The ID of the payer type whose properties are to be modified.
arFields Associated array containing new parameters of the payer type whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • LID - the ID of the site owning the new payer type;
  • NAME - the payer type name;
  • SORT - the payer type sort weight.

Return Values

Returns the ID of an updated payer type or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleRecurring

The CSaleRecurring class is used with subscriptions and subscription renewals.

Methods

Method | Description
Update | The method replaces parameters of the subscription renewal with those from the specified array.
Add | The method adds a new subscription renewal with the specified parameters.
Delete | The method deletes a specified subscription renewal.
CheckRecurring | The method searches for subscriptions that are to be renewed, and attempts to renew them.
NextPayment | The method renews the specified subscription.
CancelRecurring | The method cancels the new subscription renewal.
GetList | The method returns a list of records containing information about subscription renewal.
GetByID | The method returns parameters of a subscription renewal.


Add

CSaleRecurring::Add

int
CSaleRecurring::Add(
 array arFields
);

The method Add adds a new subscription renewal with parameters passed in arFields.

Parameters

Parameter Description
arFields Associated array containing parameters of the new subscription renewal. The following keys are possible:
  • USER_ID - the user ID;
  • MODULE - the module whose product is to be renewed;
  • PRODUCT_ID - the ID of the product to be renewed;
  • PRODUCT_NAME - the name of the product to be renewed;
  • PRODUCT_URL - the reference to the product to be renewed;
  • RECUR_SCHEME_TYPE - type of the paid subscription validity period;
  • RECUR_SCHEME_LENGTH - length of the paid subscription validity period;
  • WITHOUT_ORDER - flag: without ordering;
  • ORDER_ID - the ID of the base renewal order;
  • CANCELED - flag: renewal is cancelled;
  • DESCRIPTION - the description;
  • CALLBACK_FUNC - the callback function used to update the renewal parameters;
  • REMAINING_ATTEMPTS - number of attempts left to accomplish the renewal;
  • SUCCESS_PAYMENT - the renewal was successful;
  • CANCELED_REASON - reason of cancellation;
  • DATE_CANCELED - the date of cancellation;
  • PRIOR_DATE - the date of the last renewal;
  • NEXT_DATE - the date of the next renewal.

Return Values

The method returns the ID of the added record on success, or false otherwise.


CancelRecurring

CSaleRecurring::CancelRecurring

bool
CSaleRecurring::CancelRecurring(
 int ID
 string val[,
 string description = ""]
);

The method CancelRecurring cancels the subscription renewal identified by the ID.

Parameters

Parameter | Description
ID | The ID of the record with information about a renewal.
val | If "Y", the subscription is cancelled, "N" - the subscription is restored.
description | The reason of the subscription cancellation.

Return Values

The method returns the ID of the cancelled record on success, or false otherwise.


CheckRecurring

CSaleRecurring::CheckRecurring

void
CSaleRecurring::CheckRecurring();

The method CheckRecurring searches for subscriptions that are to be renewed, and attempts to accomplish the renewal. No more than three subscriptions can be renewed at once. For automatic subscription renewal, the method can be called using agents or the cron.

Parameters

No parameters.

Return Values

No return values.


Delete

CSaleRecurring::Delete

bool
CSaleRecurring::Delete(
 int ID
);

The method Delete deletes a subscription renewal identified by the ID.

Parameters

Parameter | Description
ID | The ID of the record to be deleted.

Return Values

The method returns true on success, or false otherwise.


GetByID

CSaleRecurring::GetByID

bool
CSaleRecurring::GetByID(
 int ID
);

The method GetByID returns parameters of a subscription renewal identified by the ID.

Parameters

Parameter | Description
ID | The ID of the record containing information about the renewal.

Return Values

The method returns an associated array containing parameters of the renewal with the following keys:

  • ID - the ID of the record;
  • USER_ID - the user ID;
  • MODULE - the module whose product is to be renewed;
  • PRODUCT_ID - the ID of the product to be renewed;
  • PRODUCT_NAME - the name of the product to be renewed;
  • PRODUCT_URL - the reference to the product to be renewed;
  • RECUR_SCHEME_TYPE - type of the paid subscription validity period;
  • RECUR_SCHEME_LENGTH - length of the paid subscription validity period;
  • WITHOUT_ORDER - flag: without ordering;
  • ORDER_ID - the ID of the base renewal order;
  • CANCELED - flag: renewal is cancelled;
  • DESCRIPTION - the description;
  • CALLBACK_FUNC - the callback function used to update the renewal parameters;
  • REMAINING_ATTEMPTS - number of attempts left to accomplish the renewal;
  • SUCCESS_PAYMENT - the renewal was successful;
  • CANCELED_REASON - reason of cancellation;
  • DATE_CANCELED - the date of cancellation;
  • PRIOR_DATE - the date of the last renewal;
  • NEXT_DATE - the date of the next renewal;
  • TIMESTAMP_X - the date when the record was last modified.

Notes

The result of the method is cached within a single page. Thus, repeated calls of the method do not cause additional queries to the database.


GetList

CSaleRecurring::GetList

CDBResult
CSaleRecurring::GetList(
 array arOrder = array(),
 array arFilter = array(),
 array arGroupBy = false,
 array arNavStartParams = false,
 array arSelectFields = array()
);

The method GetList returns a list of records containing information about subscription renewal.

Parameters

Parameter Description
arOrder Associated array used to sort the resulting records. The array has the following format:
array(
"field_name1" => "sort_order1",
"field_name2" => "sort_order2",
. . .
)
The fields field_nameN can be any information field of the subscription renewal. The sort_orderX can be either "ASC" (ascending) or "DESC" (descending).

If the sorting array has more than one elements, the resulting list is sorted by each element in series (i.e. the list is first sorted by the first element, then the result is sorted by the second element etc).

The default value is an empty array() which means that the result will not be sorted.
arFilter Associated array used to filter the returned records. The array has the following format:
array(
"[modifier1][operator1]field_name1" => "value1",
"[modifier2][operator2]field_name2" => "value2",
. . .
)
Records satisfying the filter conditions are returned as a result, others are truncated.

The following modifiers are possible:
  • ! - negation;
  • + - values null, 0 and empty string also satisfy the filter conditions.
The following operators are possible:
  • >= - the field value is more than or equal to that passed in the filter;
  • > - the field value is more than that passed in the filter;
  • <= - the field value is less than or equal to that passed in the filter;
  • < - the field value is less than that passed in the filter;
  • @ - the field value is stored in the list of comma separated values passed in the filter;
  • ~ - the field value is matched against the wildcard passed to the filter;
  • % - the field value is matched (according to the query language) against the string passed to the filter.
The fields field_nameX can be any field containing information about the subscription renewal.

Example:
array("USER_ID" => 150)
This filter tells to "return all records with the value 150 in the USER_ID field".

The default value is an empty array() which means that the result will not be filtered.
arGroupBy Associated array used to group the records. The array has the following format:
array("field_name1",
      "grouping_function2" => "field_name2", . . .)
The fields field_nameN can be any field containing information about the subscription renewal. The grouping_functionX can be one of the following:
  • COUNT - quantity counting;
  • AVG - calculation of the average value;
  • MIN - calculation of the minimum value;
  • MAX - calculation of the maximum value;
  • SUM - calculation of the total value.
If the array is empty, the method will return the number of records satisfying the filter.

The default value is false which means that the result will not be grouped.
arNavStartParams Array of the selection parameters. The following keys are possible in this array:
  • "nTopCount" - number of records returned by the method will be limited to the value of this key;
  • any key that can be passed to CDBResult::NavQuery in the third parameter.
The default value is false which means that no parameter is given.
arSelectFields Array of record fields that will be returned by the method. You may specify the required fields only. If the array contains the value of "*", all available fields will be returned.

The default value is an empty array() which means that all the fields of the main query table will be returned.

Return Values

The method returns an instance of the CDBResult class, containing the list of associated arrays of the subscription renewal parameters with the following keys:

  • ID - the ID of the record;
  • USER_ID - the user ID;
  • MODULE - the module whose product is to be renewed;
  • PRODUCT_ID - the ID of the product to be renewed;
  • PRODUCT_NAME - the name of the product to be renewed;
  • PRODUCT_URL - the reference to the product to be renewed;
  • RECUR_SCHEME_TYPE - type of the paid subscription validity period;
  • RECUR_SCHEME_LENGTH - length of the paid subscription validity period;
  • WITHOUT_ORDER - flag: without ordering;
  • ORDER_ID - the ID of the base renewal order;
  • CANCELED - flag: renewal is cancelled;
  • DESCRIPTION - the description;
  • CALLBACK_FUNC - the callback function used to update the renewal parameters;
  • REMAINING_ATTEMPTS - number of attempts left to accomplish the renewal;
  • SUCCESS_PAYMENT - the renewal was successful;
  • CANCELED_REASON - reason of cancellation;
  • DATE_CANCELED - the date of cancellation;
  • PRIOR_DATE - the date of the last renewal;
  • NEXT_DATE - the date of the next renewal;
  • TIMESTAMP_X - the date when the record was last modified;
  • USER_LOGIN - the user login;
  • USER_ACTIVE - the user active state flag;
  • USER_NAME - the user first name;
  • USER_LAST_NAME - the user last name;
  • USER_EMAIL - the user e-mail.

If an empty array is passed as an arGroupBy parameter, the method will return the number of records satisfying the filter.


NextPayment

CSaleRecurring::NextPayment

bool
CSaleRecurring::NextPayment(
 int ID
);

The method NextPayment renews the subscription identified by the ID.

Parameters

Parameter | Description
ID | The ID of the record with information about the renewal.

Return Values

Returns true on success, or false otherwise.


Update

CSaleRecurring::Update

int
CSaleRecurring::Update(
 int ID,
  array arFields

);

The method Update replaces parameters of the subscription renewal with those from the arFields array.

Parameters

Parameter | Description
ID | The ID of the record to be modified.
arFields Associated array containing new parameters of the new subscription renewal with the following keys:
  • USER_ID - the user ID;
  • MODULE - the module whose product is to be renewed;
  • PRODUCT_ID - the ID of the product to be renewed;
  • PRODUCT_NAME - the name of the product to be renewed;
  • PRODUCT_URL - the reference to the product to be renewed;
  • RECUR_SCHEME_TYPE - type of the paid subscription validity period;
  • RECUR_SCHEME_LENGTH - length of the paid subscription validity period;
  • WITHOUT_ORDER - flag: without ordering;
  • ORDER_ID - the ID of the base renewal order;
  • CANCELED - flag: renewal is cancelled;
  • DESCRIPTION - the description;
  • CALLBACK_FUNC - the callback function used to update the renewal parameters;
  • REMAINING_ATTEMPTS - number of attempts left to accomplish the renewal;
  • SUCCESS_PAYMENT - the renewal was successful;
  • CANCELED_REASON - reason of cancellation;
  • DATE_CANCELED - the date of cancellation;
  • PRIOR_DATE - the date of the last renewal;
  • NEXT_DATE - the date of the next renewal.

Return Values

The method returns the ID of the modified record on success, or false otherwise.


CSaleStatus

The CSaleStatus is used to handle order statuses (or states which can be assigned to an order to indicate its progress).

Methods

Method | Description
Add | Adds a new status given the specified parameters.
Update | Replaces parameters of the specified status with the new ones.
Delete | Deletes the specified order status.
GetList | Returns an optionally sorted and filtered list of order statuses.
GetByID | Returns parameters of the specified status.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleStatus::Add

string
CSaleStatus::Add(
 array arFields
);

The method Add adds a new status given the specified parameters.

Parameters

Parameter Description
arFields Associated array containing parameters of the new status whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • ID - the status ID (required);
  • SORT - sort weight;
  • LANG - array containing arrays of language-dependent status parameters:
    • LID - language;
    • NAME - name of the status in the language LID;
    • DESCRIPTION - status description.

Return Values

Returns the ID of the new status on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


Delete

CSaleStatus::Delete

bool
CSaleStatus::Delete(
 string ID
);

The method Delete deletes the specified order status. The status cannot be deleted if the database contains orders currently in this status.

Parameters

Parameter | Description
ID | The ID of the order status to be deleted.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


GetByID

CSaleStatus::GetByID

array
CSaleStatus::GetByID(
 string ID,
 string strLang = LANGUAGE_ID
);

The method GetByID returns parameters of the specified status.

Parameters

Parameter | Description
ID | The ID of the order status whose parameters are to be retrieved .
strLang | The ID of the language in which the parameters are to be retrieved. By default, the current language is used.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The order status ID.
SORT | Sort weight.
LID | The language ID.
NAME | The status name.
DESCRIPTION | Status description.

Example

<?
if ($arStatus = CSaleStatus::GetByID($STATUS_ID))
{
   echo "<pre>";
   print_r($arStatus);
   echo "</pre>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetList

CSaleStatus::GetList

CDBResult
CSaleStatus::GetList(
 string &by,
 string &order,
 string strLang = LANGUAGE_ID
);

The method GetList returns an optionally sorted and filtered list of order statuses.

Parameters

Parameter | Description
by Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • SORT - sort weight (default);
  • ID - the status ID;
  • NAME - the status name.
order Sort order. Can be one of the following:
  • ASC - ascending;
  • DESC - descending.
strLang | The ID of the language in which the parameters are to be retrieved. By default, the current language is used.

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Description
ID | The order status ID.
SORT | Sort weight.
LID | The language ID.
NAME | The status name.
DESCRIPTION | Status description.

© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleStatus::Update

string
CSaleStatus::Update(
 string ID,
 array arFields
);

The method Update replaces parameters of the specified status with the new ones.

Parameters

Parameter | Description
ID | The ID of the order status to be updated .
arFields Associated array containing new parameters of the status whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • ID - the status ID (required);
  • SORT - sort weight;
  • LANG - array containing arrays of language-dependent status parameters:
    • LID - language;
    • NAME - name of the status in the language LID;
    • DESCRIPTION - status description.

Return Values

Returns the ID of updated status or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleTax

Use the CSaleTax class to create, modify, delete or retrieve information about the taxes or tax exempts.

Methods

Method | Description
Update | Replaces parameters of the specified tax with the new ones.
Delete | Deletes the specified tax. This also deletes all rates and exempts of this tax.
GetByID | Returns parameters of the specified tax.
GetList | Returns an optionally sorted and filtered list of taxes.
GetExemptList | Retrieves a filtered set of tax exempt records from the tax exempt registry.
AddExempt | Adds a new record to the tax exempt registry.
DeleteExempt | Deletes tax exempts according to the specified filter from the tax exempt register.
Add | Creates a new tax given its parameters.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleTax::Add

int
CSaleTax::Add(
 array arFields
);

The method Add creates a new tax given its parameters.

Parameters

Parameter Description
arFields Associated array containing parameters of the new tax whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • LID - the site ID;
  • NAME - tax name;
  • DESCRIPTION - tax description;
  • CODE - mnemonic code.

Return Values

Returns the ID of the new tax on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


AddExempt

CSaleTax::AddExempt

bool
CSaleTax::AddExempt(
 array arFields
);

The method AddExempt adds a new record to the tax exempt registry.

Parameters

Parameter Description
arFields Associated array containing parameters of the new record. The following keys are possible:
  • GROUP_ID - the user group ID whose members have tax exempt rights;
  • TAX_ID - the ID of the tax from which the user group is to be relieved.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


Delete

CSaleTax::Delete

bool
CSaleTax::Delete(
 int ID
);

The method Delete deletes the specified tax. This also deletes all rates and exempts of this tax.

Parameters

Parameter | Description
ID | The ID of the tax to be deleted.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


DeleteExempt

CSaleTax::DeleteExempt

bool
CSaleTax::DeleteExempt(
 array arFields
);

The method DeleteExempt deletes tax exempts according to the specified filter from the tax exempt register.

Parameters

Parameter Description
arFields Associated array containing conditions on which the tax exempts are selected for deletion. The following keys apply:
  • GROUP_ID - the user group ID whose members have tax exempt rights;
  • TAX_ID - the ID of the tax from which the user group are currently relieved.
The array must contain at least one key.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


GetByID

CSaleTax::GetByID

array
CSaleTax::GetByID(
 int ID
);

The method GetByID returns parameters of the specified tax.

Parameters

Parameter | Description
ID | The ID of a tax whose parameters are to be returned.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The tax ID.
LID | The site ID.
NAME | the tax name.
CODE | Mnemonic tax code.
DESCRIPTION | The tax description.
TIMESTAMP_X | The date the record was last modified.

Example

<?
// Display parameters of the tax $TAX_ID
if ($arTax = CSaleTax::GetByID($TAX_ID))
{
   echo "<pre>";
   print_r($arTax);
   echo "</pre>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


GetExemptList

CSaleTax::GetExemptList

CDBResult
CSaleTax::GetExemptList(
 array arFilter = Array()
);

The method GetExemptList retrieves a filtered set of tax exempt records from the tax exempt registry.

Parameters

Parameter Description
arFilter Associated array used to filter records. Only the records which satisfy the filter are included in the returned list. Keys are the parameter names, and the values are conditions.

The following keys are possible:
  • GROUP_ID - the user group ID whose members have tax exempt rights;
  • TAX_ID - the ID of the tax from which the user group is to be relieved.

Return Values

The method returns an instance of the CDBResult class containing the list of associated arrays with parameters:

Key | Description
GROUP_ID | The user group ID whose members have tax exempt rights.
TAX_ID | The ID of the tax from which the user group is to be relieved.

Example

<?
// Fill an array of tax exempts for current user
$arTaxExempt = array();
if ($USER->IsAuthorized())
{
   $arUserGroups = $USER->GetUserGroupArray();
   for ($ig = 0; $ig < count($arUserGroups); $ig++)
   {
      $db_tax_ex_tmp = CSaleTax::GetExemptList(Array("GROUP_ID"=>$arUserGroups[$ig]));
      while ($ar_tax_ex_tmp = $db_tax_ex_tmp->Fetch())
      {
         if (!in_array(IntVal($ar_tax_ex_tmp["TAX_ID"]), $arTaxExempt))
         {
            $arTaxExempt[] = IntVal($ar_tax_ex_tmp["TAX_ID"]);
         }
      }
   }
}
?>
© 2001-2005 Bitrix Bitrix Site Manager
>


GetList

CSaleTax::GetList

CDBResult
CSaleTax::GetList(
 array arOrder = Array("NAME"=>"ASC"),
 array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of taxes.

Parameters

Parameter Description
arOrder Associated array used to sort records. The sorting is performed consequently on each pair "key-value". Keys are the parameter names. Values are sort direction constants.

The following keys are possible:
  • NAME - tax name;
  • ID - the tax ID;
  • LID - the site ID;
  • CODE - the taxmnemonic code;
  • TIMESTAMP_X - the date the record was last modified.
arFilter Associated array used to filter taxes. Only the records which satisfy the filter are included in the returned list. Keys are the parameter names, and the values are conditions.

The following keys are possible:
  • ID - the tax ID;
  • LID - the site ID;
  • CODE - the tax mnemonic code;

Return Values

Returns a CDBResult instance containing a set of associated arrays with the following keys.

Key | Description
ID | The tax ID.
LID | The site ID.
NAME | the tax name.
CODE | Mnemonic tax code.
DESCRIPTION | The tax description.
TIMESTAMP_X | The date the record was last modified.
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleTax::Update

int
CSaleTax::Update(
 int ID,
 array arFields
);

The method Update replaces parameters of the specified tax with the new ones.

Parameters

Parameter | Description
ID | The ID of the tax to be updated.
arFields Associated array containing new parameters of the tax whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • LID - the site ID;
  • NAME - tax name;
  • DESCRIPTION - tax description;
  • CODE - mnemonic code.

Return Values

Returns the ID of updated tax or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleTaxRate

The CSaleTaxRate class is used to create, obtain, modify and delete tax rates.

Methods

Method | Description
Update | Replaces the tax rate parameters with the new ones from the supplied array.
Delete | Deletes the specified tax rate.
GetByID | Returns parameters of the specified tax rate.
Add | Creates a new tax rate given its parameters.
GetList | Returns an optionally sorted and filtered list of tax rates.
© 2001-2005 Bitrix Bitrix Site Manager


Add

CSaleTaxRate::Add

int
CSaleTaxRate::Add(
 array arFields
);

The method Add creates a new tax rate given its parameters.

Parameters

Parameter Description
arFields Associated array containing parameters of the new tax rate whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • TAX_ID - the tax ID;
  • PERSON_TYPE_ID - the payer ID;
  • VALUE - amount of tax (percentage);
  • CURRENCY - currency;
  • IS_PERCENT - always set to "Y";
  • IS_IN_PRICE - product price includes the tax amount;
  • APPLY_ORDER - order in which the tax is applied;
  • ACTIVE - specifies the tax is active (Y/N);
  • TAX_LOCATION - array used to define locations and location groups to which this tax is applicable. Each entry in this array is in its turn an array with the following keys:
    • LOCATION_ID - the ID of location or location group;
    • LOCATION_TYPE - set to "L" for locations and to "G" for location groups.

Return Values

Returns the ID of the new tax rate on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


Delete

CSaleTaxRate::Delete

bool
CSaleTaxRate::Delete(
 int ID
);

The method Delete deletes the specified tax rate.

Parameters

Parameter | Description
ID | The ID of a tax rate to be deleted.

Return Values

Returns true on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager
>


GetByID

CSaleTaxRate::GetByID

array
CSaleTaxRate::GetByID(
 int ID
);

The method GetByID returns parameters of the specified tax rate.

Parameters

Parameter | Description
ID | The ID of a tax rate whose parameters are to be returned.

Return Values

Returns an associated array with the following keys.

Key | Description
ID | The tax rate ID.
TAX_ID | The tax ID.
PERSON_TYPE_ID | The payer type ID.
VALUE | Amount of tax (percentage).
CURRENCY | Currency.
IS_PERCENT | Always set to "Y".
IS_IN_PRICE | Product price includes the tax amount (Y/N).
APPLY_ORDER | Order in which the tax is applied.
TIMESTAMP_X | The date the record was last modified.
ACTIVE | Specifies the tax is active (Y/N).

© 2001-2005 Bitrix Bitrix Site Manager
>


GetList

CSaleTaxRate::GetList

CDBResult
CSaleTaxRate::GetList(
 array arOrder = Array("APPLY_ORDER"=>"ASC"),
 array arFilter = Array()
);

The method GetList returns an optionally sorted and filtered list of tax rates.

Parameters

Parameter Description
arOrder Assosiated array used to sort records. The sorting is performed consequently on each pair "key-value". Keys are the parameter names. Values are sort direction constants.

The following keys are possible:
  • APPLY_ORDER - order in which the tax is applied;
  • ID - the tax rate ID;
  • LID - the ID of the site for which the tax is applicable;
  • CODE - tax mnemonic code;
  • TIMESTAMP_X - the date the record was last modified;
  • ACTIVE - specifies the tax is active (Y/N);
  • NAME - tax name;
  • PERSON_TYPE_ID - the tax payer ID;
  • IS_IN_PRICE - product price includes the tax amount (Y/N).
Possible values:
  • ASC - ascending;
  • DESC - descending.
arFilter Associated array used to filter records. Only the records which satisfy the filter are included in the returned list. Keys are the parameter names, and the values are conditions.

The following keys are possible:
  • ID - the tax rate ID;
  • LID - the ID of the site for which the tax is applicable;
  • CODE - tax mnemonic code;
  • TAX_ID - the tax ID;
  • PERSON_TYPE_ID - the tax payer ID;
  • IS_IN_PRICE - product price includes the tax amount (Y/N);
  • ACTIVE - specifies the tax is active (Y/N);
  • APPLY_ORDER - order in which the tax is applied;
  • LOCATION_ID - the ID of location to which the tax can be applied.

Return Values

Returns a CDBResult instance containing a set of associated arrays with the following keys.

Key | Description
ID | The tax rate ID.
TAX_ID | The tax ID.
PERSON_TYPE_ID | The payer type ID.
VALUE | Amount of tax (percentage).
CURRENCY | Currency.
IS_PERCENT | Always set to "Y".
IS_IN_PRICE | Product price includes the tax amount (Y/N).
APPLY_ORDER | Order in which the tax is applied.
TIMESTAMP_X | The date the record was last modified.
LID | The ID of the site for which the tax is applicable.
NAME | Tax name.
CODE | Tax mnemonic code.
DESCRIPTION | Tax description.
ACTIVE | Specifies the tax is active (Y/N).

Example

<?
// Get the array of active tax rates for the current site
// for payer type $PERSON_TYPE and location $TAX_LOCATION

$arTaxList = array();

$arTaxFilter = array(
   "LID" => SITE_ID,
   "PERSON_TYPE_ID" => $PERSON_TYPE,
   "ACTIVE" => "Y",
   "LOCATION" => $TAX_LOCATION
);

$db_tax_rate_tmp = CSaleTaxRate::GetList(array("APPLY_ORDER"=>"ASC"), $arTaxFilter);
while ($ar_tax_rate_tmp = $db_tax_rate_tmp->Fetch())
{
   $arTaxList[] = $ar_tax_rate_tmp;
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Update

CSaleTaxRate::Update

int
CSaleTaxRate::Update(
 int ID,
 array arFields
);

The method Update replaces the tax rate parameters with the new ones from the supplied array.

Parameters

Parameter | Description
ID | The tax rate ID.
arFields Associated array containing the new tax rate parameters whose keys are the order parameter names, and values are the parameter values.

The following values are possible:
  • TAX_ID - the tax ID;
  • PERSON_TYPE_ID - the payer ID;
  • VALUE - amount of tax (percentage);
  • CURRENCY - currency;
  • IS_PERCENT - always set to "Y";
  • IS_IN_PRICE - product price includes the tax amount;
  • APPLY_ORDER - order in which the tax is applied;
  • ACTIVE - specifies the tax is active (Y/N);
  • TAX_LOCATION - array used to define locations and location groups to which this tax is applicable. Each entry in this array is in its turn an array with the following keys:
    • LOCATION_ID - the ID of location or location group;
    • LOCATION_TYPE - set to "L" for locations and to "G" for location groups.

Return Values

Returns the ID of the updated tax rate on success or false otherwise.

© 2001-2005 Bitrix Bitrix Site Manager


CSaleUserAccount

The CSaleUserAccount class helps manage internal user accounts.

Methods

Method | Description
Delete | The method deletes the internal user account.
Pay | The method withdraws the specified amount from the internal user account.
Withdraw | The method withdraws the specified amount from the internal user account.
UpdateAccount | The method modifies the amount of the account of a specified user.
GetByID | The method returns an associated array containing parameters of the specified account.
GetByUserID | The method returns an associated array containing parameters of an account in the specified currency for the specified user.
GetList | The method returns a selection of accounts according to the specified criteria.
Add | The method adds a new user account with the specified parameters.
Update | The method replaces parameters of a user account with those from the specified array.


Add

CSaleUserAccount::Add

int
CSaleUserAccount::Add(
 array arFields
);

The method Add adds a new user account with the specified parameters.

Parameters

Parameter Description
arFields Associated array containing parameters of the new account. The following keys are possible:
  • USER_ID - the user ID;
  • CURRENT_BUDGET - the current balance of the account;
  • CURRENCY - currency;
  • NOTES - the text description;
  • LOCKED - flag: the account is disabled;
  • DATE_LOCKED - the date the account was disabled.

Return Values

The method returns the ID of the added account on success, or false otherwise.


Delete

CSaleUserAccount::Delete

bool
CSaleUserAccount::Delete(
 int ID
);

The method Delete deletes the internal user account.

Parameters

Parameter | Description
ID | The ID of the account to be deleted.

Return Values

The method returns true on success, or false otherwise.


GetByID

CSaleUserAccount::GetByID

array
CSaleUserAccount::GetByID(
 int ID
);

The method GetByID returns an associated array containing parameters of the specified account.

Parameters

Parameter | Description
ID | The account ID.

Return Values

The method returns an associated array containing the account parameters with the following keys:

  • ID - the account ID;
  • USER_ID - the user ID;
  • CURRENT_BUDGET - the current balance of the account;
  • CURRENCY - currency;
  • NOTES - the text description;
  • LOCKED - flag: the account is disabled;
  • TIMESTAMP_X - the date when the account was last modified.;
  • DATE_LOCKED - the date when the account was disabled.

Notes

The result of the method is cached within a single page. Thus, repeated calls of the method do not cause additional queries to the database.

Example

<? if ($ar = CSaleUserAccount::GetByID(5))
{ echo "Current balance ".SaleFormatCurrency($ar["CURRENT_BUDGET"],
                                             $ar["CURRENCY"]); } ?>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByUserID

CSaleUserAccount::GetByUserID

array
CSaleUserAccount::GetByUserID(
 int userID,
 string currency
);

The method GetByUserID returns an associated array containing parameters of an account in the specified currency for the specified user.

Parameters

Parameter | Description
userID | The user ID.
currency | The currency of the account.

Return Values

The method returns an associated array containing parameters of the account with the following keys:

  • ID - the account ID;
  • USER_ID - the user ID;
  • CURRENT_BUDGET - the current balance of the account;
  • CURRENCY - currency;
  • NOTES - the text description;
  • LOCKED - flag: the account is disabled;
  • TIMESTAMP_X - the date when the account was last modified.;
  • DATE_LOCKED - the date when the account was disabled.

Notes

The result of the method is cached within a single page. Thus, repeated calls of the method do not cause additional queries to the database.

Example

<? if ($ar = CSaleUserAccount::GetByUserID(172, "USD"))
 { echo "Account balance: ".SaleFormatCurrency($ar["CURRENT_BUDGET"], $ar["CURRENCY"]); } ?>


GetList

CSaleUserAccount::GetList

CDBResult
CSaleUserAccount::GetList(
 array arOrder = array(),
 array arFilter = array(),
 array arGroupBy = false,
 array arNavStartParams = false,
 array arSelectFields = array()
);

The method GetList returns a selection of accounts according to the specified criteria.

Parameters

Parameter Description
arOrder Associated array used to sort the resulting records. The array has the following format:
array(
"field_name1" => "sort_order1",
"field_name2" => "sort_order2",
. . .
)
The fields field_nameN can be any field of an account. The sort_orderX can be either "ASC" (ascending) or "DESC" (descending).

If the sorting array has more than one elements, the resulting list is sorted by each element in series (i.e. the list is first sorted by the first element, then the result is sorted by the second element etc).

The default value is an empty array() which means that the result will not be sorted.
arFilter Associated array used to filter the records of accounts. The array has the following format:
array(
"[modifier1][operator1]field_name1" => "value1",
"[modifier2][operator2]field_name2" => "value2",
. . .
)
Records satisfying the filter conditions are returned as a result, others are truncated.

The following modifiers are possible:
  • ! - negation;
  • + - values null, 0 and empty string also satisfy the filter conditions.
The following operators are possible:
  • >= - the field value is more than or equal to that passed in the filter;
  • > - the field value is more than that passed in the filter;
  • <= - the field value is less than or equal to that passed in the filter;
  • < - the field value is less than that passed in the filter;
  • @ - the field value is stored in the list of comma separated values passed in the filter;
  • ~ - the field value is matched against the wildcard passed to the filter;
  • % - the field value is matched (according to the query language) against the string passed to the filter.
The fields field_nameX can be name of any field containing information about an account.

Example:
array("USER_ID" => 150)
This filter tells to "return all records with the value 150 in the USER_ID field".

The default value is an empty array() which means that the result will not be filtered.
arGroupBy Associated array used to group the records of accounts. The array has the following format:
array("field_name1",
      "grouping_function2" => "field_name2", ...)
The fields field_nameN can be any field containing information about an account. The grouping_functionX can be one of the following:
  • COUNT - quantity counting;
  • AVG - calculation of the average value;
  • MIN - calculation of the minimum value;
  • MAX - calculation of the maximum value;
  • SUM - calculation of the total value.
If the array is empty, the method will return the number of records satisfying the filter.

The default value is false which means that the result will not be grouped.
arNavStartParams Array of the selection parameters. The following keys are possible in this array:
  • "nTopCount" - number of records returned by the method will be limited to the value of this key;
  • any key that can be passed to CDBResult::NavQuery in the third parameter.
The default value is false which means that no parameter is given.
arSelectFields Array of record fields that will be returned by the method. You may specify the required fields only. If the array contains the value of "*", all available fields will be returned.

The default value is an empty array() which means that all the fields of the main query table will be returned.

Return Values

The method returns an instance of the CDBResult class, containing the list of associated arrays with parameters of accounts:

  • ID - the account ID;
  • USER_ID - the user ID;
  • CURRENT_BUDGET - the current balance of the account;
  • CURRENCY - currency;
  • NOTES - the text description;
  • LOCKED - flag: the account is disabled;
  • TIMESTAMP_X - the date when the account was last modified.;
  • DATE_LOCKED - the date when the account was disabled.

If an empty array is passed as an arGroupBy parameter, the method will return the number of records satisfying the filter.

Example

<?
// Select all accounts (with different currencies) of the user #21
$dbAccountCurrency = CSaleUserAccount::GetList(
        array(),
        array("USER_ID" => "21"),
        false,
        false,
        array("CURRENT_BUDGET", "CURRENCY")
    );
while ($arAccountCurrency = $dbAccountCurrency->Fetch())
{
    echo "Current balance ".$arAccountCurrency["CURRENCY"].": ";
    echo SaleFormatCurrency($arAccountCurrency["CURRENT_BUDGET"],
                            $arAccountCurrency["CURRENCY"])."<br>";
}

// Obtain the total amount of the users' accounts
$dbAccountCurrency = CSaleUserAccount::GetList(
        array("CURRENCY" => "ASC"),
        array(),
        array("CURRENCY", "SUM" => "CURRENT_BUDGET"),
        false,
        array("CURRENCY", "SUM" => "CURRENT_BUDGET")
    );
while ($arAccountCurrency = $dbAccountCurrency->Fetch())
{
    echo "Currency ".$arAccountCurrency["CURRENCY"].": ";
    echo SaleFormatCurrency($arAccountCurrency["CURRENT_BUDGET"],
                            $arAccountCurrency["CURRENCY"])."<br>";
}
?>


Pay

CSaleUserAccount::Pay

bool
CSaleUserAccount::Pay(
 int userID,
 double paySum,
 string payCurrency[,
 int orderID = 0[,
 bool useCC = True]]
);

The method Pay withdraws the specified amount from the internal user account. If there is not enough money on the internal account, the method attempts to withdraw deficient amount from the user credit card.

Parameters

Parameter | Description
userID | The user ID.
paySum | The amount to withdraw.
payCurrency | The currency of the amount to withdraw.
orderID | The order ID (if applicable).
useCC | If true, the method will attempt to withdraw deficient amount from the user credit card, if there is not enough money on the internal account. If false, the user credit card is not touched.

Return Values

The method returns true if the money has been withdrawn, or false if the specified amount could not be withdrawn.

Remarks

The amount is withdrawn only from the account in currency passed in payCurrency. Other user accounts are not affected.

Example

<?
// Withdraw 3 EUR from the Euro account, to pay order #21
$bSuccessPayment = CSaleUserAccount::Pay(
        $USER->GetID(),
        3,
        "EUR",
        21,
        False
    );
if ($bSuccessPayment)
    echo "Transaction succeeded";
?>


Update

CSaleUserAccount::Update

int
CSaleUserAccount::Update(
 int ID,
 array arFields
);

The method Update replaces parameters of a user account with those from the specified array.

Parameters

Parameter | Description
ID | The ID of the account to modify.
arFields Associated array containing new parameters of the account. The following keys are possible:
  • USER_ID - the user ID;
  • CURRENT_BUDGET - the current balance of the account;
  • CURRENCY - currency;
  • NOTES - the text description;
  • LOCKED - flag: the account is disabled;
  • DATE_LOCKED - the date the account was disabled.

Return Values

The method returns the ID of the modified account on success, or false otherwise.


UpdateAccount

CSaleUserAccount::UpdateAccount

int
CSaleUserAccount::UpdateAccount(
 int userID,
 double sum,
 string currency[,
 string description = ""[,
 int orderID = 0[,
 string notes = ""]]]
);

The method UpdateAccount modifies the amount of the account of a specified user.

Parameters

Parameter | Description
userID | The user ID.
sum | The amount to be added to or subtracted from the account. To increase the account amount, pass positive value. To decrease the account amount, pass negative value.
currency | The currency of the amount.
description | Description of the reason to modify the amount.
orderID | The order ID (if applicable).
notes | Arbitrary description.

Return Values

The method returns the ID of the user account on success, or false otherwise.

Remarks

The amount is withdrawn only from the account in currency passed in payCurrency. Other user accounts are not affected.

Example

<?
// Callback function called when the flag "Delivery allowed" changes.
// The function adds or withdraws USD 100 to or from the account.

function MyDeliveryOrderCallback($productID, $userID, $bPaid, $orderID)
{
    global $DB;

    // Process the input parameters
    $productID = IntVal($productID);    // The ID of the ordered product
    $userID = IntVal($userID);  // The customer ID
    $bPaid = ($bPaid ? True : False);   // Set or unset the delivery flag
    $orderID = IntVal($orderID);    // The order ID

    if ($userID <= 0)
        return False;

    if ($orderID <= 0)
        return False;

    // place (withdraw) money to the account
    if (!CSaleUserAccount::UpdateAccount(
            $userID,
            ($bPaid ? 100 : -100),
            "USD",
            "MANUAL",
            $orderID
        ))
        return False;

    return True;
}
?>


Withdraw

CSaleUserAccount::Withdraw

double
CSaleUserAccount::Withdraw(
 int userID,
 double paySum,
 string payCurrency[,
 int orderID = 0]
);

The method Withdraw withdraws the specified amount from the internal user account. If there is not enough money on the internal account, the method withdraws maximum available amount.

Parameters

Parameter | Description
userID | The user ID.
paySum | The amount to withdraw.
payCurrency | The currency of the amount to withdraw.
orderID | The order ID (if applicable).

Return Values

The method returns the amount actually withdrawn, or false otherwise.

Remarks

The amount is withdrawn only from the account in currency passed in payCurrency. Other user accounts are not affected.

Example

<?
// Pay the order 21 in full or partially from the user's account

$arOrder = CSaleOrder::GetByID(21);

$withdrawSum = CSaleUserAccount::Withdraw(
        $arOrder["USER_ID"],
        $arOrder["PRICE"],
        $arOrder["CURRENCY"],
        $arOrder["ID"]
    );

if ($withdrawSum > 0)
{
    $arFields = array(
            "SUM_PAID" => $withdrawSum,
            "USER_ID" => $arOrder["USER_ID"]
        );
    CSaleOrder::Update($arOrder["ID"], $arFields);

    if ($withdrawSum == $arOrder["PRICE"])
        CSaleOrder::PayOrder($arOrder["ID"], "Y", False, False);
}
?>


CSaleUserCards

The CSaleUserCards class is used to manage customers' credit cards.

Methods

Method | Description
Delete | The method deletes information about a user's credit card.
GetByID | The method returns parameters of the specified credit card.
Add | The method adds information about a new user credit card.
Update | The method modifies the information about a new user credit card.
GetList | The method returns records containing information about credit cards according to the specified criteria.
CryptData | The method encrypts or decrypts the credit card number.
CheckPassword | The method checks whether the password for credit card number encryption is set.
IdentifyCardType | The method returns the type of the credit card by its number.


Add

CSaleUserCards::Add

int
CSaleUserCards::Add(
 array arFields
);

The method Add adds information about a new user credit card.

Parameters

Parameter Description
arFields An associated array of the credit card parameters with the following keys:
  • USER_ID - the user ID;
  • SORT - sort weight;
  • PAY_SYSTEM_ACTION_ID - the ID of the payment system handler;
  • CURRENCY - the currency in which money can be withdrawn;
  • CARD_CODE - the CVC2 code;
  • CARD_TYPE - the type of the card;
  • CARD_NUM - the credit card number;
  • CARD_EXP_MONTH - the month of the credit card expiration;
  • CARD_EXP_YEAR - the year of the credit card expiration;
  • DESCRIPTION - brief description;
  • SUM_MIN - minimum amount which can be withdrawn from the card within a single transaction;
  • SUM_MAX - maximum amount which can be withdrawn from the card within a single transaction;
  • SUM_CURRENCY - the currency of the minimum/maximum amounts;
  • LAST_STATUS - the status of the last card usage;
  • LAST_STATUS_CODE - the ID of the status of the last card usage;
  • LAST_STATUS_DESCRIPTION - the description of the status of the last card usage;
  • LAST_STATUS_MESSAGE - the response received from the payment system;
  • LAST_SUM - the last amount withdrawn from the card;
  • LAST_CURRENCY - the currency of the last amount withdrawn from the card;
  • ACTIVE - active state flag;
  • LAST_DATE - the date when the credit card was last used.

Note
The credit card number must be encrypted using the CSaleUserCards::CryptData method before adding the record.

Return Values

The method returns the ID of the added record on success, or false otherwise.

Example

<?
// Save the information about the current user's new card

if (CSaleUserCards::CheckPassword())
{
    $arFields = array(
            "USER_ID" => $USER->GetID(),
            "ACTIVE" => "Y",
            "SORT" => "100",
            "PAY_SYSTEM_ACTION_ID" => 11,
            "CURRENCY" => "USD",
            "CARD_TYPE" =>
                CSaleUserCards::IdentifyCardType("4111111111111"),
            "CARD_NUM" =>
                CSaleUserCards::CryptData("4111111111111", "E"),
            "CARD_EXP_MONTH" => 11,
            "CARD_EXP_YEAR" => 2007,
            "DESCRIPTION" => false,
            "CARD_CODE" => "123",
            "SUM_MIN" => False,
            "SUM_MAX" => False,
            "SUM_CURRENCY" => False
        );

    $UserCardID = CSaleUserCards::Add($arFields);
}
?>


CheckPassword

CSaleUserCards::CheckPassword

bool
CSaleUserCards::CheckPassword();

The method CheckPassword checks whether the password for credit card number encryption is set.

Parameters

No parameters.

Return Values

The method returns true if the password was set, or false otherwise.


CryptData

CSaleUserCards::CryptData

string
CSaleUserCards::CryptData(
 string data,
 string type
);

The method CryptData encrypts or decrypts the credit card number.

Parameters

Parameter | Description
data | The data to be encrypted (or decrypted).
type | To encrypt the data, pass "E" in this parameter. To decrypt the data, pass "D".

Remarks

The card number must be encrypted before it is saved in the database, and decrypted after it is returned from the database.

Return Values

The method returns the result of the encryption (decryption).


Delete

CSaleUserCards::Delete

bool
CSaleUserCards::Delete(
 int ID
);

The method Delete deletes information about a user's credit card.

Parameters

Parameter | Description
ID | The ID of the record containing information about the card.

Return Values

The method returns true on success, or false otherwise.


GetByID

CSaleUserCards::GetByID

array
CSaleUserCards::GetByID(
 int ID
);

The method GetByID returns parameters of the specified credit card.

Parameters

Parameter | Description
ID | The ID of the credit card.

Return Values

The method returns an associated array of parameters of the credit card with the following keys:

  • ID - the credit card ID;
  • USER_ID - the user ID;
  • SORT - sort weight;
  • PAY_SYSTEM_ACTION_ID - the ID of the payment system handler;
  • CURRENCY - the currency in which money can be withdrawn;
  • CARD_CODE - the CVC2 code;
  • CARD_TYPE - the type of the card;
  • CARD_NUM - the credit card number;
  • CARD_EXP_MONTH - the month of the credit card expiration;
  • CARD_EXP_YEAR - the year of the credit card expiration;
  • DESCRIPTION - brief description;
  • SUM_MIN - minimum amount which can be withdrawn from the card within a single transaction;
  • SUM_MAX - maximum amount which can be withdrawn from the card within a single transaction;
  • SUM_CURRENCY - the currency of the minimum/maximum amounts;
  • LAST_STATUS - the status of the last card usage;
  • LAST_STATUS_CODE - the ID of the status of the last card usage;
  • LAST_STATUS_DESCRIPTION - the description of the status of the last card usage;
  • LAST_STATUS_MESSAGE - the response received from the payment system;
  • LAST_SUM - the last amount withdrawn from the card;
  • LAST_CURRENCY - the currency of the last amount withdrawn from the card;
  • ACTIVE - active state flag;
  • TIMESTAMP_X - the date when the credit card information was last modified;
  • LAST_DATE - the date when the credit card was last used..


GetList

CSaleUserCards::GetList

CDBResult
CSaleUserCards::GetList(
 array arOrder = array(),
 array arFilter = array(),
 array arGroupBy = false,
 array arNavStartParams = false,
 array arSelectFields = array()
);

The method GetList returns records containing information about credit cards according to the specified criteria.

Parameters

Parameter Description
arOrder Associated array used to sort the resulting records. The array has the following format:
array(
"field_name1" => "sort_order1",
"field_name2" => "sort_order2",
. . .
)
The fields field_nameN can be any field of a credit card. The sort_orderX can be either "ASC" (ascending) or "DESC" (descending).

If the sorting array has more than one elements, the resulting list is sorted by each element in series (i.e. the list is first sorted by the first element, then the result is sorted by the second element etc).

The default value is an empty array() which means that the result will not be sorted.
arFilter Associated array used to filter the records of credit cards. The array has the following format:
array(
"[modifier1][operator1]field_name1" => "value1",
"[modifier2][operator2]field_name2" => "value2",
. . .
)
Records satisfying the filter conditions are returned as a result, others are truncated.

The following modifiers are possible:
  • ! - negation;
  • + - values null, 0 and empty string also satisfy the filter conditions.
The following operators are possible:
  • >= - the field value is more than or equal to that passed in the filter;
  • > - the field value is more than that passed in the filter;
  • <= - the field value is less than or equal to that passed in the filter;
  • < - the field value is less than that passed in the filter;
  • @ - the field value is stored in the list of comma separated values passed in the filter;
  • ~ - the field value is matched against the wildcard passed to the filter;
  • % - the field value is matched (according to the query language) against the string passed to the filter.
The fields field_nameX can be name of any field containing information about a credit card.

Example:
array("USER_ID" => 150)
This filter tells to "return all records with the value 150 in the USER_ID field".

The default value is an empty array() which means that the result will not be filtered.
arGroupBy Associated array used to group the records of credit cards. The array has the following format:
array("field_name1",
      "grouping_function2" => "field_name2", . . .)
The fields field_nameN can be any field containing information about a credit card. The grouping_functionX can be one of the following:
  • COUNT - quantity counting;
  • AVG - calculation of the average value;
  • MIN - calculation of the minimum value;
  • MAX - calculation of the maximum value;
  • SUM - calculation of the total value.
If the array is empty, the method will return the number of records satisfying the filter.

The default value is false which means that the result will not be grouped.
arNavStartParams Array of the selection parameters. The following keys are possible in this array:
  • "nTopCount" - number of records returned by the method will be limited to the value of this key;
  • any key that can be passed to CDBResult::NavQuery in the third parameter.
The default value is false which means that no parameter is given.
arSelectFields Array of record fields that will be returned by the method. You may specify the required fields only. If the array contains the value of "*", all available fields will be returned.

The default value is an empty array() which means that all the fields of the main query table will be returned.

Return Values

The method returns an instance of the CDBResult class, containing the list of associated arrays with parameters of credit cards:

  • ID - the credit card ID;
  • USER_ID - the user ID;
  • SORT - sort weight;
  • PAY_SYSTEM_ACTION_ID - the ID of the payment system handler;
  • CURRENCY - the currency in which money can be withdrawn;
  • CARD_CODE - the CVC2 code;
  • CARD_TYPE - the type of the card;
  • CARD_NUM - the credit card number;
  • CARD_EXP_MONTH - the month of the credit card expiration;
  • CARD_EXP_YEAR - the year of the credit card expiration;
  • DESCRIPTION - brief description;
  • SUM_MIN - minimum amount which can be withdrawn from the card within a single transaction;
  • SUM_MAX - maximum amount which can be withdrawn from the card within a single transaction;
  • SUM_CURRENCY - the currency of the minimum/maximum amounts;
  • LAST_STATUS - the status of the last card usage;
  • LAST_STATUS_CODE - the ID of the status of the last card usage;
  • LAST_STATUS_DESCRIPTION - the description of the status of the last card usage;
  • LAST_STATUS_MESSAGE - the response received from the payment system;
  • LAST_SUM - the last amount withdrawn from the card;
  • LAST_CURRENCY - the currency of the last amount withdrawn from the card;
  • ACTIVE - active state flag;
  • TIMESTAMP_X - the date when the credit card information was last modified;
  • LAST_DATE - the date when the credit card was last used.

If an empty array is passed as an arGroupBy parameter, the method will return the number of records satisfying the filter.


IdentifyCardType

CSaleUserCards::IdentifyCardType

string
CSaleUserCards::IdentifyCardType(
 string ccNum
);

The method IdentifyCardType returns the type of the credit card by its number.

Parameters

Parameter | Description
ccNum | The credit card number.

Return Values

Returns the type of the credit card.

Example

<?
// Save the information about the current user's new card

if (CSaleUserCards::CheckPassword())
{
    $arFields = array(
            "USER_ID" => $USER->GetID(),
            "ACTIVE" => "Y",
            "SORT" => "100",
            "PAY_SYSTEM_ACTION_ID" => 11,
            "CURRENCY" => "USD",
            "CARD_TYPE" => CSaleUserCards::IdentifyCardType("4111111111111"),
            "CARD_NUM" => CSaleUserCards::CryptData("4111111111111", "E"),
            "CARD_EXP_MONTH" => 11,
            "CARD_EXP_YEAR" => 2007,
            "DESCRIPTION" => False,
            "CARD_CODE" => "123",
            "SUM_MIN" => False,
            "SUM_MAX" => False,
            "SUM_CURRENCY" => False
        );

    $UserCardID = CSaleUserCards::Add($arFields);
}
?>


Update

CSaleUserCards::Update

int
CSaleUserCards::Update(
 int ID,
 array arFields
);

The method Update modifies the information about a new user credit card.

Parameters

Parameter | Description
ID | The ID of the record to modify.
arFields Associated array containing new parameters of the credit card with the following keys:
  • USER_ID - the user ID;
  • SORT - sort weight;
  • PAY_SYSTEM_ACTION_ID - the ID of the payment system handler;
  • CURRENCY - the currency in which money can be withdrawn;
  • CARD_CODE - the CVC2 code;
  • CARD_TYPE - the type of the card;
  • CARD_NUM - the credit card number;
  • CARD_EXP_MONTH - the month of the credit card expiration;
  • CARD_EXP_YEAR - the year of the credit card expiration;
  • DESCRIPTION - brief description;
  • SUM_MIN - minimum amount which can be withdrawn from the card within a single transaction;
  • SUM_MAX - maximum amount which can be withdrawn from the card within a single transaction;
  • SUM_CURRENCY - the currency of the minimum/maximum amounts;
  • LAST_STATUS - the status of the last card usage;
  • LAST_STATUS_CODE - the ID of the status of the last card usage;
  • LAST_STATUS_DESCRIPTION - the description of the status of the last card usage;
  • LAST_STATUS_MESSAGE - the response received from the payment system;
  • LAST_SUM - the last amount withdrawn from the card;
  • LAST_CURRENCY - the currency of the last amount withdrawn from the card;
  • ACTIVE - active state flag;
  • LAST_DATE - the date when the credit card was last used.

Note
The credit card number must be encrypted using the CSaleUserCards::CryptData method before adding the record.

Return Values

The method returns the ID of the modified record on success, or false otherwise.


CSaleUserTransact

The CSaleUserTransact class is used with transactions.

Methods

Method | Description
Delete | The method deletes the specified transaction.
GetByID | The method returns parameters of the specified transaction.
Add | The method adds a new specified transaction.
Update | The method modifies parameters of the specified transaction.
GetList | The method returns records containing information about transactions according to the specified criteria.


Add

CSaleUserTransact::Add

int
CSaleUserTransact::Add(
 array arFields
);

The method Add adds a new specified transaction.

Parameters

Parameter Description
arFields Associated array containing parameters of a new transaction. The array has the following keys:
  • USER_ID - the user ID;
  • AMOUNT - the amount;
  • CURRENCY - the currency of the amount;
  • DEBIT - "Y" places money to an account, "N" withdraws money from an account;
  • DESCRIPTION - the description;
  • ORDER_ID - the order ID (if applicable);
  • EMPLOYEE_ID - the ID of the user who performed the transaction;
  • TRANSACT_DATE - the date of the transaction.

Return Values

The method returns the ID of the added transaction on success, or false otherwise.


Delete

CSaleUserTransact::Delete

bool
CSaleUserTransact::Delete(
 int ID
);

The method Delete deletes the specified transaction.

Parameters

-
Parameter | Description
ID | The ID of the transaction to be deleted.

Return Values

The method returns true on success, or false otherwise.


GetByID

CSaleUserTransact::GetByID

array
CSaleUserTransact::GetByID(
 int ID
);

The method GetByID returns parameters of the specified transaction.

Parameters

Parameter | Description
ID | The transaction ID.

Return Values

The method returns an associated array containing parameters of the transaction with the following keys:

  • ID - the transaction ID;
  • USER_ID - the user ID;
  • AMOUNT - the amount;
  • CURRENCY - the currency of the amount;
  • DEBIT - "Y" places money to an account, "N" withdraws money from an account;
  • DESCRIPTION - the description;
  • ORDER_ID - the order ID (if applicable);
  • EMPLOYEE_ID - the ID of the user accomplished the transaction;
  • TIMESTAMP_X - the date when the record was last modified;
  • TRANSACT_DATE - the date of the transaction.


GetList

CSaleUserTransact::GetList

CDBResult
CSaleUserTransact::GetList(
 array arOrder = array(),
 array arFilter = array(),
 array arGroupBy = false,
 array arNavStartParams = false,
 array arSelectFields = array()
);

The method GetList returns records containing information about transactions according to the specified criteria.

Parameters

Parameter Description
arOrder Associated array used to sort the resulting records. The array has the following format:
array(
"field_name1" => "sort_order1",
"field_name2" => "sort_order2",
. . .
)
The fields field_nameN can be any field of a transaction. The sort_orderX can be either "ASC" (ascending) or "DESC" (descending).

If the sorting array has more than one elements, the resulting list is sorted by each element in series (i.e. the list is first sorted by the first element, then the result is sorted by the second element etc).

The default value is an empty array() which means that the result will not be sorted.
arFilter Associated array used to filter the records of transactions. The array has the following format:
array(
"[modifier1][operator1]field_name1" => "value1",
"[modifier2][operator2]field_name2" => "value2",
. . .
)
Records satisfying the filter conditions are returned as a result, others are truncated.

The following modifiers are possible:
  • ! - negation;
  • + - values null, 0 and empty string also satisfy the filter conditions.
The following operators are possible:
  • >= - the field value is more than or equal to that passed in the filter;
  • > - the field value is more than that passed in the filter;
  • <= - the field value is less than or equal to that passed in the filter;
  • < - the field value is less than that passed in the filter;
  • @ - the field value is stored in the list of comma separated values passed in the filter;
  • ~ - the field value is matched against the wildcard passed to the filter;
  • % - the field value is matched (according to the query language) against the string passed to the filter.
The fields field_nameX can be name of any field containing information about a transaction.

Example:
array("USER_ID" => 150)
This filter tells to "return all records with the value 150 in the USER_ID field".

The default value is an empty array() which means that the result will not be filtered.
arGroupBy Associated array used to group the records of transactions. The array has the following format:
array("field_name1",
      "grouping_function2" => "field_name2", . . .)
The fields field_nameN can be any field containing information about a transaction. The grouping_functionX can be one of the following:
  • COUNT - quantity counting;
  • AVG - calculation of the average value;
  • MIN - calculation of the minimum value;
  • MAX - calculation of the maximum value;
  • SUM - calculation of the total value.
If the array is empty, the method will return the number of records satisfying the filter.

The default value is false which means that the result will not be grouped.
arNavStartParams Array of the selection parameters. The following keys are possible in this array:
  • "nTopCount" - number of records returned by the method will be limited to the value of this key;
  • any key that can be passed to CDBResult::NavQuery in the third parameter.
The default value is false which means that no parameter is given.
arSelectFields Array of record fields that will be returned by the method. You may specify the required fields only. If the array contains the value of "*", all available fields will be returned.

The default value is an empty array() which means that all the fields of the main query table will be returned.

Return Values

The method returns an instance of the CDBResult class, containing the list of associated arrays with parameters of transactions:

  • ID - the transaction ID;
  • USER_ID - the user ID;
  • AMOUNT - the amount;
  • CURRENCY - the currency of the amount;
  • DEBIT - "Y" places money to an account, "N" withdraws money from an account;
  • DESCRIPTION - the description;
  • ORDER_ID - the order ID (if applicable);
  • EMPLOYEE_ID - the ID of the user who performed the transaction;
  • TIMESTAMP_X - the date when the record was last modified;
  • TRANSACT_DATE - the date of the transaction;
  • USER_LOGIN - the user login;
  • USER_ACTIVE - active state flag;
  • USER_NAME - the user first name;
  • USER_LAST_NAME - the user last name;
  • USER_EMAIL - the user e-mail.

If an empty array is passed as an arGroupBy parameter, the method will return the number of records satisfying the filter.


Update

CSaleUserTransact::Update

int
CSaleUserTransact::Update(
 int ID,
 array arFields
);

The method Update modifies parameters of the specified transaction.

Parameters

Parameter | Description
ID | The ID of the transaction to modify.
arFields Associated array containing new parameters of the transaction. The array has the following keys:
  • USER_ID - the user ID;
  • AMOUNT - the amount;
  • CURRENCY - the currency of the amount;
  • DEBIT - "Y" places money to an account, "N" withdraws money from an account;
  • DESCRIPTION - the description;
  • ORDER_ID - the order ID (if applicable);
  • EMPLOYEE_ID - the ID of the user who performed the transaction;
  • TRANSACT_DATE - the date of the transaction.

Return Values

The method returns the ID of the modified transaction on success, or false otherwise.


SaleFormatCurrency

string
SaleFormatCurrency(
 float fSum,
 string strCurrency
);

Formats the sum fSum according to the formatting rules that the system provides for the currency strCurrency in the current language.

Parameters

Parameter | Description
fSum | The amount of money to be formatted.
strCurrency | The currency whose rules are to be used for formatting.

Return Values

Returns the formatted string

Example

<?
echo SaleFormatCurrency(11800.95, "USD");
?>


Notes for developers

Before you start calling any of the module functions or use its classes, you should check its availability and include it using the following code:

<?
if(CModule::IncludeModule("forum"))
{
   // call module functions here
}
?>

The public section of the forum is built on the module classes and high-level functions.


The Forum module tables

Forum Groups

Field | Description | Type | Required | Default
ID | The forum group ID. Unique. | Int | Yes |
SORT | Sort weight. | Int | Yes | 150

Site-dependent parameters of the forum groups

Field | Description | Type | Required | Default
FORUM_GROUP_ID | The forum group ID | Int | Yes |
LID | The site ID | Char(2) | Yes |
NAME | Name of the forum group | String(255) | Yes |
DESCRIPTION | Description of the forum group | String(255) | No |

Forums

Field | Description | Type | Required | Default
ID | The forum ID. Unique. | Int | Yes |
NAME | The forum name. | String(128) | Yes |
DESCRIPTION | The forum description. | String(255) | No |
SORT | Sort weight | Int | Yes | 150
ACTIVE | Specifies the forum is active (Y|N) | Char(1) | Yes | Y
ALLOW_HTML | Allow HTML in messages (Y|N) | Char(1) | Yes | N
ALLOW_NL2BR | Convert carriage returns to <br> in HTML mode (Y|N) | Char(1) | Yes | N
ALLOW_ANCHOR | Allow tags <a> / [a] (Y|N) | Char(1) | Yes | Y
ALLOW_BIU | Allow tags <b> / [b], <i> / [i], <u> / [u] (Y|N) | Char(1) | Yes | Y
ALLOW_IMG | Allow tag <img> / [img] (Y|N) | Char(1) | Yes | Y
ALLOW_LIST | Allow tag <ul> / [list] (Y|N) | Char(1) | Yes | Y
ALLOW_QUOTE | Allow tag <quote> / [quote] (Y|N) | Char(1) | Yes | Y
ALLOW_CODE | Allow tag <code> / [code] (Y|N) | Char(1) | Yes | Y
ALLOW_FONT | Allow tag <font> / [color], [font] (Y|N) | Char(1) | Yes | Y
ALLOW_SMILES | Allow smiley images (Y|N) | Char(1) | Yes | Y
ALLOW_UPLOAD | Allow uploading files attached to messages. Possible values: N - deny upload, Y - only images, F - files with extensions specified in ALLOW_UPLOAD_EXT, A - all files. | Char(1) | Yes | N
MODERATION | Specifies the forum is pre-moderated (Y|N) | Char(1) | Yes | N
ORDER_BY | Default sorting of the forum topics. Possible values: T - topic title, N - number of messages, A - author, V - topic views, D - creation date, P - the date of the last message. | Char(1) | Yes | P
ORDER_DIRECTION | Default sort order of the forum topics. Possible values: ASC - ascending, DESC - descending. | Char(4) | Yes | DESC
TOPICS | Number of topics in the forum. | Int | Yes | 0
POSTS | Number of posts in the forum | Int | Yes | 0
LAST_POSTER_ID | The ID of the last message author. | Int | No |
LAST_POSTER_NAME | The name of the last message author. | String(64) | No |
LAST_POST_DATE | The date of the last message.. | DateTime | No |
LAST_MESSAGE_ID | The ID of the last message. | Int | No |
ALLOW_UPLOAD_EXT | Comma-separated extensions of files allowed to be uploaded. Applicable if only ALLOW_UPLOAD is "F". | String(255) | No |
FORUM_GROUP_ID | The forum group ID. | Int | No |
ASK_GUEST_EMAIL | Require the e-mail address to be provided by unregistered authors (Y/N) | Char(1) | No | N

Forum and site relation

Field | Description | Type | Required | Default
FORUM_ID | The forum ID. | Int | Yes |
SITE_ID | The site ID. | Char(2) | Yes |
PATH2FORUM_MESSAGE | Forum message path template. Can contain macros #FORUM_ID#, #TOPIC_ID#, #MESSAGE_ID# which must be replaced with the real forum ID, topic ID and message ID. | varchar(250) | No |

Forum topics

Field | Description | Type | Required | Default
ID | The forum topic ID. Unique. | Int | Yes |
TITLE | The topic title. | String(70) | Yes |
DESCRIPTION | The topic description. | String(70) | No |
STATE | The topic status: open or closed (Y|N). | Char(1) | Yes | Y
USER_START_ID | The topic author ID. | Int | No |
USER_START_NAME | The topic author name. | String(64) | Yes |
START_DATE | The topic creation date. | DateTime | Yes |
ICON_ID | The topic icon ID. | Int | No |
POSTS | Number of replies (posts). | Int | Yes | 0
VIEWS | Number of views. | Int | Yes | 0
FORUM_ID | The parent forum ID. | Int | Yes |
APPROVED | Specifies the topic is published (Y|N). The topic is published if it contains at least one post. | Char(1) | Yes | Y
SORT | Sort weight. | Int | Yes | 150
LAST_POSTER_ID | The ID of the last message author. | Int | No |
LAST_POSTER_NAME | The name of the last message author. | String(64) | Yes |
LAST_POST_DATE | The date of the last message.. | DateTime | Yes |
LAST_MESSAGE_ID | The ID of the last message. | Int | Yes |

Posts (forum messages)

Field | Description | Type | Required | Default
ID | The post ID. Unique. | Int | Yes |
AUTHOR_ID | The post author ID. | Int | No |
AUTHOR_NAME | The post author name. | String(128) | Yes |
AUTHOR_IP | The post author ID. | String(128) | No |
USE_SMILES | The user chooses to replace text smileys with icons (Y|N). | Char(1) | Yes | Y
POST_DATE | The date the post is created. | Datetime | Yes |
POST_MESSAGE | The post text. | Text | Yes |
FORUM_ID | The ID of the forum in which the post occurred. | Int | Yes |
TOPIC_ID | The ID of the topic in which the post occurred. | Int | Yes |
APPROVED | The post is published (Y|N) | Char(1) | Yes | Y
GUEST_ID | The visitor ID. | Int | No |
AUTHOR_REAL_IP | The real IP of the post author. | Int | No |
ATTACH_IMG | Attachment. | Int | No |

Forum user profile

Field | Description | Type | Required | Default
ID | The profile ID. Unique. | Int | Yes |
USER_ID | The user ID. Unique. | Int | Yes |
DESCRIPTION | The user description. | String(64) | No |
IP_ADDRESS | The IP address from which the last message was sent. | String(128) | Yes |
AVATAR | The avatar. | Int | No |
NUM_POSTS | Total number of posts. | Int | Yes | 0
INTERESTS | The user personal information (text). | Text | No |
LAST_POST | The ID of the last message created by the user. | Int | No |
ALLOW_POST | The user is not banned. | Char(1) | Yes | Y
LAST_VISIT | The date of the last visit. | DateTime | Yes |
DATE_REG | The date the user was registered. | DateTime | Yes |
REAL_IP_ADDRESS | The real IP address used to create the last message. | String(128) | No |
SIGNATURE | Signature text. | String(255) | No |
SHOW_NAME | Denotes to show name instead of login (Y|N) | Char(1) | Yes | Y
HIDE_FROM_ONLINE | Do not show in the "Who is online" list (Y/N) | Char(1) | No | N
POINTS | Current points count. | Int | No | 0

User ranks

Field | Description | Type | Required | Default
ID | The user rank ID. Unique. |  | Yes |
MIN_POINTS | Number of points required to gain this rank. | Int | Yes | 0
CODE | Mnemonic code of the rank. | varchar(100) | No |
VOTES | Number of votes that a user in this rank can give to other users. | Int | Yes | 0

Language parameters of points

Field | Description | Type | Required | Default
POINTS_ID | The rank ID. | Int | Yes |
LID | The language ID. | Char(2) | Yes |
NAME | The rank name. | String(250) | Yes |

Point-per-post lookup table

Field | Description | Type | Required | Default
ID | The primary record ID. | Int | Yes |
MIN_NUM_POSTS | Number of messages required to gain this number of points per message. | Int | Yes | 0
POINTS_PER_POST | Number of points per message. Can be fractional. | decimal(18, 4) | Yes | 0

Smileys and icons

Field | Description | Type | Required | Default
ID | The smiley ID. Unique. |  | Yes |
TYPE | The smiley type: S - smiley, I - icon. | Char(2) | Yes | S
TYPING | Smiley text variants. Separated with spaces. | String(100) | Yes |
IMAGE | The image name. | String(128) | Yes |
SORT | Sort weight. | Int | Yes | 150
IMAGE_WIDTH | Image width. | Int | Yes | 0
IMAGE_HEIGHT | Image height. | Int | Yes | 0

Language parameters of smileys

Field | Description | Type | Required | Default
SMILE_ID | The smiley ID. | Int | Yes |
LID | The language ID. | Char(2) | Yes |
NAME | The smiley name. | String(255) | Yes |

Subscription

Field | Description | Type | Required | Default
ID | The subscription ID. | Int | Yes |
USER_ID | The subscriber ID. | Int | Yes |
FORUM_ID | The ID of the forum whose messages a subscriber wants to receive. | Int | Yes |
TOPIC_ID | The ID of the topic whose messages a subscriber wants to receive. | Int | No |
START_DATE | The date of subscription. | DateTime | Yes |
LAST_SEND | The ID of the last message sent. | Int | No |
NEW_TOPIC_ONLY | Subscribed to new topics only (Y/N) | Char(1) | Yes | N
SITE_ID | The ID of the site from which the subscription has been made. | Char(2) | Yes | en

Private messages

Field | Description | Type | Required | Default
ID | The unique message ID. | Int | Yes |
AUTHOR_ID | The message author ID. | Int | Yes |
USER_ID | The message recipient user ID. | Int | Yes |
FOLDER_ID | The user folder ID. | Int | Yes |
IS_READ | Indicates that the message is read. | Int | Yes |
USE_SMILES | Replace text smileys with images (Y|N). | Int | Yes |
POST_DATE | The date the message was created. | DateTime | Yes |
POST_SUBJ | The message subject. | String(255) | No |
POST_MESSAGE | The message body. | Text | No |

User folders

Field | Description | Type | Required | Default
ID | The unique folder ID. | Int | Yes |
TITLE | The message author ID. | String(50) | Yes |
USER_ID | The folder owner ID. | Int | Yes |

Dictionary of obscene words

Field | Description | Type | Required | Default
ID | The unique record ID. | Int | Yes |
TITLE | The dictionary name. | String(50) | Yes |
TYPE | The dictionary type. | Char | Yes |

Dictionary of letters

Field | Description | Type | Required | Default
ID | The unique record ID. | Int | Yes |
DICTIONARY_ID | The dictionary ID. | Int | Yes |
LETTER | The original letter to be substituted. | String(50) | Yes |
REPLACEMENT | The replacement letter. | String(50) | Yes |

Dictionary of unquotable words

Field | Description | Type | Required | Default
ID | The unique record ID. | Int | Yes |
DICTIONARY_ID | The dictionary ID. | Int | Yes |
WORDS | A word. | String(255) | No |
PATTERN | A pattern which would match words under this dictionary record. | String(255) | No |
REPLACEMENT | A word with which the matching words will be replaced. | String(255) | No |
DESCRIPTION | The description. | Text | No |
REPLACEMENT | The replacement word. | String(50) | Yes |
USE_IT | Use this pattern (Y|N). | Char | Yes |


Classes

The following PHP classes are used with forums.

Classes

Class | Description
CForumNew | Main forum class. Used to create, delete and obtain information about forums.
CForumTopic | Used with forum topics.
CForumPoints | Used with forum ranks and points.
CForumPoints2Post | Used to manage the point-per-message lookup table.
CForumUserPoints | Used to handle votes that the forum users give to each other.
CForumUser | Manages user profiles
CFilterDictionary | Used with dictionaries of obscene words.
CFilterLetter | Used with transliteration dictionaries.
CFilterUnquotableWords | Used with dictionaries of words.
CForumPMFolder | Used with user folders.
CForumPrivateMessage | Used with private messages.


Класс CFilterDictionary

CFilterDictionary

The CFilterDictionary class is used with dictionaries of obscene words.

Methods

Method | Description
Add | Adds a new dictionary.
Delete | Deletes an existing dictionary.
GetList | Returns a selection of filtered and sorted folders.
Update | Modifies the parameters of an existing dictionary.
© 2001-2007 Bitrix Bitrix Site Manager


Add

CFilterDictionary::Add

int
Add(
 array arFields
);

The Add method adds a new dictionary with parameters specified in the arFields array.

Parameters

Parameter Description
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the Dictionary table. The required fields must be present.

Return Values

The method returns the ID of the created record on success, or false otherwise.

See Also

Dictionary table fields

Example

<?
$arFields = Array(
    TITLE        - > $TITLE,
    TYPE      - > $TYPE,
);

$ID = CFilterDictionary::Add($arFields);

if (IntVal($ID)<=0)
    echo "Error!";
?>
© 2001-2007 Bitrix Bitrix Site Manager


Delete

CFilterDictionary::Delete

bool
Delete(
 int ID
);

The Delete method deletes a folder ID.

Parameters

Parameter | Description
ID | The ID of the record to be deleted.

Return Values

The method returns true on success, or false otherwise.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CFilterDictionary::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter [,
 bool bCount ]]]
);

The GetList method returns a selection of folders filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - filter field, can have the following values:
    • ID - the record ID;
    • TITLE - the name of the dictionary;
    • TYPE - the dictionary type;
  • order - sort order, can have the following values:
    • ASC - ascending;
    • DESC - descending;
Optional. The default value is Array("ID"=>"ASC").
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the record ID;
  • TITLE - the name of the dictionary;
  • TYPE - the dictionary type.
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Required.
bCount | If set to true, the method returns a number of records matching with the filter. Optional. False by default.

Return Values

The method returns an instance of the CDBResult object.

See Also

CDBResult
Dictionary table fields

© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CFilterDictionary::Update

int
Update(
 int ID,
 array arFields
);

The Update method replaces parameters of an existing dictionary ID with those specified in the arFields array.

Parameters

Parameter | Description
ID | The ID of the record whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the Dictionary table.

Return Values

The method returns the ID of modified dictionary on success, or false otherwise.

See Also

Dictionary table fields

© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Класс CFilterLetter

CFilterLetter

The CFilterLetter class is used with transliteration dictionaries.

Methods

Method | Description
Add | Creates a new record (installs the mapping of one symbol to another).
Delete | Deletes a record.
GetList | Returns a selection of filtered and sorted mappings.
Update | Modifies the record parameters.
© 2001-2007 Bitrix Bitrix Site Manager


Add

CFilterLetter::Add

int
Add(
 array arFields
);

The Add method creates a new record (installs the mapping of one symbol to another) with parameters specified in the arFields array.

Parameters

Parameter Description
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the Transliteration dictionary table. The required fields must be present.

Return Values

The method returns the ID of the created record on success, or false otherwise.

See Also

Transliteration dictionary table

© 2001-2007 Bitrix Bitrix Site Manager


Delete

CFilterLetter::Delete

bool
Delete(
 int ID
);

The Delete method deletes a specified record ID.

Parameters

Parameter | Description
ID | The ID of the record to be deleted.

Return Values

The method returns true on success, or false otherwise.

© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CFilterLetter::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter [,
 bool bCount ]]]
);

The GetList method returns a selection of records filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - field by which the selection is to be sorted; can have the following values:
    • ID - the message ID;
    • LETTER - the letter name;
    • DICTIONARY_ID - the dictionary ID;
  • order - sort order, can have the following values:
    • ASC - ascending;
    • DESC - descending;
Optional. The default value is Array("ID"=>"ASC").
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the message ID;
  • LETTER - the letter name;
  • DICTIONARY_ID - the dictionary ID;
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Required.
bCount | If set to true, the method returns the number of messages that match the filter. Optional. False by default.

Return Values

The method returns an instance of the CDBResult object.

See Also

CDBResult
Dictionary table
Transliteration dictionary table

© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CFilterLetter::Update

int
Update(
 int ID,
 array arFields
);

The Update method modifies the parameters of an existing record ID with those specified in the arFields array.

Parameters

Parameter | Description
ID | The ID of the record whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where:
  • field - field name;
  • value - field value.
The fields are listed in the Transliteration dictionary table.

Return Values

The method returns the ID of modified record on success, or false otherwise.

See Also

Transliteration dictionary table

© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Класс CFilterUnquotableWords

CFilterUnquotableWords

The CFilterUnquotableWords class is used with dictionaries of words.

Methods

Method | Description
Add | Creates a new record.
Delete | Deletes a record.
GetList | Returns a list of filtered and sorted records.
Update | Modifies the parameters of existing record.
© 2001-2007 Bitrix Bitrix Site Manager


Add

CFilterUnquotableWords::Add

int
Add(
 array arFields
);

The Add method creates a new record with parameters specified in arFields.

Parameters

Parameter Description
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the Word dictionary table. The required fields must be present.

Return Values

The method returns the ID of the created record on success, or false otherwise.

See Also

  • Word dictionary table
    © 2001-2007 Bitrix Bitrix Site Manager


Delete

CFilterUnquotableWords::Delete

bool
Delete(
 int ID
);

The Delete method deletes a record identified by the ID.

Parameters

Parameter | Description
ID | The ID of the record to be deleted.

Return Values

The method returns true on success, or false otherwise.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CFilterUnquotableWords::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter [,
 bool bCount ]]]
);

The GetList method returns a selection of records filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - field by which the selection is to be sorted ; can have the following values:
    • ID - the message ID;
    • WORDS - a word;
    • PATTERN - a pattern which would match words under this dictionary record;
    • REPLACEMENT - a word with which the matching words will be replaced;
    • DESCRIPTION - the description;
    • USE_IT - use this pattern in filter;
  • order - sort order, can have the following values:
    • ASC - ascending;
    • DESC - descending;
Optional. The default value is Array("ID"=>"ASC").
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the message ID;
  • DICTIONARY_ID - the dictionary ID;
  • WORDS - a word;
  • PATTERN - a pattern which would match
  • words under this dictionary record;
  • REPLACEMENT - a word with which the
  • matching words will be replaced;
  • DESCRIPTION - the description;
  • USE_IT - use this pattern in filter;
The following logic can be specified at the beginning of the field name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Required.
bCount | If set to true, the method returns the number of messages that match the filter. Optional. False by default.

Return Values

The method returns an instance of the CDBResult object.

See Also

CDBResult
Dictionary table
Letter dictionary table
Word dictionary table

© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CFilterUnquotableWords::Update

int
Update(
 int ID,
 array arFields
);

The Update method replaces parameters of an existing record ID with those specified in the arFields array.

Parameters

Parameter | Description
ID | The ID of the record whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the Word dictionary table.

Return Values

The method returns the ID of modified record on success, or false otherwise.

See Also

Word dictionary table

© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CForumGroup

The CForumGroup class is used with groups of forums.

Method

Method | Description
GetList | Returns an optionally filtered and sorted list of groups.
GetByID | Returns an array of the language-independent parameters of a group by its ID.
GetByIDEx | Returns an array of all the parameters of the group by the ID and language.
GetLangByID | Returns an array of language parameters of a group by the ID and language.
Add | Creates a new group.
Update | Modifies the parameters of a group.
Delete | Deletes a group.


Add

CForumGroup::Add

int
Add(
 array arFields
);

The method Add creates a new group with parameters specified in the array arFields. Returns the ID of the created group. Parameters of the forum visitors are not changed at once when a new rank is added, but gradually, as the visitors post new messages in the forum.

Parameters

Parameter | Description
arFields | An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where field - field name; value - field value. The fields are listed in the List of group fields. The "LANG" special field may be set to an array of arrays containing the fields with language parameters of a group. These arrays have the similar structure.

Return Values

Returns the ID of the created group on success, or false otherwise.

See Also

  • Fields of a group

    Example

<?
$arFields = array("SORT" => $SORT);
$arSysLangs = array("fr", "en");
for ($i = 0; $i<count($arSysLangs); $i++)
{
  $arFields["LANG"][] = array(
    "LID" => $arSysLangs[$i],
    "NAME" => ${"NAME_".$arSysLangs[$i]},
    "DESCRIPTION" => ${"DESCRIPTION_".$arSysLangs[$i]}
    );
}
$ID = CForumGroup::Add($arFields);
if (IntVal($ID)<=0)
  echo "Error!";
?>


Delete

CForumGroup::Delete

bool
Delete(
 int ID
);

The method Delete deletes a specified group. If any forums are bound to the specified group, the latter is not deleted.

Parameters

Parameter | Description
ID | The ID of the group to be deleted.

Return Values

Returns true on success, or false otherwise.


GetByID

CForumGroup::GetByID

array
GetByID(
 int ID
);

The method GetByID returns an array of the language-independent parameters of a group by its ID.

Parameters

Parameter | Description
ID | The group ID.

Return Values

Array of language-independent parameters of a group. If the group can not be found, the method returns false.

See Also

  • Fields of a group


GetByIDEx

CForumGroup::GetByIDEx

array
GetByIDEx(
 int ID,
 char(2) LANG
);

The method GetByIDEx returns an array of all the parameters of the group by the ID and language.

Parameters

Parameter | Description
ID | The group ID.
LANG | The site.

Return Values

Array of all the parameters of the group including language dependent ones. If the group cannot be found, the method returns false.

See Also

  • Fields of a group


GetLangByID

CForumGroup::GetLangByID

array
GetLangByID(
 int GROUP_ID,
 char(2) LANG
);

The method GetLangByID returns an array of language parameters of a group by the ID and language.

Parameters

Parameter | Description
GROUP_ID | The group ID.
LANG | The site.

Return Values

Array of language dependent parameters of the group. If the group cannot be found, the method returns false.

See Also

  • Fields of a group


GetList

CForumGroup::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter]]
);

The method GetList returns an optionally filtered and sorted list of groups.

Parameters

Parameter Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - the field by which the list is to be sorted. The following values are possible:
    • ID - the group ID;
    • SORT - sort index;
  • order - sort order. The following values are possible:
    • ASC - ascending;
    • DESC - descending.
Optional. The default value is Array("sort"=>"asc").
arFilter An array of the format Array("filtered field"=>"filter value" [, ...]).

The "filtered field" can be one of the following:
  • ID - by the ID;
  • SORT - sort index.
The filtered field may contain one of the following filter check specifiers before the name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Optional. By default, records are not filtered.

Return Values

Returns an object of the CDBResult class.

See Also

  • CDBResult
  • Fields of an element


Update

CForumGroup::Update

int
Update(
 int ID,
 array arFields
);

The method Update modifies the parameters of the existing group specified by the ID. Returns the ID of the modified group.

Parameters

Parameter | Description
ID | The ID of the group whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where:
  • field - field name;
  • value - field value.
The fields are listed in the List of group fields. The "LANG" special field may be set to an array of arrays containing the fields with language parameters of a group. These arrays have the similar structure.

Return Values

Returns the ID of the modified group on success, or false otherwise.

See Also

  • Fields of a group

    Example

<?
$arFields = array("SORT" => $SORT);
$arSysLangs = array("fr", "en");
for ($i = 0; $i<count($arSysLangs); $i++)
{
  $arFields["LANG"][] = array(
    "LID" => $arSysLangs[$i],
    "NAME" => ${"NAME_".$arSysLangs[$i]},
    "DESCRIPTION" => ${"DESCRIPTION_".$arSysLangs[$i]}
    );
}
$ID1 = CForumGroup::Update($ID, $arFields);
if (IntVal($ID1)<=0)
  echo "Error!";
?>


CForumMessage

The CForumMessage class is used with forum messages.

Methods

Method | Description
GetList | Returns a filtered and sorted list of messages.
GetListEx | Returns a filtered and sorted list of messages including all bound data .
GetByID | Returns an array of message parameters by its ID.
GetByIDEx | Returns an array of message parameters and auxiliary parameters by its ID.
Add | Adds a new message.
Update | Modifies the parameters of the existing message specified by the ID.
Delete | Deletes a specified message.
CanUserAddMessage | Thoroughly checks whether a specified user can add a new message into a specified topic.
CanUserUpdateMessage | Thoroughly checks whether a specified user can modify a specified message.
CanUserDeleteMessage | Thoroughly checks whether a specified user can delete a specified message.
GetMessagePage | Returns a page containing the specified message. The page returned is set up for pagewise navigation.


Add

CForumMessage::Add

int
Add(
 array arFields [,
 string strUploadDir]
);

The method Add adds a new message. Returns the ID of the created message.

Parameters

Parameter | Description
arFields | An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where field - field name; value - field value. Fields are listed in the List of message fields. The required fields must be filled.
strUploadDir | Directory in which files are to be uploaded. Must be specified relative to the main upload directory. Optional. The default value is "forum".

Return Values

Returns the ID of the created message on success, or false by default.

See Also

  • Message fields
  • Before a message is created, you should check whether it can be added using CForumMessage::CanUserAddMessage. It is recommended to add and modify messages and message subjects using the method ForumAddMessage.

    Example

<?
$arFields = Array(
  "POST_MESSAGE" => $POST_MESSAGE,
  "USE_SMILES" => ($USE_SMILES=="Y") ? "Y" : "N",
  "APPROVED" => $APPROVED
  "AUTHOR_NAME" => $AUTHOR_NAME,
  "AUTHOR_ID" => $AUTHOR_ID,
  "FORUM_ID" => $FID,
  "TOPIC_ID" => $TID,
  "AUTHOR_IP" => ($AUTHOR_IP!==False) ? $AUTHOR_IP : "<no address>",
  "NEW_TOPIC" => "N"
);
$ID = CForumMessage::Add($arFields);
if (IntVal($ID)<=0)
  echo "Error!";
?>


CanUserAddMessage

CForumMessage::CanUserAddMessage

bool
CanUserAddMessage(
 int TID,
 array arUserGroups,
 int iUserID
);

The method CanUserAddMessage thoroughly checks whether a specified user who is a member of a specified group can add a new message into a specified topic.

Parameters

Parameter | Description
TID | The ID of the topic to which a user wants to add a message.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all the permissions required to add a message, or false otherwise.

See Also

  • CForumMessage::CanUserUpdateMessage
  • CForumMessage::CanUserDeleteMessage

    Example

<?
if (CForumMessage::CanUserAddMessage($TID, $USER->GetUserGroupArray(), $USER->GetID()))
{
    echo "You can add message!";
}
?>


CanUserDeleteMessage

CForumMessage::CanUserDeleteMessage

bool
CanUserDeleteMessage(
 int ID,
 array arUserGroups,
 int iUserID
);

The method CanUserDeleteMessage thoroughly checks whether a specified user who is a member of a specified group can delete a specified message.

Parameters

Parameter | Description
ID | The ID of the message which the user wants to delete.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all permissions required to delete a message, or false otherwise.

See Also

  • CForumMessage::CanUserAddMessage
  • CForumMessage::CanUserUpdateMessage

    Example

<?
if (CForumMessage::CanUserDeleteMessage($ID,
                                        $USER->GetUserGroupArray(),
                                        $USER->GetID()))
{
    CForumMessage::Delete($ID);
}
?>


CanUserUpdateMessage

CForumMessage::CanUserUpdateMessage

bool
CanUserUpdateMessage(
 int ID,
 array arUserGroups,
 int iUserID
);

The method CanUserUpdateMessage thoroughly checks whether a specified user who is a member of a specified group can modify a specified message.

Parameters

Parameter | Description
ID | The ID of the message that the user wants to modify.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all the permissions required to modify a message, or false otherwise.

See Also

  • CForumMessage::CanUserAddMessage
  • CForumMessage::CanUserDeleteMessage

    Example

<?
if (CForumMessage::CanUserUpdateMessage($ID, $USER->GetUserGroupArray(), $USER->GetID()))
{
    echo "You can modify this message!";
}
?>


Delete

CForumMessage::Delete

bool
Delete(
 int ID
);

The method Delete deletes a specified message.

Parameters

Parameter | Description
ID | The ID of the message to be deleted.

Return Values

Returns true on success, or false otherwise.

See Also

  • Before a message is deleted, you should check whether it can be deleted using CForumMessage::CanUserDeleteMessage.


GetByID

CForumMessage::GetByID

array
GetByID(
 int ID
);

The method GetByID returns an array of message parameters by its ID.

Parameters

Parameter | Description
ID | The message ID.

Return Values

An array of message parameters. If the massage can not be found, false is returned.

See Also

  • Message fields

    Example

<?
$arMessage = CForumMessage::GetByID($MID);
if ($arMessage)
{
  $TID = IntVal($arMessage["TOPIC_ID"]);
  $FID = IntVal($arMessage["FORUM_ID"]);
}
?>


GetByIDEx

CForumMessage::GetByIDEx

array
GetByIDEx(
 int ID
);

The method GetByIDEx returns an array of all the message parameters including auxiliary parameters by its ID.

Parameters

Parameter | Description
ID | The message ID.

Return Values

Array of message parameters including the auxiliary ones. If the message can not be found, the method returns false.

See Also

  • Message fields

    Example

<?
// Print all the returned message parameters
$arMessage = CForumMessage::GetByIDEx($MID);
if ($arMessage)
{
  echo "<pre>";
  print_r($arMessage);
  echo "</pre>";
}
?>


GetList

CForumMessage::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter [,
 bool bCount [,
 int iNum]]]]
);

The method GetList returns an optionally filtered and sorted list of messages.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:

by - the field by which the list is to be sorted. The following values are possible:
  • AUTHOR_NAME - the name of a message author;
  • POST_DATE - the date the message was created;
  • FORUM_ID - the forum ID;
  • TOPIC_ID - the topic ID;
  • APPROVED - the message is approved and published;
  • ID - the message ID.
order - sort order. The following values are possible:
  • ASC - ascending;
  • DESC - descending;
Optional. The default value is Array("ID"=>"ASC").
arFilter An array of the format array("filter field"=>"filter value" [, ...]).

The "filter field" can be one of the following:
  • ID - the message ID;
  • AUTHOR_NAME - the name of a message author;
  • AUTHOR_ID - the message author ID;
  • FORUM_ID - the forum ID;
  • TOPIC_ID - the topic ID;
  • APPROVED - the message is approved and published.
The filtered field may contain one of the following condition operators before the name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Optional. By default, records are not filtered.
bCount If parameter is true, only the number of messages that conforms to the specified filter is returned.
Optional. The default value is false.
iNum | Maximum number of records returned. If the parameter iNum is not zero, a maximum of iNum records is returned. Not all databases support this feature. If the feature is not supported, this parameter is ignored. Optional. The default value is 0.

Return Values

Returns an object of the CDBResult class.

See Also

  • CDBResult
  • Message fields

    Example

<?
// select all the published messages of the topic
// with the ID of $TID in the message creation order
$db_res = CForumMessage::GetList(array("ID"=>"ASC"),
                                 array("TOPIC_ID"=>$TID));
while ($ar_res = $db_res->Fetch())
{
  echo $ar_res["POST_MESSAGE"]."<br>";
}
?>


GetListEx

CForumMessage::GetListEx

CDBResult
GetListEx(
 [array arOrder [,
 array arFilter [,
 bool bCount [,
 int iNum]]]]
);

The method GetListEx returns a filtered and sorted list of messages including all bound data.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:

by - the field by which the list is to be sorted. The following values are possible:
  • AUTHOR_NAME - the name of a message author;
  • POST_DATE - the date the message was created;
  • FORUM_ID - the forum ID;
  • TOPIC_ID - the topic ID;
  • APPROVED - the message is approved and published;
  • ID - the message ID.
order - sort order. The following values are possible:
  • ASC - ascending;
  • DESC - descending;
Optional. The default value is Array("ID"=>"ASC").
arFilter An array of the format array("filter field"=>"filter value" [, ...]).

The "filter field" can be one of the following:
  • ID - the message ID;
  • AUTHOR_NAME - the name of a message author;
  • AUTHOR_ID - the message author ID;
  • FORUM_ID - the forum ID;
  • TOPIC_ID - the topic ID;
  • APPROVED - the message is approved and published.
The filtered field may contain one of the following condition operators before the name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Optional. By default, records are not filtered.
bCount If parameter is true, only the number of messages that conforms to the specified filter is returned.
Optional. The default value is false.
iNum | Maximum number of records returned. If the parameter iNum is not zero, a maximum of iNum records is returned. Not all databases support this feature. If the feature is not supported, this parameter is ignored. Optional. The default value is 0.

Return Values

Returns an object of the CDBResult class.

See Also

  • CDBResult
  • Message fields

    Example

<?
// select all the published messages of the topic
// with the ID of $TID in the reverse message creation order
$db_res = CForumMessage::GetListEx(array("ID"=>"DESC"), array("TOPIC_ID"=>$TID));
while ($ar_res = $db_res->Fetch())
{
  echo "<pre>";
  print_r($ar_res);
  echo "</pre><br>";
}
?>


GetMessagePage

CForumMessage::GetMessagePage

int
GetMessagePage(
 int ID,
 int mess_per_page,
 array arUserGroups
);

The method GetMessagePage returns a page containing a specified message of a user who is a member of the specified groups. The page returned is set up for pagewise navigation given the maximum number of messages per page.

Parameters

Parameter | Description
ID | The message ID.
mess_per_page | Number of messages per page. Usually equals to the variable $FORUM_MESSAGES_PER_PAGE defined in the Forum module. This variable is initialized within the Forum module settings.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().

Return Values

Number of page on which the message will be shown. If the message can not be found, the method returns false.

See Also

  • CDBResult::NavStart

    Example

<?
if ($MID>0)
  $db_Message->NavStart($FORUM_MESSAGES_PER_PAGE,
                        true,
                        CForumMessage::GetMessagePage($MID,
                                                      $FORUM_MESSAGES_PER_PAGE,
                                                      $USER->GetUserGroupArray()));
else
  $db_Message->NavStart($FORUM_MESSAGES_PER_PAGE);
?>


Update

CForumMessage::Update

int
Update(
 int ID,
 array arFields [,
 bool skip_counts [,
 string strUploadDir]]
);

The method Update modifies the parameters of the existing message specified by the ID. Returns the ID of the modified message.

Before a message is modified, you should check whether it can be modified using CForumMessage::CanUserUpdateMessage. It is recommended to add and modify messages and message subjects using the high level function ForumAddMessage.

Parameters

Parameter | Description
ID | The ID of the message whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where
  • field - field name;
  • value - field value.
The fields are listed in the List of message fields.
skip_counts If true, the statistical data is not updated when the message is modified. It speeds up the method execution but causes information to become somewhat logically inconsistent.

Optional. False by default.
strUploadDir Directory in which files are to be uploaded. Must be specified relative to the main upload directory.

Optional. The default value is "forum".

Return Values

Returns the ID of the modified message on success, or false otherwise.

See Also

  • Message fields


CForumNew

The CForumNew class is used with forums.

Methods

Method | Description
Add | Creates a new forum.
Delete | Deletes a specified forum.
CanUserAddForum | Thoroughly checks whether a specified user can add a new forum.
CanUserDeleteForum | Thoroughly checks whether a specified user can delete a forum.
CanUserUpdateForum | Thoroughly checks whether a specified user can modify a forum.
GetByID | Returns an array of forum parameters by its ID.
GetByIDEx | Returns an array of forum parameters and auxiliary parameters by its ID.
GetList | Returns a filtered and sorted list of forums.
GetListEx | Returns a filtered and sorted list of forums including all bound data.
GetSites | Returns an array of sites as well as templates of paths to forum posts on these sites.
Update | Modifies forum parameters.


Add

CForumNew::Add

int
Add(
 array arFields
);

The method Add creates a new forum with parameters specified in the array arFields. Returns the ID of the created forum.

Before a forum is added, you should check whether it can be added using CForumNew::CanUserAddForum.

Parameters

Parameter Description
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where
  • field - field name;
  • value - field value.
The fields are listed in the List of forum fields. Required fields must be filled.

Return Values

Returns the ID of the created forum on success, or false otherwise.

See Also

  • Forum fields


CanUserAddForum

CForumNew::CanUserAddForum

bool
CanUserAddForum(
 array arUserGroups,
 int iUserID
);

The method CanUserAddForum thoroughly checks whether a specified user who is a member of a specified group can add a new forum.

Parameters

Parameter | Description
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all permissions required to add a message, or false otherwise.

See Also

  • CForumNew::CanUserUpdateForum
  • CForumNew::CanUserDeleteForum


CanUserDeleteForum

CForumNew::CanUserDeleteForum

bool
CanUserDeleteForum(
 int ID,
 array arUserGroups,
 int iUserID
);

The method CanUserDeleteForum thoroughly checks whether a specified user who is a member of a specified group can delete a specified forum.

Parameters

Parameter | Description
ID | The ID of the forum that the user iUserID wants to delete.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all the permissions required to delete a forum, or false otherwise.

See Also

  • CForumNew::CanUserAddForum
  • CForumNew::CanUserUpdateForum


CanUserUpdateForum

CForumNew::CanUserUpdateForum

bool
CanUserUpdateForum(
 int ID,
 array arUserGroups,
 int iUserID
);

The method CanUserUpdateForum thoroughly checks whether a specified user who is a member of a specified group can modify a specified forum.

Parameters

Parameter | Description
ID | The ID of the forum that the user wants to modify.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all permissions required to modify a forum, or false otherwise.

See Also

  • CForumNew::CanUserAddForum
  • CForumNew::CanUserDeleteForum

    Example

<?
if (CForumNew::CanUserUpdateForum($ID,
                                  $USER->GetUserGroupArray(),
                                  $USER->GetID()))
{
    echo "You can modify this forum!";
}
?>


Delete

CForumNew::Delete

bool
Delete(
 int ID
);

The method Delete deletes a specified forum. Before the forum is deleted, the method calls all handlers of the Forum module event OnBeforeForumDelete. If at least one of the handlers returns false, the forum will not be deleted.

Parameters

Parameter | Description
ID | The ID of the forum to be deleted.

Return Values

Returns true on success, or false otherwise.

Remarks

  • Before a forum is deleted, you should check whether it can be deleted using CForumNew::CanUserDeleteForum.


GetByID

CForumNew::GetByID

array
GetByID(
 int ID
);

The method GetByID returns an array of forum parameters by its ID. The method call result is cached, therefore, the repeated calls with the same forum do not incur extra queries to the database (unless the cache is reset after the forum parameters are changed).

Parameters

Parameter | Description
ID | The forum ID.

Return Values

An array of forum parameters. If the forum cannot be found, false is returned.

See Also

  • Forum fields

    Example

<?
$arForum = CForumNew::GetByID($FID);
if ($arForum)
{
  echo $arForum["NAME"]."<br>";
}
?>


GetByIDEx

CForumNew::GetByIDEx

array
GetByIDEx(
 int ID
);

The method GetByIDEx returns an array of forum parameters as well as its auxiliary parameters by its ID.

Parameters

Parameter | Description
ID | The forum ID.

Return Values

Array of forum parameters including the auxiliary ones. If the forum can not be found, the method returns false.

See Also

  • Forum fields

    Example

<?
// Print all the returned forum parameters
$arForum = CForumNew::GetByIDEx($FID);
if ($arForum)
{
  echo "<pre>";
  print_r($arForum);
  echo "</pre>";
}
?>


GetList

CForumNew::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter]]
);

The method GetList returns a filtered and sorted list of forums.

Parameters

Parameter Description
arOrder An array in the format Array(by1=>order1[, by2=>order2 [, ..]]), where:

by - the field by which the list is to be sorted. The following values are possible:
  • ID - the forum ID;
  • LID - the forum language;
  • NAME - the forum name;
  • ACTIVE - active state;
  • MODERATION - specifies the forum is moderated;
  • FORUM_GROUP_ID - the forum group ID;
  • TOPICS - number of threads in the forum;
  • POSTS - number of posts in the forum;
  • LAST_POST_DATE - the date the last post was created;
  • SORT - sort index;
order - sort order. The following values are possible:
  • ASC - ascending;
  • DESC - descending;
Optional. The default value is Array("SORT"=>"ASC")
arFilter An array in the format array("filter field"=>"filter value" [, ...]). The "filter field" can be one of the following:
  • LID - the forum language;
  • ACTIVE - active state;
  • ID - the forum ID;
  • FORUM_GROUP_ID - the forum group ID;
  • TOPICS - number of threads in the forum;
  • POSTS - number of posts in the forum;
  • TEXT - entry in the forum name or description;
  • PERMS - access permission for the forum (an array of two indexes, the first is a list of user group ID's, and the second is the access permission code).
The filtered field may contain one of the following filter check specifiers before the name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Optional. By default, records are not filtered.

Return Values

Returns an instance of the CDBResult class.

See Also

  • CDBResult
  • Forum fields

    Example

<?
// Display a list of forums that the current user can at least read.
// First sort the list by sort index, then by the forum name
$arFilter = array();
if (!$USER->IsAdmin())
{
  $arFilter["PERMS"] = array($USER->GetGroups(), 'A');
  $arFilter["ACTIVE"] = "Y";
}
$arOrder = array("SORT"=>"ASC", "NAME"=>"ASC");
$db_Forum = CForumNew::GetList($arOrder, $arFilter);
while ($ar_Forum = $db_Forum->Fetch())
{
  echo $ar_Forum["NAME"]."<br>";
}
?>


GetListEx

CForumNew::GetListEx

CDBResult
GetListEx(
 [array arOrder [,
 array arFilter]]
);

The method GetListEx returns an optionally filtered and sorted list of forums including all bound data.

Parameters

Parameter Description
arOrder An array in the format Array(by1=>order1[, by2=>order2 [, ..]]), where:

by - the field by which the list is to be sorted. The following values are possible:
  • ID - the forum ID;
  • LID - the forum language;
  • NAME - the forum name;
  • ACTIVE - active state;
  • MODERATION - specifies the forum is moderated;
  • FORUM_GROUP_ID - the forum group ID;
  • TOPICS - number of threads in the forum;
  • POSTS - number of posts in the forum;
  • LAST_POST_DATE - the date the last post was created;
  • SORT - sort index;
order - sort order. The following values are possible:
  • ASC - ascending;
  • DESC - descending;
Optional. The default value is Array("SORT"=>"ASC")
arFilter An array of the format array("filtered field"=>"filter value" [, ...]).

This parameter is detailed in CForumNew::GetList.

Return Values

Returns an instance of the CDBResult class.

See Also

  • CDBResult
  • Forum fields

    Example

<?
// Display a list of forums the current user can at least read.
// Group the list by forum groups.
// First sort the list by sort index, then by the forum name
$arFilter = array();
if (!$USER->IsAdmin())
{
  $arFilter["PERMS"] = array($USER->GetGroups(), 'A');
  $arFilter["ACTIVE"] = "Y";
}
$arOrder = array("SORT"=>"ASC", "NAME"=>"ASC");
$db_Forum = CForumNew::GetListEx($arOrder, $arFilter);
$currentGroupID = -1;
while ($db_Forum->NavNext(true, "f_", false)):
  if ($currentGroupID != IntVal($f_FORUM_GROUP_ID))
  {
    if (IntVal($f_FORUM_GROUP_ID)>0)
    {
      $arCurForumGroup = CForumGroup::GetLangByID($f_FORUM_GROUP_ID, LANG);
      echo "<b>";
      echo htmlspecialcharsex($arCurForumGroup["NAME"]);
      echo "<b><br>";
    }
    $currentGroupID = IntVal($f_FORUM_GROUP_ID);
  }
  echo $f_NAME."<br>";
endwhile;
?>


GetSites

CForumNew::GetSites

array
CForumNew::GetSites(
 int ID
);

The method GetSites returns an associated array whose keys are the sites to which a specified forum is bound, and values are the templates of a path to a forum post on the corresponding site.

Parameters

Parameter | Description
ID | The forum ID.

Example

// Obtain an array of real paths to the post $MID
// from the topic $TID for the forum $FID

$arForumPaths = CForumNew::GetSites($FID);
$arForumPathsCodes = array_keys($arForumPaths);
for ($i = 0; $i < count($arForumPathsCodes); $i++)
{
    $arForumPaths[$arForumPathsCodes[$i]] =
        CForumNew::PreparePath2Message($arForumPaths[$arForumPathsCodes[$i]],
                                       array("FORUM_ID"=>$FID,
                                             "TOPIC_ID"=>$TID,
                                             "MESSAGE_ID"=>$MID)
                                       );
}


Update

CForumNew::Update

int
Update(
 int ID,
 array arFields
);

The method Update modifies the parameters of the existing forum specified by the ID. Returns the ID of the modified forum.

Before a forum is modified, you should check whether it can be modified using CanUserUpdateForum.

Parameters

Parameter | Description
ID | The ID of the forum whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where
  • field - field name;
  • value - field value.
The fields are listed in the List of forum fields.

Return Values

Returns the ID of the modified forum on success, or false otherwise.

See Also

  • Forum fields


Класс CForumPMFolder

CForumPMFolder

The CForumPMFolder class is used with user folders.

Methods

Method | Description
Add | Creates a new user folder.
Delete | Deletes a user folder.
GetList | Returns a selection of filtered and sorted messages.
Update | Modifies the parameters of an existing folder.
© 2001-2007 Bitrix Bitrix Site Manager


Add

CForumPMFolder::Add

int
Add(
 array arFields
);

The Add method creates a new folder with parameters specified in the arFields array.

Parameters

Parameter Description
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the User folder table. The required fields must be present.

Return Values

The method returns the ID of the created folder on success, or false otherwise.

See Also

User folder table

Example

<?
$arFields = Array(
    TITLE        - > $TITLE,
    USER_ID      - > $USER_ID,
);

$ID = CForumPMFolder::Add($arFields);

if (IntVal($ID)<=0)
    echo "Error!";
?>
© 2001-2007 Bitrix Bitrix Site Manager


Delete

CForumPMFolder::Delete

bool
Delete(
 int ID
);

The Delete method deletes a folder ID.

Parameters

Parameter | Description
ID | The ID of the folder to be deleted.

Return Values

The method returns true on success, or false otherwise.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CForumPMFolder::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter [,
 bool bCount ]]]
);

The GetList method returns a slection of messages filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - filter field, can have the following values:
    • ID - the message ID;
    • USER_ID - the folder owner user ID;
    • TITLE - the name of a user folder;
  • order - sort order, can have the following values:
    • ASC - ascending;
    • DESC - descending;
Optional. The default value is Array("ID"=>"ASC").
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the message ID;
  • USER_ID - the folder owner user ID;
  • TITLE - the name of a user folder.

The following logic can be specified at the beginning of the field name:

  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.

Required.
bCount | If set to true, the method returns a number of messages matching the filter. Optional. False by default.

Return Values

The method returns an instance of the CDBResult object.

See Also

CDBResult
User folder table

© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Update

CForumPMFolder::Update

int
Update(
 int ID,
 array arFields
);

The Update method replaces parameters of an existing folder ID with those specified in the arFields array.

Parameters

Parameter | Description
ID | The ID of the folder whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the User folder table.

Return Values

The method returns the ID of modified folder on success, or false otherwise.

See Also

User folder table

  • © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CForumPoints

The CForumPoints class is used with the Forum user ratings.

Methods

Method | Description
GetList | Returns an optionally sorted and filtered list of forum ratings.
GetListEx | Returns an optionally sorted and filtered list of forum ratings. Information on a specific rating include language dependent data.
GetByID | Returns an array containing parameters of the specified rating.
GetByIDEx | Returns an array of all parameters of the specified rating.
GetLangByID | Returns an array of language parameters of the specified rating.
Add | Adds a new rating to the forum rating database.
Update | Replaces parameters of the specified rating with the new ones.
Delete | Deletes the specified rating.


Add

CForumPoints::Add

int
CForumPoints::Add(
 array arFields
);

The method Add adds a new rating to the forum rating database.

Parameters

Parameter | Description
$arFields | Array containing fields of a new rating. For the full list list of rating fields, please see Rating fields.

Return Values

Returns the ID of the new rating or false otherwise.


Delete

CForumPoints::Delete

bool
CForumPoints::Delete(
 int ID
);

The method Delete deletes the specified rating.

Parameters

Parameter | Description
$ID | The ID of the rating to be deleted.

Return Values

Returns true on success or false otherwise.


GetByID

CForumPoints::GetByID

array
CForumPoints::GetByID(
 int ID
);

The method GetByID returns an array containing parameters of the specified rating.

Parameters

Parameter | Description
$ID | The ID of rating whose parameters are required.

Return Values

Array of rating parameters on success. For a complete list of fields, see Forum fields.

Example

<?

$ar_res = CForumPoints::GetByID(3);
echo "A user with this rating can give ".$ar_res["VOTES"]." vote(s)";
?>


GetByIDEx

CForumPoints::GetByIDEx

array
CForumPoints::GetByIDEx(
 int ID,
 string strLang
);

The method GetByIDEx returns an array of all parameters of the specified rating. The method returns parameters specific for the passed language ID.

Parameters

Parameter | Description
ID | The ID of rating whose parameters are required.
strLang | The ID of the language.

Return Values

Returns the associated array with the following keys.

Key | Value
ID | The rating ID
MIN_POINTS | Number of points required to obtain this rating.
CODE | Mnemonic code.
VOTES | Number of votes that a user with this rating can give.
LID | The language ID.
NAME | Name of the rating in the language LID.

Example

<?
$ar_res = CForumPoints::GetByIDEx(3, "ru");
echo "Users with rating ".$ar_res["NAME"]." can give ".$ar_res["VOTES"]." votes";

?>


GetLangByID

CForumPoints::GetLangByID

array
CForumPoints::GetLangByID(
 int POINTS_ID,
 string strLang
);

The method GetLangByID returns an array of language parameters of the specified rating.

Parameters

Parameter | Description
POINTS_ID | The ID of rating whose parameters are required.
strLang | The ID of the language.

Return Values

Returns the associated array with the following keys.

Key | Value
POINTS_ID | The rating ID.
LID | The ID of the language.
NAME | Name of the rating in the language LID.

Example

<?
$ar_res = CForumPoints::GetLangByID(3, "en");
echo "Name of rating with ID=".$ar_res["POINTS_ID"]." in English is ".$ar_res["NAME"]."";
?>


GetList

CForumPoints::GetList

CDBResult
CForumPoints::GetList(
 array arOrder = array("MIN_POINTS"=>"ASC"),
 array arFilter = array()
);

The method GetList returns an optionally sorted and filtered list of forum ratings.

Parameters

Parameter Description
arOrder An array in the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - name of the field by which the sorting is to be performed:
    • ID - the rating ID;
    • CODE - mnemonic code;
    • VOTES - number of votes a user can give;
    • MIN_NUM_POSTS - minimum number of messages for this rating;
  • order - sort order:
    • ASC - ascending;
    • DESC - descending.
arFilter An array in the format Array("filter field"=>"condition" [, ...]).

"Filter field" can be the following:
  • ID - the rating ID;
  • CODE - mnemonic code;
  • MIN_NUM_POSTS - minimum number of messages for this rating.

Return Values

Returns an instance of the CDBResult class containing arrays with the following keys.

Key | Value
ID | The rating ID
MIN_POINTS | Number of points required to obtain this rating.
CODE | Mnemonic code.
VOTES | Number of votes that a user with this rating can give.

Example

// Sort by the number of votes in asc. order
// if equal, sort by ID
$arOrder = array("VOTES"=>"DESC", "ID"=>"ASC");

// Filter to select ratings with a minimum of 50 points
$arFilter = array(">=MIN_POINTS"=>50);

$db_res = CForumPoints::GetList($arOrder, $arFilter);
while ($ar_res = $db_res->Fetch())
{
   echo $ar_res["ID"]."-".$ar_res["VOTES"]."<br>";
}


GetListEx

CForumPoints::GetListEx

CDBResult
CForumPoints::GetListEx(
 array arOrder = array("MIN_POINTS"=>"ASC"),
 array arFilter = array()
);

The method GetListEx returns an optionally sorted and filtered list of forum ratings.

Parameters

Parameter Description
arOrder An array in the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - name of the field by which the sorting is to be performed:
    • ID - the rating ID;
    • CODE - mnemonic code;
    • VOTES - number of votes a user can give;
    • MIN_NUM_POSTS - minimum number of messages for this rating;
  • order - sort order:
    • ASC - ascending;
    • DESC - descending.
arFilter An array in the format Array("filter field"=>"condition" [, ...]).

"Filter field" can be the following:
  • LID - the language ID (required);
  • ID - the rating ID;
  • CODE - mnemonic code;
  • MIN_NUM_POSTS - minimum number of messages for this rating.

Return Values

Returns an instance of the CDBResult class containing arrays with the following keys.

Key | Value
ID | The rating ID
MIN_POINTS | Number of points required to obtain this rating.
CODE | Mnemonic code.
VOTES | Number of votes that a user with this rating can give.
LID | The language ID.
NAME | Name of the rating in LID.

Example

// Sort by the number of votes in asc. order
// if equal, sort by ID
$arOrder = array("VOTES"=>"DESC", "ID"=>"ASC");

// Filter to select ratings with a minimum of 50 points
$arFilter = array("LID"=>"ru", ">=MIN_POINTS"=>50);

$db_res = CForumPoints::GetList($arOrder, $arFilter);
while ($ar_res = $db_res->Fetch())
{
    echo $ar_res["NAME"]."-".$ar_res["VOTES"]."<br>";
}


Update

CForumPoints::Update

int
CForumPoints::Update(
 int ID,
 array arFields
);

The Update method replaces parameters of the specified rating with the new ones.

Parameters

Parameter | Description
ID | The ID of rating whose parameters are to be updated.
arFields | Array containing new fields of the rating.

Return Values

Returns the ID of the updated rating or false otherwise.

See Also

Rating fields

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CForumPoints2Post

The CForumPoints2Post class is used with the lookup table describing relationship between the number of user messages and number of points per message.

Methods

Method | Description
GetList | Returns an optionally filtered and sorted selection from the points-per-message lookup table.
GetByID | Returns an array describing a specified record in the lookup table.
Add | Adds a new record to the lookup table.
Update | Replaces values of the specified entry in the the points-per-message lookup table with the new ones.
Delete | Delete the specified record from the lookup table.


Add

CForumPoints2Post::Add

int
CForumPoints2Post::Add(
 array arFields
);

The method Add adds a new record to the lookup table describing relationship between the number of user messages and number of points per message.

Parameters

Parameter | Description
arFields | Array containing parameters of a new record.

Return Values

Returns the new record ID or false otherwise.


Delete

CForumPoints2Post::Delete

bool
CForumPoints2Post::Delete(
 int ID
);

The method Delete delete the specified record from the lookup table describing relationship between the number of user messages and number of points per message.

Parameters

Parameter | Description
ID | The ID of the record to be deleted.

Return Values

Returns true on success or false otherwise.


GetByID

CForumPoints2Post::GetByID

array
CForumPoints2Post::GetByID(
 int ID
);

The method GetByID returns an array describing a specified record in the lookup table describing relationship between the number of user messages and number of points per message.

Parameters

Parameter | Description
ID | The ID of the record whose information is required to be returned.

Return Values

Returns the associated array with the following keys.

Key | Value
ID | The record ID.
MIN_NUM_POSTS | Number of messages a user have to add to the forum to gain this number of points per message.
POINTS_PER_POST | Number of points per message. May be both integer and fractional; for example: 2 or 0.1.


GetList

CForumPoints2Post::GetList

CDBResult
CForumPoints2Post::GetList(
 array arOrder = array("MIN_NUM_POSTS"=>"ASC"),
 array arFilter = array()
);

The method GetList returns an optionally filtered and sorted selection from the lookup table describing relationship between the number of user messages and number of points per message.

Parameters

Parameter Description
arOrder Specifies the name of a parameter by which the sorting is to be performed.

The following values are possible:
  • ID - the record ID;
  • MIN_NUM_POSTS - number of messages a user have to add to the forum to gain this number of points per message;
  • POINTS_PER_POST - number of points per message.
arFilter The filter is an associated array whose keys are the discount parameter names, and values are the conditions.

The following keys are possible:
  • ID - the record ID;
  • MIN_NUM_POSTS - number of messages a user have to add to the forum to gain this number of points per message;

Return Values

Returns an instance of CDBResult containing a set of associated arrays with the following keys.

Key | Value
ID | The record ID.
MIN_NUM_POSTS | Number of messages a user have to add to the forum to gain this number of points per message.
POINTS_PER_POST | Number of points per message. May be both integer and fractional; for example: 2 or 0.1.


Update

CForumPoints2Post::Update

int
CForumPoints2Post::Update(
 int ID,
 array arFields
);

The method Update replaces values of the specified entry in the the points-per-message lookup table with the new ones.

Parameters

Parameter | Description
ID | The ID of the record whose values are to be updated.
arFields | Array containing new parameters of the updated record.

Return Values

Returns the record ID or false otherwise.


Класс CForumPrivateMessage

CForumPrivateMessage

The CForumPrivateMessage class is used with private messages.

Methods

Method | Description
Delete | Deletes an existing private user message.
GetList | Returns a selection of filtered and sorted messages.
GetByID | Returns an array of message parameters.
Send | Creates (and sends) a new message.
Update | Modifies the parameters of an existing message.
© 2001-2007 Bitrix Bitrix Site Manager


Delete

CForumPrivateMessage::Delete

bool
Delete(
 int ID
);

The Delete method deletes a message.

Parameters

Parameter | Description
ID | The ID of the message to be deleted.

Return Values

The method returns true on success, or false otherwise.
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

CForumPrivateMessage::GetByID

array
GetByID(
 int ID
);

The GetByID method returns an array of parameters of a specified message.

Parameters

Parameter | Description
ID | The ID of the message whose parameters are required.

Return Values

The method returns an array of message parameters. If the required message is not found, false is returned.

See Also

Private message table

Example

<?
$arMessage = CForumPrivateMessage::GetByID($MID);
if ($arMessage)
{
  $AUTHOR_ID = IntVal($arMessage["AUTHOR_ID"]);
  $USER_ID = IntVal($arMessage["USER_ID"]);
}
?>
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetList

CForumPrivateMessage::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter [,
 bool bCount ]]]
);

The GetList method returns a selection of messages filtered by arFilter and sorted in the arOrder order.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - filter field, can have the following values:
    • ID - the message ID;
    • AUTHOR_ID - the message author ID;
    • POST_DATE - the date when the message was created;
    • POST_SUBJ - the message subject;
    • POST_MESSAGE - the message body;
    • USER_ID - the recipient user ID;
    • FOLDER_ID - the folder ID;
    • IS_READ - marks the message is read;
    • USE_SMILES - indicates whether smileys can be used;
    • AUTHOR_NAME - the message author name;
  • order - sort order, can have the following values:
    • ASC - ascending;
    • DESC - descending.
Optional. The default value is Array("ID"=>"ASC").
arFilter An array in the format array("filtered field"=>"filter value" [, ...]). The following values are possible:
  • ID - the message ID;
  • AUTHOR_ID - the message author ID;
  • POST_SUBJ - the message subject;
  • POST_MESSAGE - the message body;
  • USER_ID - the recipient user ID;
  • FOLDER_ID - the folder ID;
  • IS_READ - marks the message is read.

The following logic can be specified at the beginning of the field name:

  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.

Required.
bCount | If set to true, the method returns a number of records matching the filter. Optional. False by default.

Return Values

The method returns an instance of the CDBResult object.

See Also

CDBResult
Private message table

  • © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Send

CForumPrivateMessage::Send

int
Send(
 array arFields
);

The Send method creates a message with parameters specified in the arFields array.

Parameters

Parameter Description
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the Private message table. The required fields must be present.

Return Values

The method returns the ID of the created message on success, or false otherwise.

See Also

Private message table

Example

<?
$arFields = Array(
    AUTHOR_ID    - > $AUTHOR_ID,
    POST_DATE    - > $POST_DATE,
    POST_SUBJ    - > $POST_SUBJ,
    POST_MESSAGE - > $POST_MESSAGE,
    USER_ID      - > $USER_ID,
    FOLDER_ID    - > 1,
    IS_READ      - > "N",
    USE_SMILES   - > ($USE_SMILES=="Y") ? "Y" : "N",
    AUTHOR_NAME  - > $AUTHOR_NAME
);
$ID = CForumPrivateMessage::Send($arFields);
if (IntVal($ID)<=0)
  echo "Error!";
?>
© 2001-2007 Bitrix Bitrix Site Manager


Update

CForumPrivateMessage::Update

int
Update(
 int ID,
 array arFields
);

The Update method replaces parameters of an existing message ID with those specified in the arFields array.

Parameters

Parameter | Description
ID | The ID of the message whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]):
  • field - field name;
  • value - field value.
The fields are listed in the Private message table.

Return Values

The method returns the ID of modified message on success, or false otherwise.

See Also

Private message table

  • © 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CForumSmile

The CForumSmile is used with smiles.

Methods

Method | Description
GetList | Returns a list of smiles.
GetByID | Returns language independent parameters of the specified smile.
GetByIDEx | Returns language dependent parameters of the specified smile.
GetLangByID | Returns an array of language dependent parameters of a specified smile.
Add | Creates a new smile given the provided parameters.
Update | Replaces parameters of the specified smile with the new ones.
Delete | Deletes the specified smile.


Add

int
Add(
 array arFields
);

The method Add creates a new smile given the provided parameters.

Parameters

Parameter Description
arFields Associated array of a smile parameters whose keys are the order parameter names, and values are the parameter values of the format Array(field1=>value1[, field2=>value2 [, ..]]). The following values are possible:
  • field - field name;
  • value - field value.
You can refer to the List of smile fields for a list of possible keys. A special field "LANG" should contain an array of arrays with the language parameters of a smile. All the required fields must be filled.

Return Values

Returns the ID of the new smile on success or false otherwise.

See Also

  • List of smile fields


Delete

bool
Delete(
 int ID
);

The method Delete deletes the specified smile.

Parameters

Parameter | Description
ID | The ID of the smile to be deleted.

Return Values

Returns true on success or false otherwise.


GetByID

array
GetByID(
 int ID
);

The method GetByID returns language independent parameters of the specified smile.

Parameters

Parameter | Description
ID | The ID of the smile whose properties are to be retrieved.

Return Values

Returns an associated array with the smile parameters, or false otherwise.

See Also

  • List of smile fields


GetByIDEx

array
GetByIDEx(
 int ID,
 char(2) LANG
);

The method GetByIDEx returns language dependent parameters of the specified smile.

Parameters

Parameter | Description
ID | The ID of the smile whose properties are to be retrieved.
LANG | The ID of the site which defines the language specific parameters to be retrieved.

Return Values

Returns an associated array with the smile parameters, or false otherwise.

See Also

  • List of smile fields


GetLangByID

array
GetLangByID(
 int ID,
 char(2) LANG
);

The method GetLangByID returns an array of language dependent parameters of a specified smile.

Parameters

Parameter | Description
ID | The ID of the smile whose properties are to be retrieved.
LANG | The ID of the site which defines the language specific parameters to be retrieved.

Return Values

Returns an associated array with the smile parameters, or false otherwise.

See Also

  • List of smile fields


GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter]]
);

Returns a list of smiles.

Parameters

Parameter Description
arOrder An array in the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - field by which the sorting is to be performed
    • ID - the smile ID;
    • SORT - sort weight;
  • order - sort order:
    • ASC - ascending;
    • DESC - descending;
Optional. By default Array("SORT"=>"ASC").
arFilter An array in the format array("filter field"=>"value" [, ...]). The following keys are possible:
  • ID - the smile ID;
  • SORT - sort weight.
The filter field may be prepended with the condition operator: "!" (negation), "<", "<=", ">", ">=".

Optional. By default, the records are not filtered.

Return Values

Returns an instance of the CDBResult.

See Also

  • CDBResult
  • Smile fields


Update

int
Update(
 int ID,
 array arFields
);

The method Update replaces parameters of the specified smile with the new ones.

Parameters

Parameter | Description
ID | The ID of the smile whose properties are to be modified.
arFields Associated array of a smile parameters whose keys are the order parameter names, and values are the parameter values of the format Array(field1=>value1[, field2=>value2 [, ..]]). The following values are possible:
  • field - field name;
  • value - field value.
You can refer to the List of smile fields for a list of possible keys. A special field "LANG" should contain an array of arrays with the language parameters of a smile. All the required fields must be filled.

Return Values

Returns the ID of the updated smile or false otherwise.

See Also

  • List of smile fields


CForumSubscribe

The CForumSubscribe class is used to manage the forum subscriptions.

Methods

Method | Description
GetList | Returns an optionally sorted and filtered list of subscriptions.
GetListEx | Returns an optionally sorted and filtered list of subscriptions. Each entry in the list has an e-mail of a subscribed user.
Add | Creates a new record in the subscription table given the specified parameters.
Delete | Deletes the specified subscription.
CanUserAddSubscribe | Thoroughly checks whether a user of a specified group can subscribe to the specified forum.
CanUserDeleteSubscribe | Thoroughly checks whether a user of a specified group can unsubscribe from the specified forum.


Add

CForumSubscribe::Add

int
Add(
 array arFields
);

Creates a new record in the subscription table given the specified parameters. Before calling this method, you should check whether the current user can subscribe by calling CForumSubscribe::CanUserAddSubscribe.

Parameters

Parameter Description
arFields An array in the format Array(field1=>value1[, field2=>value2 [, ..]]), where:
  • field - field name;
  • value - field value.
For the list of fields, please see Subscription fields. All the required fields must be filled.

Return Values

Returns the ID of the new subscription on success or false otherwise.

See Also

  • Subscription fields


CanUserAddSubscribe

bool
CanUserAddSubscribe(
 int FID,
 array arUserGroups
);

Thoroughly checks whether a user of a specified group can subscribe to the specified forum.

Parameters

Parameter | Description
FID | The ID of the forum to which (whole or thread) a user wants to subscribe.
arUserGroups | Array of groups that the user is member of. For the current user, you can obtain this array by calling $USER->GetUserGroupArray().

Return Values

Returns true is the user can subscribe, or false otherwise.

See Also

  • CForumNew::CanUserDeleteSubscribe


CanUserDeleteSubscribe

CForumSubscribe::CanUserDeleteSubscribe

bool
CanUserDeleteSubscribe(
 int ID,
 array arUserGroups,
 int iUserID
);

Thoroughly checks whether a user of a specified group can unsubscribe from the specified forum.

Parameters

Parameter | Description
ID | The ID of the subscription from which a user wants to unsubscribe.
arUserGroups | Array of groups that the user is member of. For the current user, you can obtain this array by calling $USER->GetUserGroupArray().
iUserID | The user ID. For the current user, you can obtain it by calling $USER->GetID().

Return Values

Returns true is the user can unsubscribe, or false otherwise.

See Also

  • CForumSubscribe::CanUserAddSubscribe


Delete

CForumSubscribe::Delete

bool
Delete(
 int ID
);

Deletes the specified subscription. Before calling this method, you should check whether the current user can unsubscribe by calling CForumSubscribe::CanUserDeleteSubscribe.

Parameters

Parameter | Description
ID | The ID of the subscription to be deleted.

Return Values

Returns true on success or false otherwise.


GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter]]
);

Returns an optionally sorted and filtered list of subscriptions.

Parameters

Parameter Description
arOrder An array in the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - name of the field by which the sorting is to be performed:
    • ID - the subscription ID;
    • USER_ID - the subscriber ID;
    • FORUM_ID - the forum ID;
    • TOPIC_ID - the topic ID;
    • START_DATE - the date of subscription;
  • order - sort order:
    • ASC - ascending;
    • DESC - descending;
Optional. By default Array("ID"=>"ASC").
arFilter An array in the format array("filter field"=>"condition value" [, ...]). The following keys are possible:
  • ID - the subscription ID;
  • USER_ID - the subscriber ID;
  • FORUM_ID - the forum ID;
  • TOPIC_ID - the topic ID;
  • TOPIC_ID_OR_NULL - the topic ID or NULL (checks if equal only);
  • LAST_SEND - the ID of the last sent message;
  • LAST_SEND_OR_NULL - the ID of the last sent message or NULL (checks if less only).
The filter field may be prepended with the condition operator: "!" (not equal), "<", "<=", ">", ">=".
Optional. By default, the records are not filtered.

Return Values

Returns an instance of the CDBResult.

See Also

  • CDBResult
  • Subscription fields


GetListEx

CForumSubscribe::GetListEx

CDBResult
CForumSubscribe::GetListEx(
 array arOrder = array("ID"=>"ASC"),
 array arFilter = array()
);

The method GetListEx returns an optionally sorted and filtered list of subscriptions. Each entry in the list has an e-mail of a subscribed user.

Parameters

Parameter Description
arOrder An array in the format Array(by1=>order1[, by2=>order2 [, ..]]), where:
  • by - name of the field by which the sorting is to be performed:
    • ID - the subscription ID;
    • USER_ID - the subscriber ID;
    • FORUM_ID - the forum ID;
    • TOPIC_ID - the topic ID;
    • START_DATE - the date of subscription;
  • order - sort order:
    • ASC - ascending;
    • DESC - descending;
Optional. By default Array("ID"=>"ASC").
arFilter An array in the format array("filter field"=>"condition" [, ...]). The following keys are possible:
  • ID - the subscription ID;
  • USER_ID - the subscriber ID;
  • FORUM_ID - the forum ID;
  • TOPIC_ID - the topic ID;
  • TOPIC_ID_OR_NULL - the topic ID or NULL (checks if equal only);
  • LAST_SEND - the ID of the last sent message;
  • LAST_SEND_OR_NULL - the ID of the last sent message or NULL (checks if less only);
  • NEW_TOPIC_ONLY - specifies that only new topics can be subscribed (Y/N);
  • LAST_SEND - the ID of the last message sent by subscription;
  • LAST_SEND_OR_NULL - the ID of the last message sent by subscription including empty values;
  • PERMISSION - minimum access permission to the forum to whose posts the subscription is setup.

Return Values

Returns an instance of the CDBResult class containing arrays with the following keys.

Key | Value
ID | The subscription ID
USER_ID | The subscriber ID
FORUM_ID | The forum ID
TOPIC_ID | The topic ID
LAST_SEND | The ID of the last sent message
NEW_TOPIC_ONLY | Specifies that only new topics can be subscribed
SITE_ID | The site ID whose messages are sent by subscription.
START_DATE | The date of subscription
EMAIL | Subscribed e-mail address.

See Also

  • CDBResult
  • Subscription fields


CForumTopic

The CForumTopic class is used with forum topics.

Methods

Method | Description
GetList | Returns a filtered and sorted list of topics.
GetListEx | Returns a filtered and sorted list of topics including all bound data.
GetByID | Returns an array of topic parameters by its ID.
GetByIDEx | Returns an array of topic parameters as well as its auxiliary parameters by its ID.
Add | Creates a new topic.
Update | Modifies topic parameters.
Delete | Deletes a topic.
CanUserAddTopic | Thoroughly checks whether a user can add a new topic.
CanUserUpdateTopic | Thoroughly checks whether a user can modify a topic.
CanUserDeleteTopic | Thoroughly checks whether a user can delete a topic.
GetNeighboringTopics | Returns the ID's of a previous and next topic relative to a specified topic.
MoveTopic2Forum | Moves a topic to another forum.


Add

int
Add(
 array arFields
);

The method Add creates a new topic with parameters specified in the array arFields. Returns the ID of the created topic.

Parameters

Parameter | Description
arFields | An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where field - field name; value - field value. The fields are listed in the List of topic fields. The required fields must be filled.

Return Values

Returns the ID of the created topic on success, or false otherwise.

See Also

  • Topic fields
  • Before a topic is created, you should check whether it can be added using CForumTopic::CanUserAddTopic. It is recommended to add and modify messages and message subjects using the method ForumAddMessage.


CanUserAddTopic

CForumTopic::CanUserAddTopic

bool
CanUserAddTopic(
 int FID,
 array arUserGroups,
 int iUserID
);

The method CanUserAddTopic thoroughly checks whether a specified user who is a member of a specified group can add a new topic to a specified forum.

Parameters

Parameter | Description
FID | The ID of the forum to which a user wants to add a topic.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all the permissions required to add a topic, or false otherwise.

See Also

  • CForumTopic::CanUserUpdateTopic
  • CForumTopic::CanUserDeleteTopic

    Example

<?
if (CForumTopic::CanUserAddTopic($FID, $USER->GetUserGroupArray(), $USER->GetID()))
{
    echo "You can add topic!";
}
?>


CanUserDeleteTopic

CForumTopic::CanUserDeleteTopic

bool
CanUserDeleteTopic(
 int ID,
 array arUserGroups,
 int iUserID
);

The method CanUserDeleteTopic thoroughly checks whether a specified user who is a member of a specified group can delete a specified topic.

Parameters

Parameter | Description
ID | The ID of the topic which a user wants to delete.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all the permissions required to delete a topic, or false otherwise.

See Also

  • CForumTopic::CanUserAddTopic
  • CForumTopic::CanUserUpdateTopic

    Example

<?
if (CForumTopic::CanUserDeleteTopic($ID, $USER->GetUserGroupArray(), $USER->GetID()))
{
    CForumTopic::Delete($ID);
}
?>


CanUserUpdateTopic

bool
CanUserUpdateTopic(
 int ID,
 array arUserGroups,
 int iUserID
);

The method CanUserUpdateTopic thoroughly checks whether a specified user who is a member of a specified group can modify a specified topic.

Parameters

Parameter | Description
ID | The ID of the topic which a user wants to modify.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all the permissions required to modify a topic, or false otherwise.

See Also

  • CForumTopic::CanUserAddTopic
  • CForumTopic::CanUserDeleteTopic

    Example

<?
if (CForumTopic::CanUserUpdateTopic($ID, $USER->GetUserGroupArray(), $USER->GetID()))
{
    echo "You can modify this topic!";
}
?>


Delete

bool
Delete(
 int ID
);

The method Delete deletes a specified topic.

Parameters

Parameter | Description
ID | The ID of the topic to be deleted.

Return Values

Returns true on success, or false otherwise.

See Also

  • Before a message is deleted, you should check whether it can be deleted using CForumTopic::CanUserDeleteTopic.


GetByID

array
GetByID(
 int ID
);

The method GetByID returns an array of topic parameters by its ID. The method call result is cached, therefore, the repeated calls with the same topic do not incur extra queries to the database (unless the cache is reset after the topic parameters are changed).

Parameters

Parameter | Description
ID | The topic ID.

Return Values

An array of topic parameters. If the topic cannot be found, false is returned.

See Also

  • Topic fields

    Example

<?
$arTopic = CForumTopic::GetByID($TID);
if ($arTopic)
{
  $FID = IntVal($arTopic["FORUM_ID"]);
}
?>


GetByIDEx

array
GetByIDEx(
 int ID
);

The method GetByIDEx returns an array of topic parameters as well as its auxiliary parameters by its ID.

Parameters

Parameter | Description
ID | The topic ID.

Return Values

Array of topic parameters including the auxiliary ones. If the topic can not be found, the method returns false.

See Also

  • Topic fields

    Example

<?
// Print all the returned topic parameters
$arTopic = CForumTopic::GetByIDEx($TID);
if ($arTopic)
{
  echo "<pre>";
  print_r($arTopic);
  echo "</pre>";
}
?>


GetList

CForumTopic::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter [,
 bool bCount [,
 int iNum]]]]
);

The method GetList returns a filtered and sorted list of topics.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:

by - the field by which the list is to be sorted. The following values are possible:
  • ID - the topic ID;
  • TITLE - the topic title;
  • STATE - topic state;
  • USER_START_ID - the ID of the user who has created a topic;
  • USER_START_NAME - the name of the user who has created a topic;
  • START_DATE - the date the topic was created;
  • POSTS - number of posts in the topic;
  • VIEWS - number of topic views;
  • APPROVED - the topic is approved and published.
  • LAST_POST_DATE - the date the last message was created in the topic;
  • SORT - sort index;

order - sort order. The following values are possible:

  • ASC - ascending;
  • DESC - descending;

Optional. The default value is Array("SORT"=>"ASC")
arFilter An array of the format array("filter field"=>"filter value" [, ...]).

The "filter field" can be one of the following:
  • STATE - topic state;
  • FORUM_ID - the forum ID;
  • ID - the topic ID;
  • APPROVED - the topic is approved and published;
  • LAST_POST_DATE - the date the last message was created in the topic;
The filtered field may contain one of the following condition operators before the name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Optional. By default, records are not filtered.
bCount If parameter is true, only the number of topics that conforms to the specified filter is returned.
Optional. The default value is false.
iNum | Maximum number of records returned. If the parameter iNum is not zero, a maximum of iNum records is returned. Not all databases support this feature. If the feature is not supported, this parameter is ignored. Optional. The default value is 0.

Return Values

 Returns an instance of the CDBResult class.

See Also
  • CDBResult
  • Topic fields

    Example

<?
// Select all the published topics of the forum $FID,
// that were sorted first by sort index,
// then by the date of the last message in the topic
$db_res = CForumTopic::GetList(array("SORT"=>"ASC",
                                     "LAST_POST_DATE"=>"DESC"),
                               array("FORUM_ID"=>$FID));
while ($ar_res = $db_res->Fetch())
{
  echo $ar_res["TITLE"]."<br>";
}
?>


GetListEx

CForumTopic::GetListEx

CDBResult
GetListEx(
 [array arOrder [,
 array arFilter [,
 bool bCount [,
 int iNum]]]]
);

The method GetListEx returns a filtered and sorted list of topics including all bound data.

Parameters

Parameter | Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]).
This parameter is detailed in CForumTopic::GetList.
arFilter An array of the format array("filter field"=>"filter value" [, ...]).
This parameter is detailed in CForumTopic::GetList.
bCount If parameter is true, only the number of topics that conforms to the specified filter is returned.
Optional. The default value is false.
iNum | Maximum number of records returned. If the parameter iNum is not zero, a maximum of iNum records is returned. Not all databases support this feature. If the feature is not supported, this parameter is ignored. Optional. The default value is 0.

Return Values

 Returns an instance of the CDBResult class.

See Also
  • CDBResult
  • Topic fields

    Example

<?
// Select all the published topics of the forum $FID,
// that were sorted first by sort index,
// then by the date of the last message in the topic
$db_res = CForumTopic::GetList(array("SORT"=>"ASC",
                                     "LAST_POST_DATE"=>"DESC"),
                               array("FORUM_ID"=>$FID));
while ($ar_res = $db_res->Fetch())
{
  echo "<pre>";
  print_r($ar_res);
  echo "</pre><br>";
}
?>


GetNeighboringTopics

CForumTopic::GetNeighboringTopics

array
CForumTopic::GetNeighboringTopics(
 int TID,
 array arUserGroups
);

The method GetNeighboringTopics returns the ID's of the neighboring topics (previous and next ones) for a specified forum topic. The topics are sorted by the date of the last message (standard sorting) considering the access permissions of the specified user groups.

Parameters

Parameter | Description
TID | The ID of the topic whose neighbor topics ID's are to be returned.
arUserGroups | Array of user group ID's used to consider access permissions. Usually, the ID's of the groups whose member the current user is.

Return Values

The method returns an array containing two elements. The first element is the ID of the previous topic, the second is the ID of the following one. If any of the neighbors does not exist for this topic, zero is returned in either first or second array entry.

Example

<?
// Display the links to the neighboring topics
// for the topic TID with respect to the current user permissions
list($iPREV_TOPIC, $iNEXT_TOPIC) =
    CForumTopic::GetNeighboringTopics($TID,
                                      $USER->GetUserGroupArray());
if ($iPREV_TOPIC > 0)
   echo "<a href=\"read.php?FID=".$FID."&TID=".$iPREV_TOPIC."\">";
echo "Previous topic";
if ($iPREV_TOPIC > 0)
   echo "</a>";
echo " | ";
if ($iNEXT_TOPIC > 0)
   echo "<a href=\"read.php?FID=".$FID."&TID=".$iNEXT_TOPIC."\">";
echo "Next topic";
if ($iNEXT_TOPIC > 0)
   echo "</a>";
?>


MoveTopic2Forum

CForumTopic::MoveTopic2Forum

bool
CForumTopic::MoveTopic2Forum(
 int TID,
 int FID
);

The method MoveTopic moves a specified topic to a specified forum.

Parameters

Parameter | Description
TID | The ID of the topic to be moved.
FID | The ID of the forum to which the topic is to be moved.

Return Values

The method returns true on success, or false otherwise.


Update

CForumTopic::Update

int
Update(
 int ID,
 array arFields [,
 bool skip_counts]
);

The method Update modifies the parameters of the existing topic specified by the ID. Returns the ID of the modified topic.

Parameters

Parameter | Description
ID | The ID of the topic whose parameters are to be modified.
arFields An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where
  • field - field name;
  • value - field value.
The fields are listed in the List of topic fields.
skip_counts If true, the statistical data is not updated when the topic is modified. It speeds up the method execution but causes information to become somewhat logically inconsistent.

Optional. False by default.

Return Values

 Returns the ID of the modified topic on success, or false otherwise.

See Also
  • Topic fields
  • Before a topic is modified, you should check whether it can be modified using CanUserUpdateTopic. It is recommended to add and modify messages and message subjects using the high level function ForumAddMessage.


CForumUser

The CForumUser class is used with profiles of the forum visitors.

Methods

Method | Description
GetList | Returns a filtered and sorted list of profiles.
GetByID | Returns an array of profile parameters by its ID.
GetByUSER_ID | Returns an array of profile parameters by the ID of the user who is the owner of the profile.
GetByIDEx | Returns an array of profile parameters as well as its auxiliary parameters by its ID.
Add | Creates a new profile.
Update | Modifies parameters of the existing profile.
Delete | Deletes a specified profile.
CanUserAddUser | Thoroughly checks whether a user can add a new profile.
CanUserUpdateUser | Thoroughly checks whether a user can modify a profile.
CanUserDeleteUser | Thoroughly checks whether a user can delete a profile.
GetUserRank | Returns parameters of the specified rank.


Add

int
Add(
 array arFields [,
 string strUploadDir ]
);

The method Add creates a new profile with parameters specified in the array arFields. Returns the ID of the created profile.

Before a profile is created, you should check whether it can be added using CForumUser::CanUserAddUse.

Parameters

Parameter | Description
arFields | An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where field - field name; value - field value. The fields are listed in the List of fields of user profile. The required fields must be filled.
strUploadDir | Directory in which files are to be uploaded. Must be specified relative to the main upload directory. Optional. The default value is "forum".

Return Values

Returns the ID of the created profile on success, or false otherwise.

See Also

Profile fields
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


CanUserAddUser

bool
CanUserAddUser(
 array arUserGroups
);

The method CanUserAddUser thoroughly checks whether a specified user who is a member of a specified group can add a new profile.

Parameters

Parameter | Description
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().

Return Values

Returns true if the user has all the permissions required to add a profile, or false otherwise.

See Also

  • CForumUser::CanUserUpdateUser
  • CForumUser::CanUserDeleteUser


CanUserDeleteUser

bool
CanUserDeleteUser(
 int ID,
 array arUserGroups
);

The method CanUserDeleteUser thoroughly checks whether a specified user who is a member of a specified group can delete a profile.

Parameters

Parameter | Description
ID | The ID of the profile which the user wants to delete.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().

Return Values

Returns true if the user has all the permissions required to delete a profile, or false otherwise.

See Also

  • CForumUser::CanUserAddUser
  • CForumUser::CanUserUpdateUser


CanUserUpdateUser

bool
CanUserUpdateUser(
 int ID,
 array arUserGroups,
 int iUserID
);

The method CanUserUpdateUser thoroughly checks whether a specified user who is a member of a specified group can modify a specified profile.

Parameters

Parameter | Description
ID | The ID of the profile which the user wants to modify.
arUserGroups | Array of groups whose member this user is. Array of groups of the current user is returned by $USER->GetUserGroupArray().
iUserID | The user ID. The current user ID is returned by $USER->GetID().

Return Values

Returns true if the user has all the permissions required to modify a profile, or false otherwise.

See Also

  • CForumUser::CanUserAddUser
  • CForumUser::CanUserDeleteUser


Delete

bool
Delete(
 int ID
);

The method Delete deletes a specified profile.

Before a profile is deleted, you should check whether it can be deleted using CForumUser::CanUserDeleteUser.

Parameters

Parameter | Description
ID | The ID of the profile to be deleted.

Return Values

Returns true on success, or false otherwise.
  • © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetByID

array
GetByID(
 int ID
);

The method GetByID returns an array of profile parameters by its ID. The method call result is cached, therefore, the repeated calls with the same profile do not incur extra queries to the database (unless the cache is reset after the profile parameters are changed).

Parameters

Parameter | Description
ID | The profile ID.

Return Values

An array of profile parameters. If the profile cannot be found, false is returned.

See Also

  • Profile fields


GetByIDEx

array
GetByIDEx(
 int ID
);

The method GetByIDEx returns an array of profile parameters as well as its auxiliary parameters by its ID.

Parameters

Parameter | Description
ID | The profile ID.

Return Values

Array of profile parameters including the auxiliary ones. If the profile can not be found, the method returns false.

See Also

  • Profile fields


GetByUSER_ID

CForumUser::GetByUSER_ID

array
GetByUSER_ID(
 int USER_ID
);

The method GetByUSER_ID returns an array of profile parameters by the ID of the user who is the owner of the profile. The method call result is cached; therefore, the repeated calls with the same user ID do not incur extra queries to the database (unless the cache is reset after the profile parameters are changed).

Parameters

Parameter | Description
USER_ID | The user ID.

Return Values

An array of profile parameters. If the profile cannot be found, false is returned.

See Also

  • Profile fields


GetList

CForumUser::GetList

CDBResult
GetList(
 [array arOrder [,
 array arFilter]]
);

The method GetList returns a filtered and sorted list of profiles.

Parameters

Parameter Description
arOrder An array of the format Array(by1=>order1[, by2=>order2 [, ..]]), where:

by - the field by which the list is to be sorted. The following values are possible:
  • ID - the profile ID;
  • USER_ID - the user ID;
  • SHOW_NAME - show name instead of login;
  • NUM_POSTS - number of posts;
  • LAST_POST - the ID of the last message;
  • NAME - user name;
  • LAST_NAME - user last name;
  • LOGIN - login;
  • LAST_VISIT - the date of the last visit;
order - sort order. The following values are possible:
  • ASC - ascending;
  • DESC - descending;
Optional. The default value is Array("ID"=>"ASC").
arFilter An array of the format array("filter field"=>"filter value" [, ...]).

The "filter field" can be one of the following:
  • ID - the profile ID;
  • USER_ID - the user ID;
  • RANK_ID - the user rank ID;
  • SHOW_NAME - show name instead of login;
  • NUM_POSTS - number of posts;
  • ALLOW_POST - allow posts from this user (i.e. not banned);
The filtered field may contain one of the following condition operators before the name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less or equal;
  • ">" - more than;
  • ">=" - more or equal.
Optional. By default, records are not filtered.

Return Values

Returns an object of the CDBResult class.

See Also

CDBResult
Profile fields
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


GetUserRank

CForumUser::GetUserRank

array
CForumUser::GetUserRank(
 int USER_ID,
 string strLang = false
);

The method GetUserRank returns parameters of the specified rank.

Parameters

Parameter | Description
USER_ID | The user ID.
strLang | The language ID. If specified, the method also returns the language-dependent parameters of the rank in the language strLang. If false, only the language-independent parameters are returned.

Return Values

Returns an associated array with the following keys:

Key | Value
ID | The rank ID.
MIN_POINTS | Number of points required to obtain this rank.
CODE | Mnemonic code.
VOTES | Number of votes that a user with this rating can give.
LID | The language ID (if strLang is specified).
NAME | Name of the rating in LID (if strLang is specified).

Example

<?
// if the forum settings allows displaying ranks
if (COption::GetOptionString("forum", "SHOW_VOTES", "Y")=="Y")
{
   // display the current user rank in the current language
   $arUserRank = CForumUser::GetUserRank($USER->GetID(),
                                         LANGUAGE_ID);
   echo $arUserRank["NAME"];
}
?>


Update

int
Update(
 int ID,
 array arFields [,
 string strUploadDir ]
);

The method Update modifies parameters of the existing profile specified by the ID with those specified in the array arFields. Returns the ID of the modified profile.

Before a profile is modified, you should check whether it can be modified using CForumUser::CanUserUpdateUser.

Parameters

Parameter | Description
ID | The ID of the profile whose parameters are to be modified.
arFields | An array of the format Array(field1=>value1[, field2=>value2 [, ..]]), where field - field name; value - field value. The fields are listed in the List of profile fields.
strUploadDir | Directory in which files are to be uploaded. Must be specified relative to the main upload directory. Optional. The default value is "forum".

Return Values

Returns the ID of the modified profile on success, or false otherwise.

See Also

  • Profile fields


CForumNew

CForumUserPoints

The CForumUserPoints class is used with voting of the forum users for other forum users.

Methods

Method | Description
GetList | Returns a filtered and sorted list of votes for forum visitors.
GetByID | Returns voting parameters by its ID.
Add | Adds a new vote that one forum user gives to another.
Update | Modifies the existing parameters of a vote.
Delete | Deletes a vote.


Add

CForumUserPoints::Add

bool
CForumUserPoints::Add(
 array arFields
);

The method Add adds a new record to the table of forum visitors votes.

Parameters

Parameter | Description
arFields | Associated array of values of record parameters.

Return Values

The method returns the ID of the added record on success, or false otherwise.

Example

<?
// The current user gives his 10 votes to the user $UID

$arFields = array(
   "POINTS" => 10,
   "FROM_USER_ID" => $USER->GetID(),
   "TO_USER_ID" => $UID
);

if (CForumUserPoints::Add($arFields))
   echo "Votes have been successfully given";
else
   echo "Error in voting";
?>


Delete

CForumUserPoints::Delete

bool
CForumUserPoints::Delete(
 int FROM_USER_ID,
 int TO_USER_ID
);

The method Delete deletes votes given by the user FROM_USER_ID to the user TO_USER_ID.

Parameters

Parameter | Description
FROM_USER_ID | The ID of the user who has given his vote.
TO_USER_ID | The ID of the user who has been given a vote to.

Return Values

The method returns true on success, or false otherwise.


GetByID

CForumUserPoints::GetByID

array
CForumUserPoints::GetByID(
 int FROM_USER_ID,
 int TO_USER_ID
);

The method GetByID returns an array describing votes of the user FROM_USER_ID given to the user TO_USER_ID.

Parameters

Parameter | Description
FROM_USER_ID | The ID of the user who has given his vote.
TO_USER_ID | The ID of the user to whom a vote has been given.

Return Values

Returns an associated array containing the following keys:

Key | Value
FROM_USER_ID | The ID of the user who has given his vote.
TO_USER_ID | The ID of the user to whom a vote has been given.
POINTS | Number of votes given.
DATE_UPDATE | The date the record was last modified.

Example

<?
// Display the number of votes the current user has given
// to the user $AID
$arUserPoints = CForumUserPoints::GetByID($USER->GetID(), $AID);
if ($arUserPoints)
{
   echo "You have given ".$arUserPoints["POINTS"]. " votes to this user";
}
?>


GetList

CForumUserPoints::GetList

CDBResult
CForumUserPoints::GetList(
 array arOrder = array("TO_USER_ID"=>"ASC"),
 array arFilter = array()
);

The method GetList returns a filtered and sorted list of votes for forum visitors.

Parameters

Parameter Description
arOrder Associated array whose keys are the names of voting parameters and values are the sort order constants.

The following voting parameters can be sorted:
  • FROM_USER_ID - the ID of the user who has given a vote;
  • TO_USER_ID - the ID of the user to whom a vote has been given;
  • POINTS - number of votes given;
  • DATE_UPDATE - the date when the record was last modified;
arFilter

Filter for the returned voting. Associated array whose keys are the names of voting parameters and values are the conditions for these parameters.

The following voting parameters can be filtered:

  • FROM_USER_ID - the ID of the user who has given a vote;
  • TO_USER_ID - the ID of the user who has been given a vote to.

Return Values

Returns an object of the CDBResult class, each record containing the following keys:

Key | Value
FROM_USER_ID | The ID of the user who has given a vote.
TO_USER_ID | The ID of the user to whom a vote has been given.
POINTS | Number of votes given.
DATE_UPDATE | The date when the record was last modified.


Update

CForumUserPoints::Update

bool
CForumUserPoints::Update(
 int FROM_USER_ID,
 int TO_USER_ID,
 array arFields
);

The method Update modifies the existing parameters of a vote that a user FROM_USER_ID has given to a user TO_USER_ID.

Parameters

Parameter | Description
FROM_USER_ID | The user who has given a vote.
TO_USER_ID | The user to whom a vote has been given.
arFields | Array of new parameters of a vote.

Return Values

Returns true on success, or false otherwise.

Example

<?
// Change the number of votes (that the current user has given to
// the user $UID) to 53
$arFields = array("POINTS" => 53);
if (CForumUserPoints::Update($USER->GetID(), $UID, $arFields))
   echo "Voting is successfully changed";
else
   echo "Error updating votes";
?>


textParser

The textParser class is used to format forum messages. Replaces special symbols and custom tags with the real HTML tags and processes links and displays smiles.

Methods

Method | Description
convert | Formats the message text.


convert

string
convert(
 string strPost_message,
 array arAllow
);

The function convert formats the message text.

Parameters

Parameter | Description
strPost_message | Text to be formatted.
arAllow Array of parameters of the text formatting. Has the structure similar to the array ALLOW of the CForum class variable. Contains the following parameters which can be set to Y or N:
  • HTML - allow all HTML tags in text;
  • ANCHOR - allow tag <a>;
  • BIU - allow tag <b>, <i>, <u>;
  • IMG - allow tag <img>;
  • QUOTE - allow tag <quote>;
  • CODE - allow tag <code>;
  • FONT - allow tag <font>,
  • LIST - allow tag <ul>, <li>;
  • SMILES - converts smiles as images ;
  • NL2BR - replace CR(+LF) with <br> if HTML is set to Y.

Example

<?
$parser = new textParser();  // create textParser
$arAllow = $Forum->ALLOW;    // fill the formatting array
                             // from the CForum class member array
                             // the two arrays are identical
$arAllow["SMILES"] = "N";    // forbid smileys as icons

// format and display a message
echo $parser->convert($strMessage, $arAllow);
?>


ForumAddMessage

int
ForumAddMessage(
 string MESSAGE_TYPE,
 int FID,
 int TID,
 int MID,
 array arFieldsG,
 &string strErrorMessage,
 &string strOKMessage [,
 int iFileSize]
);

The function ForumAddMessage adds or modifies a forum post (and/or topic). The function appends description of errors to strErrorMessage, and reports of the function successful execution to strOKMessage.

Parameters

Parameter | Description
MESSAGE_TYPE Type of action. The following values are possible:
  • NEW - creates of a new topic and adds a post to it;
  • EDIT - modifies a post (and a topic if the user has corresponding permissions);
  • REPLY - adds a new post to an existing topic.
FID | The ID of the forum to which a new topic is added. Should be specified for the "NEW" MESSAGE TYPE.
TID | The ID of the topic to which the message is added. Should be specified for the "REPLY" MESSAGE TYPE, or to 0 for the "NEW" MESSAGE TYPE.
MID | The ID of the message to modify. Should be specified for the "ADD" MESSAGE TYPE, or to 0 for other values.
arFieldsG Array containing parameters of the message and topic. Should contain the following keys:
  • POST_MESSAGE - the message body;
  • TITLE - the topic title (for NEW and EDIT and if the topic modification is permitted);
  • AUTHOR_NAME - the message author name;
  • DESCRIPTION - the topic description (for NEW and EDIT and if the topic modification is permitted);
  • ICON_ID - the topic icon ID (for NEW and EDIT and if the topic modification is permitted);
  • USE_SMILES - allow replacing smiles with icons;
  • ATTACH_IMG - attached file; an array having the same structure as $_FILES.
strErrorMessage | On return, this variable contains description of errors, if any occurs.
strOKMessage | On return, this variable contains description of the successful run.
iFileSize | Max size of files allowed for upload. Optional, 50000 bytes by default.

Return Values

Returns the ID of the message on success or false otherwise.


ForumCurrUserPermissions

char(1)
ForumCurrUserPermissions(
 int FID
);

Returns the code of the current user permission to access the specified forum.

Parameters

Parameter | Description
FID | The ID of the forum to be checked.

Return Values

Returns the code of the current user permission to access the specified forum:
  • A - deny - the current user cannot view this forum;
  • E - read - the current user can view this forum but cannot post new messages;
  • I - reply - the current user can write to existing topics but cannot create new ones;
  • M - new topic - the current user can both write to existing topics and create new ones;
  • Q - moderate - the current user can moderate the forum, i.e. perform actions that will not incur loss of information. For example, the moderator can show or hide a message, but cannot edit or delete it. Moderators receive all new posts via the e-mail.
  • U - edit - the current user can fully manage the forums message;
  • Y - full access - the current user has full access to the forum including forum settings and access rights.

The site administrators always have the full access to all forums.

See Also

  • Create/edit a forum


ForumModerateMessage

bool
ForumModerateMessage(
 int MID,
 char(1) TYPE,
 &string strErrorMessage,
 &string strOKMessage
);

Publishes or hides the specified message.

Parameters

Parameter | Description
MID | The ID of the message to publish or hide.
TYPE | If "SHOW", the message is published. If "HIDE", the message is hidden.
strErrorMessage | On return, this variable contains description of errors, if any occurs.
strOKMessage | On return, this variable contains description of the successful run.

Return Values

Returns true on success or false otherwise.


ForumSubscribeNewMessages

bool
ForumSubscribeNewMessages(
 int FID,
 int TID,
 &string strErrorMessage,
 &string strOKMessage
);

Subscribes the current visitor to new messages of the specified forum topic (if specified), or to all messages of the entire forum.

Parameters

Parameter | Description
FID | The ID of the forum to whose messages the current user wants to subscribe.
TID | The ID of the forum topic. If specified, the user is subscribed to new messages of this topic only.
strErrorMessage | On return, this variable contains description of errors, if any occurs.
strOKMessage | On return, this variable contains description of the successful run.

Return Values

Returns true on success or false otherwise.


Functions for use in the public section

These functions perform various checks of permissions and correctness of parameters; you can just call the desired function to fulfil the required operation.

Function | Description
ForumCurrUserPermissions | Returns the code of the current user permission to access the specified forum.
ForumSubscribeNewMessages | Subscribes the current visitor to new messages of the specified forum topic (if specified), or to all messages of the entire forum.
ForumAddMessage | Adds or modifies a forum post (and/or topic).
ForumModerateMessage | Publishes or hides the specified message.


Information Blocks API - Bitrix Site Manager - Content Management & Portal Solutions

Overview

The Information Blocks module implements a powerful and very flexible means used to store and access information in a diverse number of ways. The module API consists of several high-level functions intended for data access in the public section, and a set of classes encapsulating low-level methods for more specialised solutions.

Before you start calling any of the module functions or use its classes, you should check its availability and include it using the following code:

<?
if(CModule::IncludeModule("iblock"))
{
   // call module functions here
}
?>

High level methods

A set of simple is provided that can be used to obtain data for displaying in the public section. These functions require simple parameters and provide the filter presets for easy operation. The functions are configured to return only the values appropriate for the calling location; that is, only values in active state, pertaining to the current site, appropriate for the current access rights etc.

Public high level functions

Method | Description
GetIBlockList | Returns a list of information blocks. Allows using filters.
GetIBlock | Returns an information block by its ID.
GetIBlockElementListEx | Returns a list of information block elements. Allows using filters.
GetIBlockElementList | Returns a list of information block elements.
GetIBlockElement | Returns an information block element by its ID.
GetIBlockSectionList | Returns a list of information block folders.
GetIBlockSection | Returns a section by its ID.

Low level methods

If the problem is more specific and the above described functions are insufficient to solve the problem, or you need to modify data, you should use a set of classes exposing the full functionality of the Information Blocks module.

Classes of the Information Blocks module

Method | Description
CIBlockType | Deals with the information blocks types.
CIBlock | General information block class.
CIBlockProperty | Comprises the information block properties.
CIBlockPropertyEnum | Allows access to values of the type LIST.
CIBlockSection | Deals with the information block sections.
CIBlockElement | Exposes elements and values of their properties.
CIBlockResult | Worker class for handling the selection objects.
_CIBElement | Worker class for handling the element selection objects.


Structure of the information blocks tables - Bitrix Site Manager - Content Management & Portal Solutions

Structure of the information blocks tables

Fields

Types of information blocks

Field | Description | Type | Required | Default
ID | Unique ID of an information block type. | String(50) | Yes |
SECTIONS | Flag (Y or N). Specifies whether this block contain sections. Required. | Char(1) | Yes | Y
EDIT_FILE_BEFORE | Full path to the element field array file handler called before an element is saved from the element editing page. | String(255) |  |
EDIT_FILE_AFTER | Full path to the element editing user interface file handler. | String(255) |  |
IN_RSS | Denotes that blocks of this type can be exported to RSS (Y|N). | Char(1) |  | N
SORT | Type sort order. | Int |  | 500

Language-dependent parameters of an information block type

Field | Description | Type | Required | Default
IBLOCK_TYPE_ID | Block type ID. | String(50) | Yes |
LID | ID of the parameters language. | Char(2) | Yes |
NAME | Name of an information block type. | String(100) | Yes |
SECTION_NAME | Name of the information block sections (if present). | String(100) | No |
ELEMENT_NAME | Name of the information block elements. | String(100) | No |

Information Blocks

Field | Description | Type | Required | Default
ID | Information block ID. | Int | Yes |
CODE | Mnemonic identifier (alias). | String(50) | No |
EXTERNAL_ID | External ID. | String(255) | No |
IBLOCK_TYPE_ID | Information block type ID. | String(50) | Yes |
TIMESTAMP_X | Date of the last modification of the block parameters. | Datatime | Yes | Current
NAME | Name. | Int | Yes |
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
SORT | Sort weight. | Int | Yes | 500
LIST_PAGE_URL | Template of the page URL used for the block elements public view. | String(255) | No |
SECTION_PAGE_URL | Template of the page URL used to view the block section. | String(255) | No |
DETAIL_PAGE_URL | Template of the page URL used for the element detailed view. | String(255) | No |
PICTURE | Picture ID in the file table. | Int | No |
DESCRIPTION | Description. | Text | No |
DESCRIPTION_TYPE | Description type (text/html) | Char(4) | Yes | Text
RSS_ACTIVE | Allows the dynamic export to RSS (Y|N) | Char(1) | Yes | Y
RSS_TTL | RSS time to live and interval between each build of an RSS file, in hours (requires RSS_FILE_ACTIVE or RSS_YANDEX_ACTIVE to be set) | Int | Yes | 24
RSS_FILE_ACTIVE | Export RSS to a file. | Char(1) | Yes | N
RSS_FILE_LIMIT | Number of elements exported to an RSS file (requires RSS_FILE_ACTIVE) | Int | No |
RSS_FILE_DAYS | Number of days to export to an RSS file (requires RSS_FILE_ACTIVE). -1 means no day limit. | Int | No |
INDEX_ELEMENT | Specifies the information block elements should be indexed for searching. | Char(1) | Yes | Y
INDEX_SECTION | Specifies the information block sections should be indexed for searching. | Char(1) | Yes | N

Information Blocks Sections

Field | Description | Type | Required | Default
ID | Section ID. | Int | Yes |
CODE | Mnemonic identifier (alias). | String(255) | No |
EXTERNAL_ID | External ID. | String(255) | No |
IBLOCK_ID | Information block ID. | Int | Yes |
IBLOCK_SECTION_ID | Parent section ID. Void for root sections. | Int | No |
TIMESTAMP_X | Date of the last modification. | Datetime | Yes | Current
SORT | Sort order (among sections within one parent group). | Int | Yes | 500
NAME | Section name. | String(255) | Yes |
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
GLOBAL_ACTIVE | Active state flag with respect to the state of parent groups. Read-only. | Char(1) | - | -
PICTURE | Picture ID in the file table. | Int | No |
DESCRIPTION | Description of a section. | Text | No |
DESCRIPTION_TYPE | Description type (text/html). | Char(4) | Yes | Text
LEFT_MARGIN | Left margin of a section. Calculated automatically. Read-only. | Int | - | -
RIGHT_MARGIN | Right margin of a section. Calculated automatically. Read-only. | Int | - | -
DEPTH_LEVEL | Section nesting level. Calculated automatically. Read-only. | Int | - | -
SEARCHABLE_CONTENT | Data used for search operations when filtering sections. Calculated automatically. Composed of the fields NAME and DESCRIPTION (latter without the HTML tags). | Text | - | -
SECTION_PAGE_URL | Template of the page URL used for the detailed view of the section. Defined by the information block parameters. Modified automatically. | String(255) |  |

Elements
Field | Description | Type | Required | Default
ID | Element ID. | Int | Yes
CODE | Mnemonic identifier (alias). | String(255) | No
EXTERNAL_ID | External ID. | String(255) | No
NAME | Element name. | String(255) | Yes
IBLOCK_ID | Information block ID. | Int | Yes
IBLOCK_SECTION_ID | Section ID. Void if the element does not belong to section. If the element belongs to more than one section, this field contains the ID of one of the sections. | Int | No
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
DATE_ACTIVE_FROM | Date the element is active from. | Datetime | No
DATE_ACTIVE_TO | Expiry date of the element. | Datetime | No
SORT | Sort weight of an element within one parent section. | Int | Yes | 500
PREVIEW_PICTURE | Thumbnail picture ID in the file table. | Int | No
PREVIEW_TEXT | Short description text (announcement). | Text | No
PREVIEW_TEXT_TYPE | Type of the short description text (text/html). | Char(4) | Yes | Text
DETAIL_PICTURE | Detailed picture ID in the file table. | Int | No
DETAIL_TEXT | Full text of the element contents. | Text | No
DETAIL_TEXT_TYPE | Type of the full text (text/html). | Char(4) | Yes | Text
SEARCHABLE_CONTENT Data used for search operations when filtering sections. Calculated automatically. Composed of the fields NAME and DESCRIPTION (the latter without the HTML tags). Text - -
EXTERNAL_ID | External ID. | String(255) | No
DATE_CREATE | Date of the element creation. | Datetime | Yes | Current
CREATED_BY | ID of a user who created the element. | Int | Yes | Current user
CREATED_USER_NAME | Name of a user who created the element. Read-only.
TIMESTAMP_X | Date of the last element modification. | Datetime | Yes | Current
MODIFIED_BY | ID of a user who modified the element the last time. | Int | Yes | Current user
USER_NAME | Name of a user who modified the element the last time. Read-only.
LANG_DIR Path to the site folder. Inferred from the information block parameters. Modified automatically. String(255) - -
LIST_PAGE_URL Template of the page URL used for the public view of the information block elements. Inferred from the information block parameters. Modified automatically. String(255) - -
DETAIL_PAGE_URL Template of the page URL used for the detailed view of the information block elements. Inferred from the information block parameters. Modified automatically. String(255) - -
SHOW_COUNTER | Number of the element shows. Changed upon each call of the function CIBlockElement::CounterInc. | Int | No
SHOW_COUNTER_START | Date of the first show of the element. Changed upon each call of the function CIBlockElement::CounterInc. | Datetime | No
WF_COMMENTS | Comment of the workflow administrator. | Text | No
WF_STATUS_ID | ID of the element status in the workflow. | Int | Yes | 1
LOCK_STATUS Current lock state of the element. Can have the following values:
  • red - locked;
  • greed - available for editing;
  • yellow - locked by the current user.
 String -

Properties

Field | Description | Type | Required | Default
ID | Property ID. | Int | Yes |
CODE | Property mnemonic code (alias). | String(50) | No |
EXTERNAL_ID | External ID of a property. | Int | No | 100
IBLOCK_ID | ID of an information block. | Int | Yes |
NAME | Name of a property. | String(100) | Yes |
ACTIVE | Property active state flag (Y|N). | Char(1) | Yes | Y
SORT | Sort weight. | Int | Yes | 500
PROPERTY_TYPE | Property type. Possible values: S - string, F - file, L - list. | Char(1) | Yes | S
MULTIPLE | Indicates the multiple property set. | Char(1) | Yes | N
TIMESTAMP_X | Date of the last property modification. | Datetime | Yes | Current
DEFAULT_VALUE | Default value of a property (except type L). | String(255) | No |
ROW_COUNT | Number of rows in the input field. | Int | Yes | 1
COL_COUNT | Number of columns in the input field. | Int | Yes | 30
LIST_TYPE | Type of the list type (L). Can be "L" (drop-down list) or "C" (check boxes). | Char(1) | Yes | L
MULTIPLE_CNT | Number of rows in the drop-down list for properties of the LIST type. | Int | No |
FILE_TYPE | Comma-separated list of acceptable file extensions for properties of the type FILE. | Char(200) | No |
SEARCHABLE | Specifies the property value should be indexed. | Char(1) | Yes | N
FILTRABLE | Specifies the fields for filtering by this property should be displayed int he administrative section. | Char(1) | Yes | N

Possible values for properties of the type LIST

Field | Description | Type | Required | Default
ID | Value ID. | int | Yes |
PROPERTY_ID | Property ID. | int | Yes |
VALUE | Value of the property. | string(255) | Yes |
DEF | Denotes this value is default (Y|N). | char(1) | No | N
SORT | Sort weight of the variant. | int | No | 500
EXTERNAL_ID | External ID of the property variant. | string(200) | No |

Property values

Field | Description | Type | Required | Default
ID | ID of a value. |  | Yes |
IBLOCK_PROPERTY_ID | Property ID. |  | Yes |
IBLOCK_ELEMENT_ID | Element ID. |  | Yes |
VALUE | Value itself. |  | Yes |
VALUE_TYPE | Type of a value (text/html). |  | Yes |


Creating custom forms for the information block elements editing - Bitrix Site Manager - Content Management & Portal Solutions

Creating custom forms for the information block elements editing

The information block element creation and/or editing web form is undoubtedly one of the most frequently used ones. Furthermore, the Internet online stores and mass media find this kind of a web form the most popular in administration sections of their sites. Despite the fact that the form design and fields are automatically adjusted according to the information block settings and parameters, or that the Information Blocks module had been developed to cover the widest possible range of tasks, sometimes users find it desirable to customize a form according to their specific needs.

Consider an example of the editing form creation for a generic Interned media periodical.

A common article requires the following fields to exist in the form:

  • article title;
  • preamble text;
  • preamble picture;
  • article text;
  • large picture;
  • article publication date;
  • author;
  • workflow status for the Editor's approval;
  • list of sections to bind the article.
The process of the information block creation and customization is detailed in the help section. We shall only consider the lacking and redundant elements compared to the standard editing form:
  • a number of excessive fields (sorting, expiry date etc.);
  • the form field order should be altered;
  • automatic generation of thumbnails from the full large picture would be convenient;
  • the article body and title fields need to be made the required ones;
  • the custom form should automatically set the publication time.

We shall elaborate on the original code of /bitrix/modules/iblock/admin/iblock_element_edit.php, namely the customizable part of the code:

<form method="POST" action="iblock_element_edit.php?type=<?echo $type?>&lang=<?echo LANG?>&IBLOCK_ID=<?echo $IBLOCK_ID?>&<?echo GetFilterParams("filter_");?>#tb" ENCTYPE="multipart/form-data" name="form_element">
<?echo GetFilterHiddens("filter_");?>
<input type="hidden" name="Update" value="Y">
<input type="hidden" name="from" value="<?echo htmlspecialchars($from)?>">
<input type="hidden" name="WF" value="<?echo htmlspecialchars($WF)?>">
<input type="hidden" name="return_url" value="<?echo $return_url?>">
<input type="hidden" name="ID" value="<?echo $ID?>">
<input type="hidden" name="IBLOCK_SECTION_ID" value="<?echo IntVal($IBLOCK_SECTION_ID)?>">
<table border="0" cellspacing="1" cellpadding="3" class="edittable" width="100%">
    <?if ($WF=="Y" || $view=="Y"):?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?=GetMessage("IBLOCK_WF_STATUS")?></font></td>
        <td valign="top" nowrap><font class="tablebodytext">
        <?echo SelectBox("WF_STATUS_ID", CWorkflowStatus::GetDropDownList("N", "desc"), "", $str_WF_STATUS_ID);?></font></td>
    </tr>
    <?endif;?>
    <?
    if($ID>0):
        $p = CIblockElement::GetByID($ID);
        $pr = $p->ExtractFields("prn_");

        if(CModule::IncludeModule("workflow")):
            if(strlen($pr["DATE_CREATE"])>0):
            ?>
                <tr>
                    <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_CREATED")?></font></td>
                    <td valign="top"><font class="tablebodytext"><?echo $pr["DATE_CREATE"]?><?
                    if (intval($pr["CREATED_BY"])>0):
                    ?>&nbsp;&nbsp;&nbsp;[<a class="tablebodylink" href="user_edit.php?lang=<?=LANG?>&ID=<?=$pr["CREATED_BY"]?>"><?echo $pr["CREATED_BY"]?></a>]&nbsp;<?=htmlspecialcharsex($pr["CREATED_USER_NAME"])?><?
                    endif;
                    ?></font></td>
                </tr>
            <?endif;?>
            <tr>
                <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_LAST_UPDATE")?></font></td>
                <td valign="top"><font class="tablebodytext"><?echo $str_TIMESTAMP_X?><?
                if (intval($str_MODIFIED_BY)>0):
                ?>&nbsp;&nbsp;&nbsp;[<a class="tablebodylink" href="user_edit.php?lang=<?=LANG?>&ID=<?=$str_MODIFIED_BY?>"><?echo $str_MODIFIED_BY?></a>]&nbsp;<?=$str_USER_NAME?><?
                endif;
                ?></font></td>
            </tr>
        <?endif?>
        <?if($WF=="Y" && strlen($prn_WF_DATE_LOCK)>0):?>
        <tr>
            <td valign="top" align="right" nowrap><font class="tablefieldtext"><?echo GetMessage("IBLOCK_DATE_LOCK")?></font></td>
            <td valign="top" nowrap><font class="tablebodytext"><?echo $prn_WF_DATE_LOCK?><?
            if (intval($prn_WF_LOCKED_BY)>0):
            ?>&nbsp;&nbsp;&nbsp;[<a class="tablebodylink" href="user_edit.php?lang=<?=LANG?>&ID=<?=$prn_WF_LOCKED_BY?>"><?echo $prn_WF_LOCKED_BY?></a>]&nbsp;<?=$prn_LOCKED_USER_NAME?><?
            endif;
            ?></font></td>
        </tr>
        <?endif;?>
    <?endif;?>
    <tr>
        <td valign="top" width="50%" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_ACTIVE")?></font></td>
        <td valign="top" width="50%"><input type="checkbox" name="ACTIVE" value="Y"<?if($str_ACTIVE=="Y")echo " checked"?>></td>
    </tr>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_ACTIVE_PERIOD")?>(<?echo CLang::GetDateFormat("SHORT");?>)</font></td>
        <td valign="top"><font class="tablebodytext">
            <?echo CalendarPeriod("ACTIVE_FROM", $str_ACTIVE_FROM, "ACTIVE_TO", $str_ACTIVE_TO, "form_element", "N", "class=\"typeselect\"", "class=\"typeinput\"", "19")?>
        </font>
        </td>
    </tr>
    <?if($arIBTYPE["SECTIONS"]=="Y"):?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_SECTION")?></font></td>
        <td valign="top" align="left">
        <?$l = CIBlockSection::GetTreeList(Array("IBLOCK_ID"=>$IBLOCK_ID));?>
        <select name="IBLOCK_SECTION[]" size="14" multiple class="typeselect">
            <option value="0"<?if(is_array($str_IBLOCK_ELEMENT_SECTION) && in_array(0, $str_IBLOCK_ELEMENT_SECTION))echo " selected"?>><?echo GetMessage("IBLOCK_CONTENT")?></option>
        <?
            while($l->ExtractFields("l_")):
                ?><option value="<?echo $l_ID?>"<?if(is_array($str_IBLOCK_ELEMENT_SECTION) && in_array($l_ID, $str_IBLOCK_ELEMENT_SECTION))echo " selected"?>><?echo str_repeat(" . ", $l_DEPTH_LEVEL)?><?echo $l_NAME?></option><?
            endwhile;
        ?>
        </select>
        </td>
    </tr>
    <?endif?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><font class="required">*</font><?echo GetMessage("IBLOCK_NAME")?></font></td>
        <td valign="top">
            <input type="text" name="NAME" size="50" maxlength="255" class="typeinput" value="<?echo $str_NAME?>">
        </td>
    </tr>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_SORT")?></font></td>
        <td valign="top">
            <input type="text" name="SORT" size="7" class="typeinput" maxlength="10" value="<?echo $str_SORT?>">
        </td>
    </tr>
    <?if(COption::GetOptionString("iblock", "show_xml_id", "N")=="Y"):?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_EXTERNAL_CODE")?></font></td>
        <td valign="top">
            <input type="text" size="20" name="XML_ID" maxlength="255" class="typeinput" value="<?echo $str_XML_ID?>">
        </td>
    </tr>
    <?endif?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_CODE")?></font></td>

        <td valign="top">
            <input type="text" size="20" name="CODE" maxlength="255" class="typeinput" value="<?echo $str_CODE?>">
        </td>
    </tr>
    <?if(count($PROP)>0):?>
    <tr>
        <td valign="top" align="center" colspan="2" class="tablehead"><font class="tableheadtext"><b><?echo GetMessage("IBLOCK_ELEMENT_PROP_VALUE");?></b></font></td>
    </tr>
    <?
    foreach($PROP as $prop_code=>$prop_fields):
        $prop_values = $prop_fields["VALUE"];
    ?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo htmlspecialcharsex($prop_fields["NAME"])?>:</font></td>
        <td valign="top">
        <font class="tablebodytext"><?_ShowPropertyField('PROP['.$prop_fields["ID"].']', $prop_fields, $prop_values, ((!$bVarsFromForm) && ($ID<=0)), $bVarsFromForm);?></font>
    </td>
    </tr>
    <?endforeach;?>
    <?endif?>

    <tr>
        <td valign="top" align="center" colspan="2" class="tablehead" nowrap><font class="tableheadtext"><b><?echo GetMessage("IBLOCK_ELEMENT_PREVIEW")?></b></font></td>
    </tr>
    <tr>
        <td valign="top" align="right" class="tablebody" nowrap><font class="tablefieldtext"><?echo GetMessage("IBLOCK_PICTURE")?></font></td>
        <td valign="top" align="left" class="tablebody"><font class="tablebodytext">
            <?echo CFile::InputFile("PREVIEW_PICTURE", 20, $str_PREVIEW_PICTURE, false, 0, "IMAGE", "class=\"typefile\"", 40);?><br>
            <?echo CFile::ShowImage($str_PREVIEW_PICTURE, 200, 200, "border=0", "", true)?>
            </font>
        </td>
    </tr>

    <?if(ereg('(MSIE|Internet Explorer) ([0-9]).([0-9])+', $_SERVER['HTTP_USER_AGENT'], $version) && IntVal($version[2])>=5 && COption::GetOptionString("iblock", "use_htmledit", "Y")=="Y" && CModule::IncludeModule("fileman")):?>
    <tr>
        <td valign="top" colspan="2">
            <?CFileMan::AddHTMLEditorFrame("PREVIEW_TEXT", $str_PREVIEW_TEXT, "PREVIEW_TEXT_TYPE", $str_PREVIEW_TEXT_TYPE, 300);?>
        </td>
    </tr>
    <?else:?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_DESC_TYPE")?></font></td>
        <td valign="top">
            <font class="tablebodytext">
                <input type="radio" name="PREVIEW_TEXT_TYPE" value="text"<?if($str_PREVIEW_TEXT_TYPE!="html")echo " checked"?>> <?echo GetMessage("IBLOCK_DESC_TYPE_TEXT")?> / <input type="radio" name="PREVIEW_TEXT_TYPE" value="html"<?if($str_PREVIEW_TEXT_TYPE=="html")echo " checked"?>> <?echo GetMessage("IBLOCK_DESC_TYPE_HTML")?>
            </font>
        </td>
    </tr>
    <tr>
        <td valign="top" align="center"colspan="2" width="100%">
            <textarea cols="110" class="typearea" rows="10" name="PREVIEW_TEXT" wrap="virtual"><?echo $str_PREVIEW_TEXT?></textarea>
        </td>
    </tr>
    <?endif?>
    <tr>
        <td valign="top" align="center" colspan="2" class="tablehead" nowrap><font class="tableheadtext"><b><?echo GetMessage("IBLOCK_ELEMENT_DETAIL")?></b></font></td>
    </tr>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_PICTURE")?></font></td>
        <td valign="top"><font class="tablebodytext">
            <?echo CFile::InputFile("DETAIL_PICTURE", 20, $str_DETAIL_PICTURE, false, 0, "IMAGE", "class=\"typefile\"", 40);?><br>
            <?echo CFile::ShowImage($str_DETAIL_PICTURE, 200, 200, "border=0", "", true)?>
            </font>
        </td>
    </tr>
    <?if(ereg('(MSIE|Internet Explorer) ([0-9]).([0-9])+', $_SERVER['HTTP_USER_AGENT'], $version) && IntVal($version[2])>=5 && COption::GetOptionString("iblock", "use_htmledit", "Y")=="Y" && CModule::IncludeModule("fileman")):?>
    <tr>
        <td valign="top" colspan="2">
            <?CFileMan::AddHTMLEditorFrame("DETAIL_TEXT", $str_DETAIL_TEXT, "DETAIL_TEXT_TYPE", $str_DETAIL_TEXT_TYPE, 440);?>
        </td>
    </tr>
    <?else:?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo GetMessage("IBLOCK_DESC_TYPE")?></font></td>
        <td valign="top">
            <font class="tablebodytext">
                <input type="radio" name="DETAIL_TEXT_TYPE" value="text"<?if($str_DETAIL_TEXT_TYPE!="html")echo " checked"?>> <?echo GetMessage("IBLOCK_DESC_TYPE_TEXT")?> / <input type="radio" name="DETAIL_TEXT_TYPE" value="html"<?if($str_DETAIL_TEXT_TYPE=="html")echo " checked"?>> <?echo GetMessage("IBLOCK_DESC_TYPE_HTML")?>
            </font>
        </td>
    </tr>
    <tr>
        <td valign="top" align="center" colspan="2">
            <textarea cols="110" rows="20" class="typearea" name="DETAIL_TEXT" wrap="virtual"><?echo $str_DETAIL_TEXT?></textarea>
        </td>
    </tr>
    <?endif?>
    <?if (CModule::IncludeModule("workflow")):?>
    <tr>
        <td class="tablehead" align="center" colspan="2"><font class="tableheadtext"><b><?=GetMessage("IBLOCK_COMMENTS")?></b></font></td>
    </tr>
    <tr>
        <td valign="top" align="center" colspan="2">
            <textarea name="WF_COMMENTS" class="typearea" cols="110" rows="10"><?echo $str_WF_COMMENTS?></textarea></td>
    </tr>
    <?endif?>
    <?
    if ($view!="Y" && CModule::IncludeModule("catalog") && CCatalog::GetByID($IBLOCK_ID))
    {
        include($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/catalog/admin/templates/product_edit.php");
    }
    ?>
</table>
<br>
<input <?if ($view=="Y" || $prn_LOCK_STATUS=="red") echo "disabled";?> type="submit" class="button" name="save" value="<?echo (($ID > 0)?GetMessage('IBLOCK_SAVE'):GetMessage('IBLOCK_ADD'))?>">
&nbsp;
<input <?if ($view=="Y" || $prn_LOCK_STATUS=="red") echo "disabled";?> class="button" type="submit" name="apply" value="<?echo GetMessage('IBLOCK_APPLY')?>">
&nbsp;
<input <?if ($view=="Y" || $prn_LOCK_STATUS=="red") echo "disabled";?> type="submit" class="button" name="dontsave" value="<? echo GetMessage("IBLOCK_DONT_SAVE") ?>">
&nbsp;
<input type="reset" value="<?echo GetMessage('IBLOCK_RESET');?>" class="button">
</form>

Save this script to a file, say /bitrix/php_interface/include/iblock_element_edit.php. Create the file /bitrix/php_interface/include/iblock_element_edit_before_save.php at the same location. The latter file will contain an element save handler script. Specify paths to these files in the Information Blocks module settings (for the required information block type) in fields Save operation handler and File with element editing form.

The spade-work is finished; now let us get down to the form design. Delete the unnecessary fields and re-layout the page /bitrix/php_interface/include/iblock_element_edit.php according to our requirements. The below is the resulting page code after the modification.

<form method="POST" action="iblock_element_edit.php?type=<?echo $type?>&lang=<?echo LANG?>&IBLOCK_ID=<?echo $IBLOCK_ID?>&<?echo GetFilterParams("filter_");?>#tb" ENCTYPE="multipart/form-data" name="form_element">
<?echo GetFilterHiddens("filter_");?>
<input type="hidden" name="Update" value="Y">
<input type="hidden" name="from" value="<?echo htmlspecialchars($from)?>">
<input type="hidden" name="WF" value="<?echo htmlspecialchars($WF)?>">
<input type="hidden" name="return_url" value="<?echo $return_url?>">
<input type="hidden" name="ID" value="<?echo $ID?>">
<input type="hidden" name="IBLOCK_SECTION_ID" value="<?echo IntVal($IBLOCK_SECTION_ID)?>">
<table border="0" cellspacing="1" cellpadding="3" class="edittable" width="100%">
    <?
    $prop_code = "AUTHOR";
    $prop_fields = $PROP[$prop_code];
    $prop_values = $prop_fields["VALUE"];
    ?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><?echo htmlspecialcharsex($prop_fields["NAME"])?>:</font></td>
        <td valign="top">
        <font class="tablebodytext"><?_ShowPropertyField('PROP['.$prop_fields["ID"].']', $prop_fields, $prop_values, ((!$bVarsFromForm) && ($ID<=0)), $bVarsFromForm);?></font>
    </td>
    </tr>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext">Date (<?echo CLang::GetDateFormat("SHORT");?>)</font></td>
        <td valign="top"><font class="tablebodytext">
            <?echo CalendarDate("ACTIVE_FROM", $str_ACTIVE_FROM, "form_element", "20", "class=\"typeinput\"")?>
        </font>
        </td>
    </tr>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext"><font class="required">*</font>Title</font></td>
        <td valign="top">
            <textarea name="NAME" cols="50" rows="5" class="typearea"><?echo $str_NAME?></textarea>
        </td>
    </tr>
    <tr>
        <td valign="top" align="center" colspan="2" class="tablehead" nowrap><font class="tableheadtext"><b>Preamble</b></font></td>
    </tr>
    <?if(ereg('(MSIE|Internet Explorer) ([0-9]).([0-9])+', $_SERVER['HTTP_USER_AGENT'], $version) && IntVal($version[2])>=5 && COption::GetOptionString("iblock", "use_htmledit", "Y")=="Y" && CModule::IncludeModule("fileman")):?>
    <tr>
        <td valign="top" colspan="2">
            <?CFileMan::AddHTMLEditorFrame("PREVIEW_TEXT", $str_PREVIEW_TEXT, "PREVIEW_TEXT_TYPE", $str_PREVIEW_TEXT_TYPE, 300);?>
        </td>
    </tr>
    <?else:?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext">Preamble type:</font></td>
        <td valign="top">
            <font class="tablebodytext">
                <input type="radio" name="PREVIEW_TEXT_TYPE" value="text"<?if($str_PREVIEW_TEXT_TYPE!="html")echo " checked"?>> Body / <input type="radio" name="PREVIEW_TEXT_TYPE" value="html"<?if($str_PREVIEW_TEXT_TYPE=="html")echo " checked"?>> HTML
            </font>
        </td>
    </tr>
    <tr>
        <td valign="top" align="center"colspan="2" width="100%">
            <textarea cols="110" class="typearea" rows="10" name="PREVIEW_TEXT" wrap="virtual"><?echo $str_PREVIEW_TEXT?></textarea>
        </td>
    </tr>
    <?endif?>
    <tr>
        <td valign="top" align="center" colspan="2" class="tablehead" nowrap><font class="tableheadtext"><b>Article</b></font></td>
    </tr>
    <?if(ereg('(MSIE|Internet Explorer) ([0-9]).([0-9])+', $_SERVER['HTTP_USER_AGENT'], $version) && IntVal($version[2])>=5 && COption::GetOptionString("iblock", "use_htmledit", "Y")=="Y" && CModule::IncludeModule("fileman")):?>
    <tr>
        <td valign="top" colspan="2">
            <?CFileMan::AddHTMLEditorFrame("DETAIL_TEXT", $str_DETAIL_TEXT, "DETAIL_TEXT_TYPE", $str_DETAIL_TEXT_TYPE, 440);?>
        </td>
    </tr>
    <?else:?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext">Body text type:</font></td>
        <td valign="top">
            <font class="tablebodytext">
                <input type="radio" name="DETAIL_TEXT_TYPE" value="text"<?if($str_DETAIL_TEXT_TYPE!="html")echo " checked"?>> Text / <input type="radio" name="DETAIL_TEXT_TYPE" value="html"<?if($str_DETAIL_TEXT_TYPE=="html")echo " checked"?>> HTML
            </font>
        </td>
    </tr>
    <tr>
        <td valign="top" align="center" colspan="2">
            <textarea cols="110" rows="20" class="typearea" name="DETAIL_TEXT" wrap="virtual"><?echo $str_DETAIL_TEXT?></textarea>
        </td>
    </tr>
    <?endif?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext">Large picture</font></td>
        <td valign="top"><font class="tablebodytext">
            <?echo CFile::InputFile("DETAIL_PICTURE", 20, $str_DETAIL_PICTURE, false, 0, "IMAGE", "class=\"typefile\"", 40);?><br>
            <?echo CFile::ShowImage($str_DETAIL_PICTURE, 200, 200, "border=0", "", true)?>
            </font>
        </td>
    </tr>
    <tr>
        <td valign="top" align="right" class="tablebody" nowrap><font class="tablefieldtext">Picture in list:</font></td>
        <td valign="top" align="left" class="tablebody"><font class="tablebodytext">
            <input type="checkbox" name="MAKE_PREVIEW_PICTURE" value="Y" onClick="document.getElementById('PREVIEW_PICTURE').disabled=this.checked;">Create from large picture<br>
            <?echo CFile::InputFile("PREVIEW_PICTURE", 20, $str_PREVIEW_PICTURE, false, 0, "IMAGE", "class=\"typefile\"", 40);?><br>
            <?echo CFile::ShowImage($str_PREVIEW_PICTURE, 200, 200, "border=0", "", true)?>
            </font>
        </td>
    </tr>
    <?if($arIBTYPE["SECTIONS"]=="Y"):?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext">Sections:</font></td>
        <td valign="top" align="left">
        <?$l = CIBlockSection::GetTreeList(Array("IBLOCK_ID"=>$IBLOCK_ID));?>
        <select name="IBLOCK_SECTION[]" size="14" multiple class="typeselect">
            <option value="0"<?if(is_array($str_IBLOCK_ELEMENT_SECTION) && in_array(0, $str_IBLOCK_ELEMENT_SECTION))echo " selected"?>>Unbound</option>
        <?
            while($l->ExtractFields("l_")):
                ?><option value="<?echo $l_ID?>"<?if(is_array($str_IBLOCK_ELEMENT_SECTION) && in_array($l_ID, $str_IBLOCK_ELEMENT_SECTION))echo " selected"?>><?echo str_repeat(" . ", $l_DEPTH_LEVEL)?><?echo $l_NAME?></option><?
            endwhile;
        ?>
        </select>
        </td>
    </tr>
    <?endif?>
    <tr>
        <td valign="top" align="center" colspan="2" class="tablehead"><font class="tableheadtext"><b>Validity and workflow</b></font></td>
    </tr>
    <?if ($WF=="Y" || $view=="Y"):?>
    <tr>
        <td valign="top" align="right"><font class="tablefieldtext">Status:</font></td>
        <td valign="top" nowrap><font class="tablebodytext">
        <?echo SelectBox("WF_STATUS_ID", CWorkflowStatus::GetDropDownList("N", "desc"), "", $str_WF_STATUS_ID);?></font></td>
    </tr>
    <?endif;?>
    <?
    if($ID>0):
        $p = CIblockElement::GetByID($ID);
        $pr = $p->ExtractFields("prn_");

        if(CModule::IncludeModule("workflow")):
            if(strlen($pr["DATE_CREATE"])>0):
            ?>
                <tr>
                    <td valign="top" align="right"><font class="tablefieldtext">Created:</font></td>
                    <td valign="top"><font class="tablebodytext"><?echo $pr["DATE_CREATE"]?><?
                    if (intval($pr["CREATED_BY"])>0):
                    ?>&nbsp;&nbsp;&nbsp;[<a class="tablebodylink" href="user_edit.php?lang=<?=LANG?>&ID=<?=$pr["CREATED_BY"]?>"><?echo $pr["CREATED_BY"]?></a>]&nbsp;<?=htmlspecialcharsex($pr["CREATED_USER_NAME"])?><?
                    endif;
                    ?></font></td>
                </tr>
            <?endif;?>
            <tr>
                <td valign="top" align="right"><font class="tablefieldtext">Modified:</font></td>
                <td valign="top"><font class="tablebodytext"><?echo $str_TIMESTAMP_X?><?
                if (intval($str_MODIFIED_BY)>0):
                ?>&nbsp;&nbsp;&nbsp;[<a class="tablebodylink" href="user_edit.php?lang=<?=LANG?>&ID=<?=$str_MODIFIED_BY?>"><?echo $str_MODIFIED_BY?></a>]&nbsp;<?=$str_USER_NAME?><?
                endif;
                ?></font></td>
            </tr>
        <?endif?>
        <?if($WF=="Y" && strlen($prn_WF_DATE_LOCK)>0):?>
        <tr>
            <td valign="top" align="right" nowrap><font class="tablefieldtext">Locked:</font></td>
            <td valign="top" nowrap><font class="tablebodytext"><?echo $prn_WF_DATE_LOCK?><?
            if (intval($prn_WF_LOCKED_BY)>0):
            ?>&nbsp;&nbsp;&nbsp;[<a class="tablebodylink" href="user_edit.php?lang=<?=LANG?>&ID=<?=$prn_WF_LOCKED_BY?>"><?echo $prn_WF_LOCKED_BY?></a>]&nbsp;<?=$prn_LOCKED_USER_NAME?><?
            endif;
            ?></font></td>
        </tr>
        <?endif;?>
    <?endif;?>
    <?if (CModule::IncludeModule("workflow")):?>
    <tr>
        <td valign="top" align="center" colspan="2">
            <textarea name="WF_COMMENTS" class="typearea" cols="110" rows="10"><?echo $str_WF_COMMENTS?></textarea></td>
    </tr>
    <?endif?>
</table>
<br>
<input <?if ($view=="Y" || $prn_LOCK_STATUS=="red") echo "disabled";?> type="submit" class="button" name="save" value="<?echo (($ID > 0)?"Edit":"Add")?>">
&nbsp;
<input <?if ($view=="Y" || $prn_LOCK_STATUS=="red") echo "disabled";?> class="button" type="submit" name="apply" value="Apply">
&nbsp;
<input <?if ($view=="Y" || $prn_LOCK_STATUS=="red") echo "disabled";?> type="submit" class="button" name="dontsave" value="Quit without saving">
</form>

The design is ready. Now we have to create the save operation handler. The arrays $_POST and $_FILES contain the saved fields and values that we may need to alter. The array $PROP contains the form properties.

Add the following condition to check for the article body text:

if (strlen($_POST['DETAIL_TEXT'])<=0)
    $error = new _CIBlockError(2,
                               'DESCRIPTION_REQUIRED',
                               'Please provide the article body.');

The _CIBlockError constructor takes 3 parameters: error severity, an identifier and the error description. If the editing form appears to have a variable named $error containing an instance of this class, no changes will be saved.

Redefine the field $_POST["ACTIVE_FROM"] to automatically set the article publication date:

if ($_POST["WF_STATUS_ID"]==1 &&
    strlen($_POST["ACTIVE_FROM"])<=0)
{
    $_POST["ACTIVE_FROM"] = date("m.d.Y H:i:s");
}

Please note that this code does not respect the language preferences for the date format. If you need the format other than DD.MM.YYYY HH:MI:SS, handle it appropriately.

To automatically create the picture thumbnail that would be built on the large one, we need to create the handler function BXIBlockAfterSave. Being defined before an element is saved, it is automatically called upon the successful save operation. Define it in the beginning of the file /bitrix/php_interface/include/iblock_element_edit_before_save.php:

<?
function BXIBlockAfterSave($arFields)
{
    if($_POST['MAKE_PREVIEW_PICTURE']=='Y')
    {
        $dbr = CIBlockElement::GetByID($arFields['ID']);
        if (($ar = $dbr->Fetch()) &&
            $ar['DETAIL_PICTURE']>0)
        {
            $img_path = $_SERVER['DOCUMENT_ROOT'].CFile::GetPath($ar['DETAIL_PICTURE']);
            $width = 200;
            $height = 200;
            list($width_orig, $height_orig) = getimagesize($img_path);
            if($width && ($width_orig < $height_orig))
               $width = ($height / $height_orig) * $width_orig;
            else
               $height = ($width / $width_orig) * $height_orig;
            $image_p = imagecreatetruecolor($width, $height);
            $image = imagecreatefromjpeg($img_path);
            imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
            $new_img_path = tempnam("/tmp", "FOO").".jpg";
            imagejpeg($image_p, $new_img_path);
            $be = new CIBlockElement();
            $be->Update($arFields['ID'], Array('PREVIEW_PICTURE'=>CFile::MakeFileArray($new_img_path)), false);
            @unlink($new_img_path);
        }
    }
}
?>

The above script creates a thumbnail from the large image and sets the appropriate thumbnail field if the flag MAKE_PREVIEW_PICTURE is set to "Y". The example is effective for JPEG images only.

The same function can be used to clear the cache of pages with the saved article:

function BXIBlockAfterSave($arFields)
{
    if ($arFields['WF_STATUS_ID']==1)
    {
        BXClearCache(true, "/en/main_page/");
        BXClearCache(true, "/en/detail/".$arFields['ID']."/");
    }
}

That's all. We have got the form fully accustomed to our requirements. The changes of the completely different nature may be needed sometimes. For example, a form for uploading and editing a number of images may be required. In this case, simply create a new page and add it to the administrative menu.

The following is the complete code of the page /bitrix/php_interface/include/iblock_element_edit_before_save.php.

<?
if ($REQUEST_METHOD=="POST" &&
    strlen($Update)>0 &&
    $view!="Y" &&
    (!$error) &&
    empty($dontsave) &&
    strlen($_POST['DETAIL_TEXT']) <= 0)
{
    $error = new _CIBlockError(2, "DESCRIPTION_REQUIRED", "Please type the article body");
}
elseif ($_POST["WF_STATUS_ID"] == 1 &&
        strlen($_POST["ACTIVE_FROM"]) <= 0)
{
    $_POST["ACTIVE_FROM"] = date("d.m.Y H:i:s");
}

function BXIBlockAfterSave($arFields)
{
    if($_POST['MAKE_PREVIEW_PICTURE']=='Y')
    {
        $dbr = CIBlockElement::GetByID($arFields['ID']);
        if(($ar = $dbr->Fetch()) &&
            $ar['DETAIL_PICTURE']>0)
        {
            $img_path = $_SERVER['DOCUMENT_ROOT'].CFile::GetPath($ar['DETAIL_PICTURE']);
            $width = 200;
            $height = 200;
            list($width_orig, $height_orig) = getimagesize($img_path);
            if($width && ($width_orig < $height_orig))
               $width = ($height / $height_orig) * $width_orig;
            else
               $height = ($width / $width_orig) * $height_orig;
            $image_p = imagecreatetruecolor($width, $height);
            $image = imagecreatefromjpeg($img_path);
            imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
            $new_img_path = tempnam("/tmp", "FOO").".jpg";
            imagejpeg($image_p, $new_img_path);
            $be = new CIBlockElement();
            $be->Update($arFields['ID'], Array('PREVIEW_PICTURE'=>CFile::MakeFileArray($new_img_path)), false);
            @unlink($new_img_path);
            die($new_img_path);
        }
    }

    if($arFields['WF_STATUS_ID']==1)
    {
        BXClearCache(true, "/en/main_page/");
        BXClearCache(true, "/en/detail/".$arFields['ID']."/");
    }
}
?>


RSS - Bitrix Site Manager - Content Management & Portal Solutions

RSS

The RSS is the format developed for the exchange of information (mainly news) between sites. The RSS format is built on the XML specification. You can obtain the detailed information on the RSS 2.0 format here: http://backend.userland.com/rss.

Terms used

Channel
Information block in the RSS format.
Server site
It's a site that exports (transmits) information in the RSS format.
Client site
It's a site that imports (receives) information in the RSS format.
Caching
This means the temporary storage of information obtained from a server site, on a client site, to accelerate repeated access to it.
Channel node
Element of an information block e.g. news or product in the RSS format.

Export to the RSS

There are three ways to export the information block content to the RSS format.

Dynamic ("on-the-fly") generation of an RSS file upon the client site request

To enable this method, check the box Allow dynamic RSS export in the information block settings, and set the amount of time after which a client site will have to re-request information from a server site in the field Valid (hours) (during this period a client site will use the cached information).

The access to an RSS file comes to requesting the file /bitrix/rss.php from a server site with parameters ID, LANG, TYPE and LIMIT in the URL.

Request parameters
Parameter | Description
ID | Information block ID, or the symbolic code of the section.
LANG | Site of the information block.
TYPE | Type of the information block.
LIMIT | Maximum number of information block elements to export.

Sample request

http://www.bitrixsoft.com/bitrix/rss.php?ID=3&LANG=ru&TYPE=news&LIMIT=3

Pregeneration of an RSS file

Enabling this method requires checking the flag Allow export to RSS file in the information block settings and set the fields Number of exported elements (limits the maximum number of elements exported to a file; set to -1 to remove restrictions) and Export last days (restricts the exported elements to those dated and active within the specified number of days; set to -1 to remove restrictions).

The RSS file is generated repeatedly at intervals specified in the field Valid (hours) and saved to a file with the name like iblock_rss_<block ID>.xml to the folder specified in the module settings.

To access the RSS file, a client site requests the file http://<server site>/<folder specified in the module settings>/iblock_rss_<block ID>.xml.

Sample request
http://www.bitrixsoft.com/upload/iblock_rss_3.xml

RSS channel element structure

By default, the node <item> is built as follows:

<item>
  <title>Field "Name of information block element"</title>
  <link>Field "Detailed view page URL"</link>
  <description>Field "Brief description" of an information block element.
               If this field is empty, the field "Full description" is used.</description>
  <pubDate>Field "Active period" of the information block.</pubDate>
  <enclosure url="URL of an image loaded in the field "Brief description" of an information block element"
             length="Size of the image file"
             type="Type of the image file"
             width="Width of an image"
             height="Height of an image"/>
</item>

You can alter the generation parameters on the information block editing page, section RSS export fields assignment. The RSS fields can have any text values. Besides that, use of parameter templates is permitted. Parameters should be specified in the form of #NAME#. Parameter names can be the property codes as well as the following values:

  • NAME - title of an information block element;
  • DETAIL_PAGE_URL - address of a page containing detailed view of an element;
  • PREVIEW_TEXT - brief description;
  • DETAIL_TEXT - detailed description;
  • ACTIVE_FROM - start of the active period.

Import from the RSS

To receive the information, a client site should call the method CIBlockRSS::GetNewsEx. The method GetNews is also supported but is now obsolete and is not recommended.

array
CIBlockRSS::GetNewsEx(
 SITE,
 PORT,
 PATH,
 QUERY_STR
);

The method returns a channel from the cache (if it is not expired) or from a server site.

Request parameters

Parameter | Description
SITE | Address of a server site. For example, "www.bitrixsoft.com".
PORT | Port of a server site. For example, 80.
PATH | Path to the RSS file on the server site. For example, "/bitrix/rss.php".
QUERY_STR | Query string (if required). For example, ID=3&LANG=ru&TYPE=news&LIMIT=5. Please note that the query string should conform the HTTP specification.

Return value

The function returns an array with the information from the requested RSS file.

Samples

<?
CModule::IncludeModule("iblock");
$arRes = CIBlockRSS::GetNewsEx("www.bitrix.com",
                               80, "/bitrix/rss.php",
                               "ID=3&LANG=ru&TYPE=news&LIMIT=5");
$arRes = CIBlockRSS::FormatArray($arRes);

echo $arRes["title"];          // Title of a channel or block
echo $arRes["link"];           // Server site URL
echo $arRes["description"];    // Description of a channel or block
echo $arRes["lastBuildDate"];  // File timestamp on the server site
echo $arRes["ttl"];            // Time-to-live

echo $arRes["image"]["title"];   // Image title if present
echo $arRes["image"]["url"];     // Link to the image file if present
echo $arRes["image"]["width"];   // Width of the image file if present
echo $arRes["image"]["height"];  // Height of the image file if present

echo $arRes["item"][0]["title"];       // Title of the first news
echo $arRes["item"][1]["title"];       // Title of the second news
echo $arRes["item"][1]["link"];        // Link to the second news
echo $arRes["item"][1]["description"]; // Description of the second news
echo $arRes["item"][1]["pubDate"];     // Date of the second news publication
echo $arRes["item"][1]["enclosure"]["url"];     // Link to the second news attachment
echo $arRes["item"][1]["enclosure"]["length"];  // Size of the second news attachment file
echo $arRes["item"][1]["enclosure"]["type"];    // MIME-type of the second news attachment
echo $arRes["item"][1]["enclosure"]["width"];   // Width of the second news enclosed image
echo $arRes["item"][1]["enclosure"]["height"];  // Height of the second news enclosed image

?>

<?
CModule::IncludeModule("iblock");
$arRes = CIBlockRSS::GetNewsEx("www.bitrixsoft.com",
                               80, "/bitrix/rss.php",
                               "ID=demo&LANG=en&TYPE=news&LIMIT=5");
$arRes = CIBlockRSS::FormatArray($arRes);
?>
<b><?echo $arRes["title"] ?></b><br>

<table cellpadding="2" cellspacing="0" border="0" width="80%">
  <?for ($i = 0; $i < count($arRes["item"]); $i++):?>
  <tr>
    <td width="100%">
      <font class="date">
        <?echo $arRes["item"][$i]["pubDate"]?>
      </font>&nbsp;|&nbsp;
      <?if (strlen($arRes["item"][$i]["link"])>0):?>
        <a href="<?echo $arRes["item"][$i]["link"]?>" class="title">
      <?endif;?>
      <?echo $arRes["item"][$i]["title"]?>
      <?if (strlen($arRes["item"][$i]["link"])>0):?>
        </a>
      <?endif;?>
      <br>
    </td>
  </tr>
  <tr>
    <td valign="top" width="100%">
      <?if (strlen($arRes["item"][$i]["enclosure"]["url"])>0):?>
        <table cellpadding="0" cellspacing="0" border="0" align="left">
          <tr>
            <td valign="top">
              <img
               src="<?echo $arRes["item"][$i]["enclosure"]["url"] ?>"
               width="<?echo $arRes["item"][$i]["enclosure"]["width"] ?>"
               height="<?echo $arRes["item"][$i]["enclosure"]["height"]?>"
               border="0">
            </td>
          </tr>
        </table>
      <?endif;?>
      <font class="text">
        <?echo $arRes["item"][$i]["description"];?>
        <br>
      </font>
    </td>
  </tr>
  <?endfor;?>
</table>
© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Filters

A majority of functions and methods of the Information Blocks module, namely those used to retrieve lists, allow using different filters to specify search conditions. The filter type operators are specified right before the name of the filter field.

Types

  • (empty) - for the string fields denotes search using a mask (the mask notation: "%" - any number of arbitrary symbols; "_" - any one symbol). For fields of non-string types, this means strict match searching.

<?
// find elements whose name starts from "#"
$res = CIBlockElement::GetList(Array(), Array("NAME"=>"#%"));

// find elements with the ID == 100
$res = CIBlockElement::GetList(Array(), Array("ID"=>"100"));
?>
  • "!" - for the string fields denotes expression that does not match a mask, or not equal for other types.

<?
// find elements whose name does not start with "#"
$res = CIBlockElement::GetList(Array(), Array("!NAME"=>"#%"));
?>
  • "?" - means the logic is used:

<?
// find elements whose name contains "One" or "Two"
$res = CIBlockElement::GetList(Array(), Array("?NAME"=>"One | Two"));
?>
  • "<" - less
  • "<=" - less or equal
  • ">" - more
  • ">=" - more or equal

<?
// find elements whose name starts with "A"
$res = CIBlockElement::GetList(Array(),
                               Array(">=NAME"=>"A", "<NAME"=>"B"));

// find elements whose ID is more than 100
$res = CIBlockElement::GetList(Array(), Array(">ID"=>"100"));
?>
  • "=" - equal
  • "!=" - not equal:

<?
// find elements whose name is "ELEMENT%1"
$res = CIBlockElement::GetList(Array(), Array("=NAME"=>"ELEMENT%1"));
?>
  • "%" - substring,
  • "!%" - not substring:

<?
// find elements whose name contains the symbol "%"
$res = CIBlockElement::GetList(Array(), Array("%NAME"=>"%"));
?>
  • "<>" - between,
  • "!<>" - not between. These filters takes an array in the format Array("lower bound of a range", "higher bound of a range") on input:

<?
// find elements whose name starts
// between "A" and "B" or between "D" and "E"
$res = CIBlockElement::GetList(Array(),
                               Array("><NAME"=>Array(Array("A", "B"),
                                                     Array("D", "E"))));

// find elements whose active state
// date is not within 2003
$res = CIBlockElement::GetList(Array(), Array("!><DATE_ACTIVE_FROM"=>
    Array(
        date($DB->DateFormatToPHP(CLang::GetDateFormat("FULL")),
                   mktime(0,0,0,1,1,2003)),
        date($DB->DateFormatToPHP(CLang::GetDateFormat("FULL")),
                   mktime(0,0,0,1,1,2004))
    )));
?>


Storing properties in dedicated tables

Introduction

Since version 5.1, developers can choose how and where the properties of an information block element are located. Properties can now be stored in dedicated tables, and all property values of an element can be saved in a single row. The following notes should be taken into consideration.

  1. When selecting elements, property values can be obtained immediately because the count of tables does not increase and is always 1.
  2. The same rule apply to filtering by property values (with the exception of multiple properties).
  3. Fetching values of multiple properties now does not result in Cartesian multiplication of query results - property values are passed in an array.
  4. For complex filters with simple (not multiple) properties, the database aggregative index can now be created manually for faster selection operations.
  5. For information blocks that store property values in dedicated tables, elements cannot be selected transparently (with the filter set to an information block type and a property symbolic code). IBLOCK_ID has to be specified in the filter.

API remains fully compatible. You can use the same programming approaches as before. However, you can take advantage of the new techniques: for example, calling CIBlockElement::GetProperty is now redundant after obtaining property values using CIBlockElement::GetList.

Information blocks

Information blocks now have a new field: VERSION. This allows developers to choose the type of storage for information block property values: in a public or dedicated storage. In the latter case, two new tables are created for an information block in the database; the names of these tables include the information block ID. One of the tables store multiple properties, the other one stores simple and cached values of multiple properties.

The information block editing form displays a link that activates the storage type converter. Use extreme care with this feature, since the duration of conversion depends on the amount of property values. During conversion, the information block is in unstable state because some values are converted but some are not. A test MySQL configuration indicated speed of 1500 elements per 20 second step.

The class CIBlockResult now overrides Fetch. It now caches values of obtained multiple properties. For the "list" properties, it selects pairs ID=>VALUE from the list dictionary.

An array of fields ($arFields) of CIBlock::Add now supports the "VERSION" field . It can be 1 - for public storage and 2 - for dedicated storage.

Information block properties

There are no changes to information block properties in the administration interface, nor in the Control Panel.

When editing properties (toggling the "Multiple" flag or changing the property type), additional support operations are performed in the dedicated storages. These include adding/deleting columns, insertion, removal or updating of many records. You should avoid editing dedicated properties if possible. The best practice would be to change the type or the "multiple" flag at a single run. For simple properties, the best order of operations is to make them multiple and then change the type. For multiple properties, change the type and then make them simple.

Information block elements

The major changes occurred to the GetList method. These changes was highlighted in the Introduction.

When an element is added, a corresponding record is added to a table that stores values of element properties.

Values of information block element properties

The ID's of values of simple properties of dedicated information blocks are synthetic. It consists of ID's of an element and a property separated with colon (:).

When a multiple property is updated, the cache is reset.

Property values are stored in 2 tables. The table description is for reference only and is subject to change:

  • b_iblock_element_prop_mNN - for multiple properties. Has the same structure as b_iblock_element_property;
  • b_iblock_element_prop_sNN - for single properties. Has a field IBLOCK_ELEMENT_ID - the ID of an information block element to which the following properties belong:
    • PROPERTY_XX - stores values of a simple property XX or cached values of a multiple property;
    • DESCRIPTION_XX - stores the simple property description.

Power use of new information blocks. Programming techniques

To take advantages that a new storage structure can give, you have to alter the programming logic of components.

For example: consider a piece of an old-fashioned code:

<?
// Define an array of the required fields
$arSelect = array(
    "ID",
    "IBLOCK_ID",
    "IBLOCK_SECTION_ID",
    "NAME",
    "PREVIEW_PICTURE",
    "DETAIL_PICTURE",
    "DETAIL_PAGE_URL",
);

// Get the list of elements (+1 query)
if($rsElements = GetIBlockElementListEx($IBLOCK_TYPE,
                                        false, false,
                                        array($ELEMENT_SORT_FIELD => $ELEMENT_SORT_ORDER),
                                        $ELEMENT_COUNT,
                                        $arFilter, $arSelect))
{
    // Initialise pagewise display.
    $rsElements->NavStart($ELEMENT_COUNT);
    $count = intval($rsElements->SelectedRowsCount());
    if ($count>0)
    {
        // For each element:
        while ($obElement = $rsElements->GetNextElement())
        {
            $arElement = $obElement->GetFields();

            // Obtain element properties (+1 query)
            $arProperty = $obElement->GetProperties();

            // Now we can use property values
            // example:
            echo $arProperty["SOURCE"],"<br>";
            // etc.
        }
    }
}
?>

Now, having converted to a new storage mode, we can avoid requests in loops:

<?
// Define an array of the required fields
$arSelect = array(
    "ID",
    "IBLOCK_ID",
    "IBLOCK_SECTION_ID",
    "NAME",
    "PREVIEW_PICTURE",
    "DETAIL_PICTURE",
    "DETAIL_PAGE_URL",
    "PROPERTY_SOURCE", // Specify the required property
    // ...                and any other that we may need
    // ...                right here!
);

// Get the list of elements (+1 query)
if($rsElements = GetIBlockElementListEx($IBLOCK_TYPE,
                                        false, false,
                                        array($ELEMENT_SORT_FIELD => $ELEMENT_SORT_ORDER),
                                        Array("nPageSize"=>$ELEMENT_COUNT),
                                        $arFilter, $arSelect))
{
    // Initialise pagewise display.
    $rsElements->NavStart($ELEMENT_COUNT);
    if($obElement = $rsElements->GetNextElement())
    {
        // Do for each element:
        do
        {
            $arElement = $obElement->GetFields();

            // Now we can use property values
            // example:
            echo $arElement["PROPERTY_SOURCE"],"<br>";
            // etc.
        }
        while ($obElement = $rsElements->GetNextElement())
    }
}
?>
© 2001-2007 Bitrix Bitrix Site Manager


Infromation blocks classes - Bitrix Site Manager - Content Management & Portal Solutions

Classes

The following classes are used in development using the Information Block module.

CIBlockElement

CIBlockElement allows various types of operations on information blocks.

Method | Description
GetList | Returns a list of elements. Filters allowed.
GetByID | Returns an element by its ID.
GetElementGroups | Takes the element ID and returns sections to which the element is bound.
GetProperty | Obtains the element properties.
Add | Adds a new element.
Update | Updates an element.
Delete | Deletes an element from an information block.
SetElementSection | Binds an information block element to sections.
SetPropertyValues | Updates a set of the element properties.
SetPropertyValueCode | Modifies the value of the element property.
UpdateSearch | Indexes an element in the search module.
CounterInc | Increments the element shows counter.

CIBlockSection

CIBlockSection is the class for handling the information block sections.

Method | Description
GetList | Returns a filtered list of sections.
GetByID | Returns a section by its ID.
Add | Adds a new section to an information block.
Update | Updates a section.
Delete | Deletes a section from an information block.
GetCount | Returns the number of sections.
GetSectionElementsCount | Returns the number of elements in the section.
GetTreeList | Returns a list of sections sorted in the order of the fully expanded tree.
GetNavChain | Returns the path from the root to the section.
ReSort | Recalculates the left and right margins.

CIBlock

CIBlock is the general class for use with information blocks.

Method | Description
ShowPanel | Adds the block, section and element control buttons to the site toolbar.
SetPermission | Assigns the user group permissions to access an information block.
GetProperties | Returns the information block properties.
GetGroupPermissions | Returns access permissions to the information block.
GetPermission | Retrieves access permissions of the current user.
GetList | Returns the filtered list of information blocks.
GetByID | Returns the block by the ID.
Add | Adds a new block.
Update | Updates an information block.
Delete | Deletes an information block.

CIBlockProperty

CIBlockProperty allows handling the information block properties.

Method | Description
GetList | Returns a filtered list of properties.
GetByID | Returns a property by the ID.
Add | Adds a new property.
Update | Updates the property parameters.
Delete | Deletes a property.
GetPropertyEnum | Enumerates the LIST property variants.
UpdateEnum | Updates the array of the property enumeration results.

CIBlockPropertyEnum

CIBlockPropertyEnum is used for handling values of properties of the type LIST.

Method | Description
GetList | Returns a filtered list of variants.
Add | Adds a new variant.
Update | Updates a variant.
Delete | Deletes the property variant.

CIBlockType

CIBlockType provides the programming interface to the information block types.

Method | Description
GetList | Returns a filtered list of types.
GetByID | Returns a type by the ID.
Add | Adds a new type.
Update | Updates a set of the type parameters.
Delete | Delete the block type.

CIBlockResult

CIBlockResult is the helper class for handling the results of operations.

Method | Description
GetNext | Returns an array of the selected fields.
GetNextElement | Returns an instance of _CIBElement from the selection.

_CIBElement

_CIBElement is the helper class for handling the element selection objects.

Method | Description
GetFields | Returns the fields of an element.
GetProperty | Returns the value of an element property.
GetProperties | Returns values of a set of the element properties.
GetGroups | Returns a list of sections to which the element is bound.


CIBlock - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock

CIBlock is the general class for use with information blocks.

Class methods

Method | Description
GetList | Returns the filtered list of information blocks.
GetSite | Returns a list of sites to which the information block is bound.
GetByID | Returns the block by the ID.
GetProperties | Returns the information block properties.
GetPermission | Retrieves access permissions of the current user.
Add | Adds a new block.
Update | Updates an information block.
Delete | Deletes an information block.
SetPermission | Assigns the user group permissions to access an information block.
GetGroupPermissions | Returns access permissions to the information block.
ShowPanel | Adds the block, section and element control buttons to the site toolbar.


CIBlock::Add - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::Add

int
CIBlock::Add(
 array arFields
);

Adds a new information block.

Parameters

Parameter Description
arFields An array of the format Array("field"=>"value", ...).

Contains values of all fields of an information block. The field SITE_ID must contain an array of identifiers of the sites to which the new block is to be bound.

The field GROUP_ID with an array of pairs "user group code=>access permission" may be used to set the access permissions for different user groups to the information block (see CIBlock::SetPermission).

Return Values

The method returns the ID of the created information block on success, or false otherwise. In the latter case, the property LAST_ERROR contains the error code.

See Also

  • CIBlock::Update
  • Fields of information blocks

    Example

    <?
$arPICTURE = $_FILES["PICTURE"];
$ib = new CIBlock;
$arFields = Array(
  "ACTIVE" => $ACTIVE,
  "NAME" => $NAME,
  "CODE" => $CODE,
  "LIST_PAGE_URL" => $LIST_PAGE_URL,
  "DETAIL_PAGE_URL" => $DETAIL_PAGE_URL,
  "IBLOCK_TYPE_ID" => $type,
  "SITE_ID" => Array("en", "de"),
  "SORT" => $SORT,
  "PICTURE" => $arPICTURE,
  "DESCRIPTION" => $DESCRIPTION,
  "DESCRIPTION_TYPE" => $DESCRIPTION_TYPE,
  "GROUP_ID" => Array("2"=>"D", "3"=>"R")
  );
if ($ID > 0)
  $res = $ib->Update($ID, $arFields);
else
{
  $ID = $ib->Add($arFields);
  $res = ($ID>0);
}
?>


CIBlock::Delete - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::Delete

bool
CIBlock::Delete(
 int ID
);

The method deletes an information block.

Parameters

Parameter | Description
ID | Information block ID.

Return Values

Returns true on success, or false otherwise.

Example

<?
if($USER->IsAdmin())
{
    $DB->StartTransaction();
    if(!CIBlock::Delete($iblock_id))
    {
        $strWarning .= GetMessage("IBLOCK_DELETE_ERROR");
        $DB->Rollback();
    }
    else
        $DB->Commit();
}
?>


CIBlock::GetByID - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::GetByID

CDBResult
CIBlock::GetByID(
 int ID
);

Returns an information block by the ID.

Parameters

Parameter | Description
ID | Information block ID.

Return Values

Returns an instance of CDBResult.

See Also

  • CDBResult
  • Result fields

    Example

    <?
$res = CIBlock::GetByID($_GET["BID"]);
if ($ar_res = $res->GetNext())
    echo $ar_res['NAME'];
?>


CIBlock::GetByID - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::GetSite

CDBResult
CIBlock::GetSite(
 int iblock_id
);

Returns a list of sites to which the information block is bound.

Parameters

Parameter | Description
iblock_id | Information block ID.

Return Values

Returns an instance of CDBResult with the site fields.

See Also

  • CDBResult
  • Fields of CSite

    Example

    <?
$db_iblock_type = CIBlockType::GetList();
while($ar_iblock_type = $db_iblock_type->Fetch())
{
   if($arIBType = CIBlockType::GetByIDLang($ar_iblock_type["ID"], LANG))
   {
      echo htmlspecialcharsex($arIBType["NAME"])."<br>";
   }
}
?>


CIBlock::GetGroupPermissions - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::GetGroupPermissions

array
CIBlock::GetGroupPermissions(
 int ID
);

Returns access permissions to the information block for all user groups.

Parameters

Parameter | Description
ID | Information block ID.

Return Values

An array of the format Array("user group ID"=>"Permission"[, ...]). The permission can be one of the following: "D" - deny, "R" - read-only, "U" - edit through the workflow, "W" - write, "X" - full access (write + right to alter the permissions).

See Also

  • GetPermission

    Example

    <?
// select a list of users who can read the block $IBLOCK_ID
$gr_res = CIBlock::GetGroupPermissions($IBLOCK_ID);
$res = Array(1);
foreach($gr_res as $group_id=>$perm)
if ($perm>"R")
    $res[] = $group_id;
$res = CUser::GetList($by="NAME", $order="ASC", Array("GROUP_MULTI"=>$res));
?>


CIBlock::GetList - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::GetList

CDBResult
CIBlock::GetList(
 array arOrder = Array("SORT"=>"ASC"),
 array arFilter = Array(),
 bool bIncCnt = false
);

Returns a list of information blocks filtered by arFilter and sorted by arOrder.

Parameters

Parameter | Description
arOrder Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • id - section ID;
  • iblock_type - section type;
  • name - name;
  • active - active state;
  • sort - sort weight;
  • active - active sign;
  • element_cnt - number of elements (if bIncCnt is true);
  • timestamp_x - modification date;
order is the sort order. Can be asc for ascending sorts or desc for descending.

Default value is Array("sort"=>"asc"). Full list of sorting fields and additional information can be found in CIBlockElement::GetList()
arFilter Optional additional filter by fields in the form of Array("Filter field"=>"filter values", ...). The Filtering field can be one of the following:
  • ACTIVE - by the active state (Y|N);
  • NAME - by names (wildcards [%_] allowed);
  • EXTERNAL_ID, XML_ID - by external ID;
  • SITE_ID - by site;
  • TYPE - by the section type;
  • CODE - by mnemonic identifier;
  • ID - by the ID;
  • CNT_ACTIVE (if only bIncCnt is true). If set to "Y", only the active elements are counted and the result is set as the value of the field ELEMENT_CNT. Otherwise, all elements are counted;
  • CNT_ALL (if only bIncCnt is true). If set to "Y", the unpublished elements are also counted and the result is set as the value of the field ELEMENT_CNT. Otherwise, all other elements are only counted.
All the filtering fields may have the conditions specified before the name.

The "filter values" are a single value or an array.

The default parameter value is an empty array.
bIncCnt | Specifies that the number of elements of the information block is to be returned in the field ELEMENT_CNT. Optional. The default value is false.

Return Values

Returns an instance of CDBResult.

See Also

  • CDBResult
  • CIBlock fields

    Example

    <?
// select all active information blocks of the type catalog of the current site
// selection is limited to all blocks with mnemonic code other than my_products,
// return the number of active elements.
$res = CIBlock::GetList(
    Array(),
    Array(
        'TYPE'=>'catalog',
        'SITE_ID'=>SITE_ID,
        'ACTIVE'=>'Y',
        "CNT_ACTIVE"=>"Y",
        "!CODE"=>'my_products'
    ), true
);
while($ar_res = $res->Fetch())
{
    echo $ar_res['NAME'].': '.$ar_res['ELEMENT_CNT'];
}
?>


CIBlock::GetPermission - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::GetPermission

string
CIBlock::GetPermission(
 int IBLOCK_ID
);

Returns the current user permissions to access the block identified by the IBLOCK_ID.

Parameters

Parameter | Description
IBLOCK_ID | Information block ID.

Return Values

Returns a character describing the access permissions:

  • "D" - deny;
  • "R" - read;
  • "U" - modify through the workflow;
  • "W" - write;
  • "X" - full access (write + access permissions modification).

See Also

  • GetGroupPermissions

    Example

    <?
$iblock_permission = CIBlock::GetPermission($id);
if ($iblock_permission<"X")
    return false;
?>


CIBlock::GetProperties - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::GetProperties

CDBResult
CIBlock::GetProperties(
 int iblock_id,
 array arOrder=Array(),
 array arFilter=Array()
);
Returns properties of an information block by its identifier. The returned properties may be sorted and the filter may be applied.

Parameters

Parameter | Description
iblock_id | Information block ID.
arOrder | Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. See CIBlockProperty::GetList() for the full description of the sorting fields.
arFilter | Optional additional filter by fields in the form of Array("Filtered field"=>"Value", ...). See CIBlockProperty::GetList() for the full description of fields and values.

Return Values

Returns an instance of CDBResult.

See Also

  • Property fields
  • CIBlockProperty::GetList()

    Example

    <?
$res = CIBlock::GetProperties($IBLOCK_ID, Array(), Array("CODE"=>"SRC"));
if ($res_arr = $res->Fetch())
    $SrcPropID = $res_arr["ID"];
else
{
    $arFields = Array(
        "NAME"          => "Import source",
        "ACTIVE"        => "Y",
        "SORT"          => "1000",
        "DEFAULT_VALUE" => "",
        "CODE"          => "SRC",
        "ROW_COUNT"     => "1",
        "COL_COUNT"     => "10",
        "MULTIPLE"      => "N",
        "MULTIPLE_CNT"  => "",
        "PROPERTY_TYPE" => "S",
        "LIST_TYPE"     => "L",
        "IBLOCK_ID"     => $IBLOCK_ID
    );
    $ibp = new CIBlockProperty;
    $SrcPropID = $ibp->Add($arFields);
    if (IntVal($SrcPropID)<=0)
        $strWarning .= $ibp->LAST_ERROR."<br>";
}
?>


CIBlock::SetPermission - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::SetPermission

CIBlock::SetPermission(
 int IBLOCK_ID,
 array arPERMISSIONS
);

Assigns the user group permissions to access an information block.

Parameters

Parameter | Description
IBLOCK_ID | Information block ID.
arPERMISSIONS | An array of the format Array("group id"=>"permission", ....), where the permission is: D - deny, R - read, U - modify through the workflow, W - read, X - full access (write + the information block access permissions modification).

See Also

  • CIBlock::GetPermission()
  • CIBlock::Update()

    Example

    <?
CIBlock::SetPermission($IBLOCK_ID, Array("2"=>"R", "3"=>"W"));
?>


CIBlock::ShowPanel - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::ShowPanel

CIBlock::ShowPanel(
 int IBLOCK_ID = 0,
 int ELEMENT_ID = 0,
 int SECTION_ID = 0,
 string TYPE_ID = "news"
);
Adds the control buttons to the site toolbar. The buttons added are used to quickly switch to editing the objects of the Information Blocks module, with respect to the access permissions.

Parameters

Parameter | Description
IBLOCK_ID | Information block ID. If specified (greater than zero), buttons allowing the modification (changing parameters, adding elements and sections) of this information block are added to the toolbar.
ELEMENT_ID | Information block element ID. If specified (greater than zero), buttons allowing the modification (editing and viewing the revision history) of this element are added to the toolbar.
SECTION_ID | Information block section ID. If specified (greater than zero), buttons allowing the section properties modification of this section are added to the toolbar.
TYPE_ID | Type of an information block. If specified, a button allowing to create a new block is added to the toolbar.

Remarks

If the ELEMENT_ID is specified while the IBLOCK_ID is not, the function will automatically determine the latter.

See Also

  • CMain::ShowPanel()

    Example

    <?
$IBLOCK_TYPE = 'catalog';
if (CModule::IncludeModule('iblock')):
    if ($arIBlockElement = GetIBlockElement($_GET['ID'], $IBLOCK_TYPE)):
        CIBlock::ShowPanel($arIBlockElement['IBLOCK_ID'], $_GET['ID'], 0, $IBLOCK_TYPE);
        $APPLICATION->SetTitle($arIBlockElement['NAME']);
        $APPLICATION->AddChainItem($arIBlockElement['IBLOCK_NAME'],
                                   $arIBlockElement['LIST_PAGE_URL']);
        ?>
        <?=$arIBlockElement['NAME']?><br>
        <?=$arIBlockElement['DETAIL_TEXT']?>
        <?
    endif;
endif;
?>


CIBlock::Update - Bitrix Site Manager - Content Management & Portal Solutions

CIBlock::Update

bool
CIBlock::Update(
 int ID,
 array arFields
);

The function updates a number of properties of an information block with a single call.

Parameters

Parameter | Description
ID | Information block ID.
arFields An array of the format Array("field"=>"value", ...). The array contains values of all fields of an information block.

Additionally, the field SITE_ID contains an array of the site identifiers describing sites to which the block is bound.

The field GROUP_ID can be used to set the access permissions for the information block. To do so, set the value of this field to an array of pairs "user_group_id=>access_permission" (see CIBlock::SetPermission()).

Return Values

The function returns true on success, or false otherwise. In case of failure, the property LAST_ERROR contains the error code.

See Also

  • CIBlock::Add
  • Information block fields

    Example

    <?
$arPICTURE = $_FILES["PICTURE"];
$ib = new CIBlock;
$arFields = Array(
  "ACTIVE" => $ACTIVE,
  "NAME" => $NAME,
  "CODE" => $CODE,
  "LIST_PAGE_URL" => $LIST_PAGE_URL,
  "DETAIL_PAGE_URL" => $DETAIL_PAGE_URL,
  "IBLOCK_TYPE_ID" => $type,
  "SITE_ID" => Array("en", "de"),
  "SORT" => $SORT,
  "PICTURE" => $arPICTURE,
  "DESCRIPTION" => $DESCRIPTION,
  "DESCRIPTION_TYPE" => $DESCRIPTION_TYPE,
  "GROUP_ID" => Array("2"=>"D", "3"=>"R")
  );
if ($ID > 0)
  $res = $ib->Update($ID, $arFields);
else
{
  $ID = $ib->Add($arFields);
  $res = ($ID>0);
}
?>


CIBlockElement - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement

CIBlockElement allows various types of operations on information blocks.

Methods

Method | Description
GetList | Returns a list of elements. Filters allowed.
GetByID | Returns an element by its ID.
GetElementGroups | Takes the element ID and returns sections to which the element is bound.
GetProperty | Obtains the element properties.
Add | Adds a new element.
Update | Updates an element.
Delete | Deletes an element from an information block.
SetElementSection | Binds an information block element to sections.
SetPropertyValues | Updates a set of the element properties.
SetPropertyValueCode | Modifies the value of the element property.
UpdateSearch | Indexes an element in the search module.
CounterInc | Increments the element shows counter.


CIBlockElement::Add - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::Add

int
CIBlockElement::Add(
 array arFields,
 bool bWorkFlow = false,
 bool bUpdateSearch = true
);
Adds a new element to an information block.

Parameters

Parameter | Description
arFields | An array of the format Array("field"=>"value", ...) containing values of the element fields of an information block. May also contain the field PROPERTY_VALUES, which is an array of the element properties in the format Array("property code"=>"value"). The property code can be either numeric or mnemonic property code. For more information on properties, see CIBlockElement::SetPropertyValues() and CIBlockElement::SetPropertyValueCode()
bWorkFlow | If true, the new element is added in the workflow mode. If the Workflow module is installed, this operation is journalled in the element log. Optional. By default, elements are added without the workflow features.
bUpdateSearch | Tells to index the new element in the search engine. To speed up processing when adding a large set of elements, set this parameter to false and re-index the search database later. Optional.

Return Values

The method returns the ID of the added element on success. In case of failure returns false and sets the property LAST_ERROR to the error description text.

See Also

  • CIBlockElement::Update
  • CIBlockElement::SetPropertyValues()
  • CIBlockElement::SetPropertyValueCode()

    Example

    <?
$el = new CIBlockElement;

$PROP = array();
$PROP[12] = "White";  // property with code 12 is assigned value "White"
$PROP[3] = 38;        // property with code 3 is assigned value 38

$arLoadProductArray = Array(
  "MODIFIED_BY"    => $USER->GetID(), // element modified by the current user
  "IBLOCK_SECTION" => false,          // put element in the root
  "IBLOCK_ID"      => 18,
  "PROPERTY_VALUES"=> $PROP,
  "NAME"           => "element",
  "ACTIVE"         => "Y",            // active
  "PREVIEW_TEXT"   => "brief text",
  "DETAIL_TEXT"    => "detailed text",
  "DETAIL_PICTURE" => CFile::MakeFileArray($_SERVER["DOCUMENT_ROOT"]."/image.gif")
  );

if($PRODUCT_ID = $el->Add($arLoadProductArray))
  echo "New ID: ".$PRODUCT_ID;
else
  echo "Error: ".$el->LAST_ERROR;
?>


CIBlockElement::CounterInc - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::CounterInc

CIBlockElement::CounterInc(
 int ID
);
Increments the element views counter. The increment operations respect the uniqueness of the element views within a single session.

Parameters

Parameter | Description
ID | Element ID.

Example

<?
if(CModule::IncludeModule("iblock"))
    CIBlockElement::CounterInc($ID);
?>


CIBlockElement::Delete - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::Delete

bool
CIBlockElement::Delete(
 int ID
);

The method deletes an element from the information block.

Parameters

Parameter | Description
ID | Element ID.

Return Values

Returns true on success, or false otherwise.

Example

<?
if(CIBlock::GetPermission($IBLOCK_ID)>='W')
{
    $DB->StartTransaction();
    if(!CIBlockElement::Delete($ELEMENT_ID))
    {
        $strWarning .= 'Error!';
        $DB->Rollback();
    }
    else
        $DB->Commit();
}
?>


CIBlockElement::GetByID - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::GetByID

CIBlockResult
CIBlockElement::GetByID(
 int ID
);

Returns the element parameters.

Parameters

Parameter | Description
ID | Element ID.

Return Values

Return an instance of CIBlockResult with the information block element fields.

Remarks

The method does not check for the published state of the element or whether the element is the history record. To retrieve published elements only, use the method GetList().

See Also

  • CDBResult
  • CIBlockResult
  • Information block element fields
  • CIBlockElement::GetList()

    Example

    <?
$res = CIBlockElement::GetByID($_GET["PID"]);
if ($ar_res = $res->GetNext())
    echo $ar_res['NAME'];
?>


CIBlockElement::GetElementGroups - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::GetElementGroups

CDBResult
CIBlockElement::GetElementGroups(
 int ID
);

Retrieves sections to which the element is bound.

Parameters

Parameter | Description
ID | Element ID.

Return Values

Returns an instance of CDBResult with section fields.

See Also

  • CDBResult
  • Section fields
  • CIBlockElement::SetElementSectio n()

    Example

    <?
$db_old_groups = CIBlockElement::GetElementGroups($ELEMENT_ID);
$ar_new_groups = Array($NEW_GROUP_ID);
while($ar_group = $db_old_groups->Fetch())
     $ar_new_groups[] = $ar_group["ID"];
CIBlockElement::SetElementSection($ELEMENT_ID, $ar_new_groups);
?>


CIBlockElement::GetList - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::GetList

CIBlockResult
CIBlockElement::GetList(
 array arOrder = Array("SORT"=>"ASC"),
 array arFilter = Array(),
 mixed arGroupBy = false,
 mixed arNavStartParams = false,
 array arSelectFields = Array()
);

Returns a list of elements filtered by arFilter.

Parameters

Parameter Description
arOrder Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • id - element ID;
  • sort - sort index;
  • timestamp_x - modification date;
  • name - name;
  • active_from - date an element is active from;
  • active_to - date an element is active till;
  • status - workflow status of an element;
  • code - element mnemonic code;
  • iblock_id - information block ID;
  • modified_by - ID of the last user who modified an element;
  • active - element is active;
  • show_counter - number of the element shows (counted by CounterInc);
  • show_counter_start - time of the first show (counted by CounterInc);
  • shows - average shows (shows / show duration);
  • rand - random order;
  • property_<PROPERTY_CODE> - by value of the property identified by the PROPERTY_CODE (e.g. PROPERTY_123 or PROPERTY_NEWS_SOURCE)
  • catalog_<CATALOG_FIELD>_<PRICE_TYPE> - by the field CATALOG_FIELD (can be PRICE or CURRENCY) of price of the type PRICE_TYPE (e.g. catalog_PRICE_1 or CATALOG_CURRENCY_3).
order is the sort order. Can be asc for ascending sorts or desc for descending.

Default value is Array("sort"=>"asc").
arFilter An array of the format Array("filter field"=>"filter value" [, ...]) where the "filtering field" can be the following:
  • ID - by the identifier;
  • ACTIVE - by the active state (Y|N); passing an empty value ("ACTIVE"=>"") causes the method to return all elements disregarding their state;
  • NAME - by name (wildcards [%_] allowed);
  • CODE - by the mnemonic code (wildcards [%_] allowed);
  • EXTERNAL_ID - by the external ID (wildcards [%_] allowed);
  • PREVIEW_TEXT - by the brief text (wildcards [%_] allowed);
  • PREVIEW_TEXT_TYPE - by the brief text type (html|text);
  • PREVIEW_PICTURE - by the code of a preamble image;
  • DETAIL_TEXT - by the detailed text (wildcards [%_] allowed);
  • DETAIL_TEXT_TYPE - by the detailed text type (html|text);
  • DETAIL_PICTURE - by the code of a large image;
  • CHECK_PERMISSIONS - if "Y", the selection will respect the permissions to access the information blocks. By default, the permissions are not checked.
  • MIN_PERMISSION - minimum allowed access permission. Effective if only CHECK_PERMISSIONS is "Y". Default is "R". For the full list of access permissions, see CIBlock::SetPermission.
  • SEARCHABLE_CONTENT - by the all available searchable content. Includes title, brief and detailed description text (wildcards [%_] allowed);
  • SORT - by the sort weight;
  • TIMESTAMP_X - by modification date (wildcards [%_] allowed);
  • MODIFIED_USER_ID - by the code of a user who modified an element;
  • DATE_CREATE - by creation date;
  • CREATED_BY - by the code of a user who created an element;
  • DATE_ACTIVE_FROM - by date an element is active from;
  • DATE_ACTIVE_TO - by date an element is active till;
  • ACTIVE_DATE - a non-empty value enables sorting by fields DATE_ACTIVE_FROM and DATE_ACTIVE_TO. If the value is empty (""), no filtering is performed;
  • IBLOCK_ID - by the information block ID;
  • IBLOCK_CODE - by the information block mnemonic code (wildcards [%_] allowed);
  • IBLOCK_SITE_ID - by site;
  • IBLOCK_TYPE - by the information block type (wildcards [%_] allowed);
  • IBLOCK_ACTIVE - by the information block active state (Y|N);
  • SECTION_ID - by parent section;
  • INCLUDE_SUBSECTIONS - if the SECTION_ID is specified, selects elements of all child sections of this section;
  • SHOW_COUNTER - by number of shows;
  • SHOW_COUNTER_START - by the time of the first show;
  • WF_COMMENTS - by the workflow comment (wildcards [%_] allowed);
  • WF_STATUS_ID - by the workflow status;
  • SHOW_HISTORY - if set to "Y", result will include history of elements. By default, only the published elements are selected;
  • SHOW_NEW - if the SHOW_HISTORY is not set or not Y and SHOW_NEW is set to Y, unpublished elements are also selected;
  • WF_PARENT_ELEMENT_ID - by the code of the parent element in the workflow (for revision history);
  • WF_NEW - by the unpublished state of an element (Y/N);
  • WF_LOCK_STATUS - by the lock state in the workflow (red|green|yellow);
  • PROPERTY_<property ID> - by property values (wildcards [%_] allowed);
  • CATALOG_<CATALOG_FIELD>_<PRICE_TYPE> - by field CATALOG_FIELD of price of the type PRICE_TYPE (price type code), the CATALOG_FIELD can be PRICE or CURRENCY.

All the filtering fields may have the conditions specified before the name.

The "filter values" are a single value or an array.

The default parameter value is an empty array.
arGroupBy Array of fields for grouping. If any fields are specified, the selection becomes grouped by these fields, and the result contains the field CNT (number of grouped elements). If the parameter contains an empty array, the function returns the number of elements in the field CNT.

You can group by either fields of element or by property values. To do the latter, set one of the grouping fields to PROPERTY_<PROPERTY_CODE> where PROPERTY_CODE is the ID or mnemonic code.

Optional. By default, records are not grouped.
arNavStartParams Parameters used for the implementation of the page navigation. This is achieved by passing an array of pairs "parameter=>value" with the following possible parameters:
  • nTopCount - number of upper elements;
  • bShowAll - directs to retrieve all elements;
  • iNumPage - number of page;
  • nPageSize - desired number of elements per page.
Optional. By default, all available and appropriate elements are selected.
arSelectFields Array containing the element fields to retrieve. Allows to get the property values immediately. To do so, set the name of one of the fields to PROPERTY_<PROPERTY_CODE> where PROPERTY_CODE is the ID or mnemonic code. The result will contain values of the element properties as fields:
  • PROPERTY_<PROPERTY_CODE>_VALUE - property value;
  • PROPERTY_<PROPERTY_CODE>_ID - element value ID;
  • PROPERTY_<PROPERTY_CODE>_ENUM_ID - value ID (for properties of the LIST type).
Obtaining the element price values is also possible if the Commercial Catalog module is installed. Set one of the fields to CATALOG_GROUP_<PROPERTY_CODE> where PROPERTY_CODE is the ID of the price type.

By default, all the element fields are retrieved.

Return Values

Returns an instance of CIBlockResult.

See Also

  • CDBResult
  • Fields of an element

    Example

    <?
$arSelect = Array("ID", "NAME", "DATE_ACTIVE_FROM");
$arFilter = Array("IBLOCK_ID"=>IntVal($yvalue),
                  "ACTIVE_DATE"=>"Y",
                  "ACTIVE"=>"Y");
$res = CIBlockElement::GetList(Array(), $arFilter,
                               false,
                               Array("nPageSize"=>50),
                               $arSelect);
while ($ob = $res->GetNextElement())
{
  $arFields = $ob->GetFields();
  print_r($arFields);
}
?>
    <?
// select active elements from information block $yvalue,
// that has the property with code SRC set
// and the active state date starts from 01.01.2003.
// Group the selected elements by the active state date
$arFilter = Array(
   "IBLOCK_ID"=>IntVal($yvalue),
   ">DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT")),
                             mktime(0,0,0,1,1,2003)),
   "ACTIVE"=>"Y",
   "!PROPERTY_SRC"=>false
   );
$res = CIBlockElement::GetList(Array("SORT"=>"ASC", "PROPERTY_PRIORITY"=>"ASC"),
                               $arFilter, Array("DATE_ACTIVE_FROM"));
while($ar_fields = $res->GetNext())
{
    echo $ar_fields["DATE_ACTIVE_FROM"].": ".$ar_fields["CNT"]."<br>";
}
?>


CIBlockElement::GetProperty - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::GetProperty

CDBResult
CIBlockElement::GetProperty(
 int iblock_id,
 int element_id,
 string by = "sort",
 string order = "asc",
 array arFilter = Array()
);

The function returns values of the element properties.

Parameters

Parameter | Description
iblock_id | Block ID.
element_id | Element ID.
by Used to sort the result. Can be one of the following values:
  • id - by the property ID;
  • name - by the property name;
  • active - by the property active state;
  • sort - by the property sort weight.
Optional; the default value is sort.
order Optional sort order. Can be one of the following values:
  • asc - ascending;
  • desc - descending.
arFilter Optional additional filter in the form of Array("Filtered field"=>"Value", ...). The Filtered field can be the following:
  • ACTIVE - by the active state (Y|N);
  • NAME - by name (wildcards [%_] allowed);
  • ID - by the ID;
  • PROPERTY_TYPE - by the property type;
  • CODE - by mnemonic code;
  • EMPTY - by empty fields.
By default, no additional filtering applied.

Return Values

Returns an instance of CDBResult containing fields of properties and the following fields:
  • PROPERTY_VALUE_ID - the ID of the property value;
  • VALUE - value itself;
  • DESCRIPTION - description of the property value;
  • VALUE_ENUM - property value identifier for the type LIST.

See Also

  • CDBResult
  • Property fields

    Example

    <?
$db_props = CIBlockElement::GetProperty($PRODUCT_IBLOCK_ID,
                                        $PRODUCT_ID, "sort",
                                        "asc",
                                        Array("CODE"=>"FORUM_TOPIC_ID"));
if ($ar_props = $db_props->Fetch())
    $FORUM_TOPIC_ID = IntVal($ar_props["VALUE"]);
else
    $FORUM_TOPIC_ID = false;
?>


CIBlockElement::SetElementSection - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::SetElementSection

CIBlockElement::SetElementSection(
 int ID,
 array arSections
);
The method binds the information block element to a section.

Parameters

Parameter | Description
ID | Element ID.
arSections | Array of the section numeric identifiers to which the element is to be bound.

See Also

  • CIBlockElement:: GetElementGroups()

    Example

    <?
$ID = 18;  // element ID
$arSects = array(1, 5, 7); // array of section ID's
CIBlockElement::SetElementSection($ID, $arSects);
?>


CIBlockElement::SetPropertyValueCode - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::SetPropertyValueCode

bool
CIBlockElement::SetPropertyValueCode(
 int ELEMENT_ID,
 string PROPERTY_CODE,
 string PROPERTY_VALUE
);
The method sets the value of an element property.

Parameters

Parameter | Description
ELEMENT_ID | Element ID.
PROPERTY_CODE | Mnemonic or numeric identifier of a property which is to be changed.
PROPERTY_VALUE | New value; single value or an array depending on the property kind.

See Also

  • CIBlockElement::Update
  • CIBlockElement::SetPropertyValues

    Example

    <?
$arFile = CFile::MakeFileArray($_SERVER["DOCUMENT_ROOT"]."/images/add_basket.gif");
CIBlockElement::SetPropertyValueCode($ELEMENT_ID, "picture", $arFile);
?>


CIBlockElement::SetPropertyValues - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::SetPropertyValues

CIBlockElement::SetPropertyValues(
 int ELEMENT_ID,
 int IBLOCK_ID,
 array PROPERTY_VALUES,
 string PROPERTY_CODE = false
);
The method sets values of one or all properties of an information block element.

Parameters

Parameter | Description
ELEMENT_ID | Element ID whose properties are to be set.
IBLOCK_ID | Information block ID.
PROPERTY_VALUES | Array of property values. If PROPERTY_CODE is other than false, the PROPERTY_VALUES array must contain a single value or an array of values for multiple-value properties. If PROPERTY_CODE is false, the PROPERTY_VALUES array contains pairs "property code"=>"value". In this pair, the property code is the numeric or mnemonic property identifier, and the value is a single value or an array of values for multiple-value properties. Please note that the PROPERTY_VALUES array must contain a full set of properties and values; in case any currently existing property is missing from this array, all its values are removed from the element property set.
PROPERTY_CODE | Code of a property to modify. If this parameter is other than false, a property with this name or code is only modified. This parameter is optional and is set to false by default.

See Also

  • CIBlockElement::Update
  • CIBlockElement::SetPropertyValueCode

    Example

    <?
$ELEMENT_ID = 18;  // element ID
$PROPERTY_CODE = "PROP1";  // property ID
$PROPERTY_VALUE = "blue";  // property value

// Set a new value to this property
$strSql =
  "SELECT BE.IBLOCK_ID ".
  "FROM b_iblock_element BE ".
  "WHERE BE.ID = ".IntVal($ELEMENT_ID);
$dbr = $DB->Query($strSql);
if ($dbr_arr = $dbr->Fetch())
{
  $IBLOCK_ID = $dbr_arr["IBLOCK_ID"];
  CIBlockElement::SetPropertyValues($ELEMENT_ID,
                                    $IBLOCK_ID,
                                    $PROPERTY_VALUE,
                                    $PROPERTY_CODE);
}
?>


CIBlockElement::Update - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::Update

bool
CIBlockElement::Update(
 int ID,
 array arFields,
 bool bWorkFlow = false,
 bool bUpdateSearch = true
);

The method updates parameters (fields) of an element.

Parameters

Parameter | Description
ID | Element ID.
arFields | An array of the format Array("field"=>"value", ...) containing values of the element fields. Additionally, it can contain the field PROPERTY_VALUES which is an array with pairs "property code"=>"value" where the property code is the numeric or mnemonic property identifier, and the value is a single value or an array of values for multiple-value properties. Please note that the PROPERTY_VALUES array must contain a full set of properties and values; in case any currently existing property is missing from this array, all its values are removed from the element property set. The following methods also sets property values: SetPropertyValues, SetPropertyValueCode.
bWorkFlow | If true, the new element is added in the workflow mode. If the Workflow module is installed, this operation is journalled in the element log. Optional. By default, elements are added without the workflow features.
bUpdateSearch | Tells to index the new element in the search engine. To speed up processing when adding a large set of elements, set this parameter to false and re-index the search database later. Optional.

Return Values

Returns true on success or false otherwise. In the latter case, the LAST_ERROR property of the instance contains the error description.

See Also

  • CIBlockElement::Add

    Example

    <?
$el = new CIBlockElement;

$PROP = array();
$PROP[12] = "White";  // assign the value of "White" to the property with the ID of 2
$PROP[3] = 38;        // assign the value of 38 to the property with the ID of 3

$arLoadProductArray = Array(
  "MODIFIED_BY"    => $USER->GetID(), // element is modified by the current user
  "IBLOCK_SECTION" => false,          // element resides in the root
  "IBLOCK_ID"      => 18,
  "PROPERTY_VALUES"=> $PROP,
  "NAME"           => "element",
  "ACTIVE"         => "Y",            // active
  "PREVIEW_TEXT"   => "brief text",
  "DETAIL_TEXT"    => "detailed text",
  "DETAIL_PICTURE" => CFile::MakeFileArray($_SERVER["DOCUMENT_ROOT"]."/image.gif")
  );

$PRODUCT_ID = 2;  // modify element with the ID of 2
$res = $el->Update($PRODUCT_ID, $arLoadProductArray);
?>


CIBlockElement::UpdateSearch - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockElement::UpdateSearch

CIBlockElement::UpdateSearch(
 int ID,
 bool bOverWrite = false
);
Indexes the element in the Search module.

Parameters

Parameter | Description
ID | Element ID
bOverWrite | Tells to re-index the element even if its timestamp is unchanged.


CIBlockProperty - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockProperty

CIBlockProperty allows handling the information block properties.

Methods

Method | Description
GetList | Returns a filtered list of properties.
GetByID | Returns a property by the ID.
Add | Adds a new property.
Update | Updates the property parameters.
Delete | Deletes a property.
GetPropertyEnum | Enumerates the LIST property variants.
UpdateEnum | Updates the array of the property enumeration results.


Add - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockProperty::Add

int
CIBlockProperty::Add(
 array fields
);

The method adds a new property.

Parameters

Parameter | Description
fields | An array in the format Array("field"=>"value"). Contains values of all fields of a property. You can also set the options for properties of the LIST type. To do so, assign an array Array(array("VALUE"=>"value", "DEF"=>"default (Y/N)", "SORT"=>"sort weight"),...) to the field VALUES. See the UpdateEnum function description for more information.

Return Values

The method returns the property ID on success. In case of failure, it returns false and sets the property LAST_ERROR to the error description.

See Also

  • CIBlockProperty::Update
  • Property fields

    Example

    <?
$arFields = Array(
  "NAME" => "Colour",
  "ACTIVE" => "Y",
  "SORT" => "100",
  "CODE" => "color",
  "PROPERTY_TYPE" => "L",
  "IBLOCK_ID" => 11
  );

$arFields["VALUES"][0] = Array(
  "VALUE" => "Red",
  "DEF" => "N",
  "SORT" => "100"
}

$arFields["VALUES"][1] = Array(
  "VALUE" => "Yellow",
  "DEF" => "N",
  "SORT" => "200"
}

$arFields["VALUES"][2] = Array(
  "VALUE" => "Green",
  "DEF" => "Y",
  "SORT" => "300"
}

$ibp = new CIBlockProperty;
$PropID = $ibp->Add($arFields);
?>


CIBlockProperty::GetByID - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockProperty::GetByID

CDBResult
CIBlockProperty::GetByID(
 mixed ID,
 int IBLOCK_ID = false,
 string IBLOCK_CODE = false
);

Returns a property by its ID.

Parameters

Parameter | Description
ID | Numeric or mnemonic property ID.
IBLOCK_ID | Information block ID. Used to locate a property more precisely if a property ID is the mnemonic code shared between properties of several information blocks.
IBLOCK_CODE | Information block mnemonic code. Serves the same purpose as the IBLOCK_ID.

Return Values

Returns an instance of CDBResult.

Remarks

If both IBLOCK_ID and IBLOCK_CODE are passed, the method attempts searches in either of them ("OR").

See Also

  • CDBResult
  • Property fields

    Example

    <?
$res = CIBlockProperty::GetByID("SRC", false, "company_news");
if($ar_res = $res->GetNext())
  echo $ar_res['NAME'];
?>


CIBlockProperty::GetList - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockProperty::GetList

CDBResult
CIBlockProperty::GetList(
 array arOrder = Array(),
 array arFilter = Array()
);

Returns a filtered and sorted list of properties.

Parameters

Parameter Description
arOrder Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • id - property ID;
  • block_id - information block ID;
  • name - name;
  • active - property is active;
  • sort - sort weight;
  • timestamp_x - modification date;
  • searchable - by the fact that the property value should be indexed;
  • filtrable - by the fact that the fields for filtering by this property should be displayed int he administrative section.
order is the sort order. Can be asc for ascending sorts or desc for descending.
arFilter An array of the format Array("filtering field"=>"value" [, ...]) where the "filtering field" can be the following:
  • ACTIVE - by the active state (Y|N);
  • CODE - by the mnemonic code (wildcards [%_] allowed);
  • NAME - by name (wildcards [%_] allowed);
  • EXTERNAL_ID - by the external ID (wildcards [%_] allowed; negation allowed: !EXTERNAL_ID);
  • PROPERTY_TYPE - by the property type;
  • IBLOCK_ID - by the ID of the parent information block;
  • ID - by the identifier;
  • SEARCHABLE - by the fact that the property value should be indexed;
  • FILTRABLE - by the fact that the fields for filtering by this property should be displayed int he administrative section.
The default parameter value is an empty array.

Return Values

Returns an instance of CDBResult

See Also

  • CDBResult
  • Property fields

    Example

    <?
$IBLOCK_ID = 11;
$properties = CIBlockProperty::GetList(Array("sort"=>"asc",
                                             "name"=>"asc"),
                                       Array("ACTIVE"=>"Y",
                                             "IBLOCK_ID"=>$IBLOCK_ID));
while($prop_fields = $properties->GetNext())
{
    echo $prop_fields["ID"]." - ".$prop_fields["NAME"]."<br>";
}
?>


CIBlockProperty::GetPropertyEnum - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockProperty::GetPropertyEnum

CDBResult
CIBlockProperty::GetPropertyEnum(
 mixed PROP_ID,
 array arOrder = Array("SORT"=>"asc"),
 array arFilter = Array()
)

Returns filtered and sorted variants of the LIST property value.

Parameters

Parameter | Description
PROP_ID | Numerical or mnemonic property identifier.
arOrder Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • id - ID;
  • value - value itself;
  • sort - sort weight.
order is the sort order. Can be asc for ascending sorts or desc for descending.
arFilter An array of the format Array("filtering field"=>"value" [, ...]) where the "filtering field" can be the following:
  • VALUE - by the property variant value (wildcards [%_] allowed);
  • IBLOCK_ID - by the ID of the parent information block;
  • ID - by the variant identifier.
The default parameter value is an empty array.

Return Values

Returns an instance of CDBResult, containing records of the property variant fields.

See Also

  • Property variant fields
  • CIBlockPropertyEnum::GetList()

    Example

    <?
$db_enum_list = CIBlockProperty::GetPropertyEnum("IMPORTANT_NEWS",
                                                 Array(),
                                                 Array("IBLOCK_ID"=>$BID,
                                                       "VALUE"=>"Yes"));
if($ar_enum_list = $db_enum_list->GetNext())
{
  $db_important_news = CIBlockElement::GetList(Array(),
                                               Array("IBLOCK_ID"=>$BID,
                                                     "PROPERTY"=>
                                                         array("IMPORTANT_NEWS"=>
                                                               $ar_enum_list["ID"])));
}
?>


CIBlockProperty::Update - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockProperty::Update

bool
CIBlockProperty::Update(
 int ID,
 array arFields
);

The method changes parameters of a property.

Parameters

Parameter | Description
ID | Property ID.
arFields | An array of the format Array("field"=>"value", ...) containing values of the property fields. Additionally, it can contain the field VALUES which is an array Array(array("VALUE"=>"value", "DEF"=>"default (Y/N)", "SORT"=>"sort weight"),...); this allows to set the selection options for the LIST properties. See the UpdateEnum function description for more information.

Return Values

The method returns true on success. In case of failure, it returns false and sets the property LAST_ERROR to the error description.

See Also

  • CIBlockProperty::Add
  • Property fields

    Example

    <?
$arFields = Array(
  "NAME" => "Colour",
  "ACTIVE" => "Y",
  "SORT" => "100",
  "CODE" => "color",
  "PROPERTY_TYPE" => "L",
  "IBLOCK_ID" => 11
  );

$arFields["VALUES"][0] = Array(
  "VALUE" => "Red",
  "DEF" => "N",
  "SORT" => "100"
}

$arFields["VALUES"][1] = Array(
  "VALUE" => "Yellow",
  "DEF" => "N",
  "SORT" => "200"
}

$arFields["VALUES"][2] = Array(
  "VALUE" => "Green",
  "DEF" => "Y",
  "SORT" => "300"
}

$ibp = new CIBlockProperty;
if(!$ibp->Update($ID, $arFields))
    echo $ibp->LAST_ERROR;
?


CIBlockProperty::UpdateEnum - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockProperty::UpdateEnum

CIBlockProperty::UpdateEnum(
 int ID,
 array arVALUES
);

The method sets the LIST property options.

Parameters

Parameter | Description
ID | Property ID.
arVALUES | An array of all values in the format Array("existing value ID"=>"array of values", ..., "new values", ...). The array of values is the Array(array("VALUE"=>"value", "DEF"=>"default (Y/N)", "SORT"=>"sort weight"),...).

Remarks

Array arVALUES should contain a full list of values. All values existing in the property but missing from the array arVALUES will be deleted.

See Also

  • Possible values for properties of the type LIST
  • Class CIBlockPropetyEnum
  • CIBlockPropetyEnum::Update
  • CIBlockPropetyEnum::Add

    • Example

    <?
$cnt = 0;
$ar_all_values = Array();
$db_enum_list = CIBlockProperty::GetPropertyEnum($PROP_ID,
                                                 Array('SORT'=>'ASC'));
while($ar_enum = $db_enum_list->Fetch())
{
    $cnt++;
    $ar_all_values[$ar_enum['ID']] = Array('SORT'=>$cnt,
                                           'VALUE'=>$ar_enum['VALUE']);
}

CIBlockPropertyEnum::UpdateEnum($PROP_ID, $ar_all_values);
?>


Delete - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockProperty::Delete

bool
CIBlockProperty::Delete(
 int ID
);

The method deletes a property.

Parameters

Parameter | Description
ID | Property ID.

Return Values

Returns true on success or false otherwise.


CIBlockPropertyEnum - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockPropertyEnum

CIBlockPropertyEnum is used for handling values of properties of the type LIST.

Methods

Method | Description
GetList | Returns a filtered list of variants.
Add | Adds a new variant.
Update | Updates a variant.
Delete | Deletes the property variant.


CIBlockPropertyEnum::Add - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockPropertyEnum::Add

int
CIBlockPropertyEnum::Add(
 array fields
);

The method adds a new option of the LIST property value.

Parameters

Parameter | Description
fields | An array of the format Array("field"=>"value", ...). Contains values of all fields of the property value option.

Return Values

Returns the ID of the added option, or false otherwise.

See Also

  • CIBlockPropertyEnum::Update
  • Possible values for properties of the type LIST

    Example

    <?
$ibpenum = new CIBlockPropertyEnum;
if ($PropID = $ibpenum->Add(Array('PROPERTY_ID'=>$PROPERTY_ID,
                                  'VALUE'=>'New Enum 1')))
    echo 'New ID:'.$PropID;
?>


CIBlockPropertyEnum::Delete - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockPropertyEnum::Delete

bool
CIBlockPropertyEnum::Delete(
 int ID
);

The method deletes an option of the LIST property value.

Parameters

Parameter | Description
ID | Option ID.

Return Values

Returns true on success, or false otherwise.


CIBlockPropertyEnum::GetList - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockPropertyEnum::GetList

CDBResult
CIBlockPropertyEnum::GetList(
 array arOrder = Array("SORT"=>"ASC", "VALUE"=>"ASC"),
 array arFilter = Array()
);

Returns a filtered and sorted list of the LIST property value options.

Parameters

Parameter Description
arOrder Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • id - by the option ID;
  • value - by option value;
  • sort - by sort weight;
  • external_id - by external ID of an option;
  • def - by the attribute default;
  • property_id - by the property ID;
  • property_sort - by the property sort weight;
  • property_code - by the mnemonic property code.
order is the sort order. Can be asc for ascending sorts or desc for descending.
arFilter Optional additional filter by fields in the form of Array("Filtered field"=>"Value", ...). The Filtered field can be the following:
  • VALUE - by value (wildcards [%_] allowed);
  • ID - by the option value ID;
  • SORT - by sort weight;
  • DEF - by the attribute default (Y/N);
  • EXTERNAL_ID - by external ID (wildcards [%_] allowed);
  • CODE - by mnemonic identifier (wildcards [%_] allowed);
  • PROPERTY_ID - by the property ID or mnemonic code;
  • IBLOCK_ID - by the parent information block ID.
The default parameter value is an empty array.

Return Values

Returns an instance of CDBResult

See Also

  • CDBResult
  • Possible values for properties of the type LIST

    Example

    <?
$property_enums = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC",
                                                     "SORT"=>"ASC"),
                                               Array("IBLOCK_ID"=>$IBLOCK_ID,
                                                     "CODE"=>"COLORS"));
while($enum_fields = $property_enums->GetNext())
{
    echo $enum_fields["ID"]." - ".$enum_fields["VALUE"]."<br>";
}
?>


CIBlockPropertyEnum::Update - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockPropertyEnum::Update

bool
CIBlockPropertyEnum::Update(
 int ID,
 array arFields
);

The method modifies the value option.

Parameters

Parameter | Description
ID | Option ID.
arFields | An array of the format Array("field"=>"value", ...). Contains values of all fields of a property value option.

Return Values

Returns true on success, or false otherwise.

See Also

  • CIBlockPropertyEnum::Add
  • Possible values for properties of the type LIST

    Example

    <?
$ibpenum = new CIBlockPropertyEnum;
$ibpenum->Update($PROPERTY_ENUM_ID, Array('VALUE'=>'Enum 1'));
?>


CIBlockResult - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockResult

CIBlockResult is the helper class for handling the results of operations. The class is inherited from CDBResult and contains all its properties and methods.

The following methods return an instance of CIBlockResult: CIBlockElement::GetList, CIBlockElement::GetByID, GetIBlockElementList and GetIBlockElementListEx. This class allows for flexible and effective handling of the information block elements.

Methods

Method | Description
GetNext | Returns an array of element fields, replacing variables like #IBLOCK_ID# in fields LIST_PAGE_URL and DETAIL_PAGE_URL.
GetNextElement | Returns an instance of _CIBElement from the selection.


CIBlockResult::GetNext - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockResult::GetNextElement

mixed
CIBlockResult::GetNext();

Returns an array of field values converted to an HTML safe format. Variables #IBLOCK_ID# etc. are replaced with their corresponding values in fields LIST_PAGE_URL and DETAIL_PAGE_URL, so these fields will contain valid links.

Return Values

The method returns an array with the information block element fields in the format of Array("field"=>"value" [, ...]) and moves the pointer to the next record.

The method returns false when it reaches the last record or if the result contains no records.

See Also

  • CDBResult
  • CIBlockResult::GetNextElement
  • CIBlockElement::GetList
  • Fields of information block element

  • Example

    <?
$res = CIBlockElement::GetByID($_GET["PID"]);
if ($ar_res = $res->GetNext())
    echo '<a href="'.$ar_res['DETAIL_PAGE_URL'].'">'.$ar_res['NAME'].'</a>';
?>


CIBlockResult::GetNextElement - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockResult::GetNextElement

_CIBElement
CIBlockResult::GetNextElement();

The method returns an instance of _CIBElement from the selection.

Return Values

The method returns an instance of _CIBElement and moves the pointer to the next record.

The method returns false when it reaches the last record or if the result contains no records.

See Also

  • _CIBElement
  • CIBlockResult::GetNext
  • CIBlockElement::GetList

    Example

    <?
$res = CIBlockElement::GetByID($_GET["PID"]);
if ($obRes = $res->GetNextElement())
{
    $ar_res = $obRes->GetFields();
    echo $ar_res['NAME'];
}
?>


CIBlockSection - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection

CIBlockSection is the class for handling the information block sections.

Methods

Method | Description
GetList | Returns a filtered list of sections.
GetByID | Returns a section by its ID.
Add | Adds a new section to an information block.
Update | Updates a section.
Delete | Deletes a section from an information block.
GetCount | Returns the number of sections.
GetSectionElementsCount | Returns the number of elements in the section.
GetTreeList | Returns a list of sections sorted in the order of the fully expanded tree.
GetNavChain | Returns the path from the root to the section.
Resort | Recalculates the left and right margins.


CIBlockSection::Add - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::Add

int
Add(
 array arFields,
 bool bResort = true,
 bool bUpdateSearch = true
);

The method adds a new section to an information block.

Parameters

Parameter | Description
arFields | An array of the format Array("field"=>"value", ...), containing values of the information block section fields.
bResort | If set to true, tells to recalculate the left and right margins (fields LEFT_MARGIN and RIGHT_MARGIN). Set this parameter to false if you perform a series of calls. In the latter case, set this parameter to false, perform the required calls and then invoke ReSort.
bUpdateSearch | Specifies the section should be indexed for searching right after the save.

Return Values

The method returns the ID of the new section on success. In case of failure, it returns false and sets the property LAST_ERROR to the error description.

See Also

  • CIBlockSection::Update

    Example

    <?
$bs = new CIBlockSection;
$arFields = Array(
  "ACTIVE" => $ACTIVE,
  "IBLOCK_SECTION_ID" => $IBLOCK_SECTION_ID,
  "IBLOCK_ID" => $IBLOCK_ID,
  "NAME" => $NAME,
  "SORT" => $SORT,
  "PICTURE" => $_FILES["PICTURE"],
  "DESCRIPTION" => $DESCRIPTION,
  "DESCRIPTION_TYPE" => $DESCRIPTION_TYPE
  );

if($ID > 0)
{
  $res = $bs->Update($ID, $arFields);
}
else
{
  $ID = $bs->Add($arFields);
  $res = ($ID>0);
}

if(!$res)
  echo $bs->LAST_ERROR;
?>


CIBlockSection::GetCount - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::GetCount

int
CIBlockSection::GetCount(
 array arFilter = Array()
);

Returns the number of sections that satisfy the filter conditions.

Parameters

Parameter Description
arFilter An array of the format Array("filter field"=>"value" [, ...])
The filter field can be the following:
  • ACTIVE - by the active state (Y|N);
  • GLOBAL_ACTIVE - by the active state with respect to those of parent sections (Y|N);
  • NAME - by name (wildcards [%_] allowed);
  • CODE - by the mnemonic code (wildcards [%_] allowed);
  • EXTERNAL_ID - by the external ID (wildcards [%_] allowed);
  • SECTION_ID - by the parent section ID;
  • DEPTH_LEVEL - by the nesting level;
  • LEFT_BORDER, RIGHT_BORDER - by left and right margins (fields LEFT_MARGIN and RIGHT_MARGIN);
  • ID - by the section ID;
  • IBLOCK_ID - by the ID of the parent information block;
  • IBLOCK_ACTIVE - by the parent information block active state;
  • IBLOCK_NAME - by the information block name (wildcards [%_] allowed);
  • IBLOCK_TYPE - by the information block type;
  • IBLOCK_CODE - by the information block mnemonic code (wildcards [%_] allowed);
  • IBLOCK_EXTERNAL_ID - by the information block external code (wildcards [%_] allowed);
All the filter fields may have the following conditions before the name:
  • "!" - not equal;
  • "<" - less than;
  • "<=" - less than or equal;
  • ">" - more than;
  • ">=" - more than or equal.
The "filter values" are a single value or an array.

The default parameter value is an empty array.

Return Values

Number of sections.

See Also

  • CIBlockSection::GetList

    Example

    <?
    $arFilter = Array(
        "IBLOCK_ID"=>$IBLOCK_ID,
        "SECTION_ID"=>$f_ID
        );

    echo CIBlockSection::GetCount($arFilter);
?>


CIBLockSection::GetList - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::GetList

CDBResult
CIBlockSection::GetList(
 array arOrder = Array("SORT"=>"ASC"),
 array arFilter = Array(),
 bool bIncCnt = false
);

Returns a filtered and sorted list of sections.

Parameters

Parameter | Description
arOrder Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • id - section ID;
  • section - parent section ID;
  • name - section name;
  • active - active state;
  • left_margin - left margin;
  • depth_level - section nesting level;
  • sort - sort weight;
  • element_cnt - number of elements in section; effective if only bIncCnt is true;
  • timestamp_x - modification date.
order is the sort order. Can be asc for ascending sorts or desc for descending.
arFilter An array of the format Array("filter field"=>"value" [, ...])
The filter field can be the following:
  • ACTIVE - by the active state (Y|N);
  • GLOBAL_ACTIVE - by the active state with respect to those of parent sections (Y|N);
  • NAME - by name (wildcards [%_] allowed);
  • CODE - by the mnemonic code (wildcards [%_] allowed);
  • EXTERNAL_ID - by the external ID (wildcards [%_] allowed);
  • SECTION_ID - by the parent section ID;
  • DEPTH_LEVEL - by the nesting level;
  • LEFT_BORDER, RIGHT_BORDER - by left and right margins (fields LEFT_MARGIN and RIGHT_MARGIN; see Remarks);
  • ID - by the section ID;
  • IBLOCK_ID - by the ID of the parent information block;
  • IBLOCK_ACTIVE - by the parent information block active state;
  • IBLOCK_NAME - by the information block name (wildcards [%_] allowed);
  • IBLOCK_TYPE - by the information block type;
  • IBLOCK_CODE - by the information block mnemonic code (wildcards [%_] allowed);
  • IBLOCK_EXTERNAL_ID - by the information block external code (wildcards [%_] allowed);
  • PROPERTY - by values of properties of the child elements; PROPERTY is an array of kind Array("property ID"=>"value", ...).
All the filter fields except SECTION_ID and ACTIVE_DATE may have the conditions specified before the name.

The "filter values" are a single value or an array.

The default parameter value is an empty array.
bIncCnt | Specifies that the number of sections of the information block is to be returned in the field ELEMENT_CNT. Optional. The default value is false.

Return Values

Returns an instance of CDBResult

Remarks

The sorting field left_margin (the so-called "through sorting") is calculated based on the field sort, nesting level and the parent level sort weight. The difference between sort and left_margin is that the sort is defined by the user to sort sections within a single parent section, while the left_margin is calculated automatically and is used for sorting within the whole information block.

See Also

  • CDBResult
  • Section fields

    Example

    <?
$arIBTYPE = CIBlockType::GetByIDLang($type, LANGUAGE_ID);
if($arIBTYPE!==false)
{
    // select only active sections from the information block $IBLOCK_ID,
    // having elements with properties "SRC" starting with "https://"
    $arFilter = Array('IBLOCK_ID'=>$IBLOCK_ID,
                      'GLOBAL_ACTIVE'=>'Y',
                      'PROPERTY'=>Array('SRC'=>'https://%'));
    $db_list = CIBlockSection::GetList(Array($by=>$order), $arFilter, true);
    $db_list->NavStart(20);
    echo $db_list->NavPrint($arIBTYPE["SECTION_NAME"]);
    while($ar_result = $db_list->GetNext())
    {
        echo $ar_result['ID'].' '.$ar_result['NAME'].': '.$ar_result['ELEMENT_CNT'].'<br>';
    }
    echo $db_list->NavPrint($arIBTYPE["SECTION_NAME"]);
}
?>


CIBlockSection::GetSectionElementsCount - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::GetSectionElementsCount

Obsolete

int
CIBlockSection::GetSectionElementsCount(
 int ID,
 array arFilter = Array()
);

Returns the number of elements in the section, with respect to the filter settings.

Parameters

Parameter | Description
ID | Section ID.
arFilter An array of the format Array("filter field"=>"value", ...).
The filter field can be the following:
  • ACTIVE - active elements (Y|N);
  • CNT_ALL - count the unpublished elements (only if the Workflow module is installed);
  • PROPERTY - array for filtering by values: Array("property ID"=>"value", ...).

Remarks

This method is obsolete. Use CIBlockElement::GetList instead with the grouping enabled.

See Also

  • CIBlockElement::GetList


CIBlockSection::GetTreeList - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::GetTreeList

CDBResult
CIBlockSection::GetTreeList(
 array arFilter=Array()
);

The function returns a list of sections sorted in the order of the fully expanded tree. This method is essentially a wrapper for CIBlockSection::GetList with the sorting parameter being set:

CIBlockSection::GetList(Array("left_margin"=>"asc"), $arFilter);

See Also

  • CIBlockSection::GetList


CIBlockSection::Resort - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::Resort

CIBlockSection::Resort(
 int IBLOCK_ID
);

The method recalculates the left and right margins of all sections of an information block IBLOCK_ID.

Parameters

Parameter | Description
IBLOCK_ID | Information block ID.

Remarks

You should remember to invoke this function after a series of calls to CIBlockSection::Add or CIBlockSection::Update if you set their parameter bReSort to false to increase the processing speed.

See Also

  • CIBlockSection::Add()
  • CIBlockSection::Update()

    Example

    <?
$obSect = new CIBlockSection;
for($i=0; $i < 100; $i++)
{
    $obSect->Add(Array('NAME'=>'Section #'.$i,
                       'IBLOCK_ID'=>$IBLOCK_ID),
                 false);
}

CIBlockSection::ReSort($IBLOCK_ID);
?>


CIBlockSection::Update - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::Update

bool
CIBlockSection::Update(
 int ID,
 array arFields,
 bool bResort = true
 bool bUpdateSearch = true
);

The method modifies parameters of a section.

Parameters

Parameter | Description
ID | Section ID.
arFields | An array of the format Array("field"=>"value", ...), containing values of the information block section fields.
bResort | If set to true, tells to recalculate the left and right margins (fields LEFT_MARGIN and RIGHT_MARGIN). Set this parameter to false if you do not modify fields affecting the margins, or if you perform a series of calls. In the latter case, set this parameter to false, perform the required calls and then invoke ReSort.
bUpdateSearch | Specifies the section should be indexed for searching right after the save.

Return Values

The method returns true on success. In case of failure, it returns false and sets the property LAST_ERROR to the error description.

See Also

  • CIBlockSection::Add

    Example

    <?
$bs = new CIBlockSection;

$arPICTURE = $_FILES["PICTURE"];
$arPICTURE["MODULE_ID"] = "iblock";

$arFields = Array(
  "ACTIVE" => $ACTIVE,
  "IBLOCK_SECTION_ID" => $IBLOCK_SECTION_ID,
  "IBLOCK_ID" => $IBLOCK_ID,
  "NAME" => $NAME,
  "SORT" => $SORT,
  "PICTURE" => $arPICTURE,
  "DESCRIPTION" => $DESCRIPTION,
  "DESCRIPTION_TYPE" => $DESCRIPTION_TYPE
  );

if($ID > 0)
{
  $res = $bs->Update($ID, $arFields);
}
else
{
  $ID = $bs->Add($arFields);
  $res = ($ID>0);
}
?>


Delete - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::Delete

bool
CIBlockSection::Delete(
 int ID
);

The method deletes a section identified by the ID. All child sections and elements are deleted if they are bound to only this section .

Parameters

Parameter | Description
ID | Section ID.

Return Values

Returns true on success, or false otherwise.

Example

<?
if (CIBlock::GetPermission($IBLOCK_ID)>='W')
{
    $DB->StartTransaction();
    if (!CIBlockSection::Delete($SECTION_ID))
    {
        $strWarning .= 'Error.';
        $DB->Rollback();
    }
    else
        $DB->Commit();
}
?>


GetByID - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::GetByID

CDBResult
GetByID(
 int ID
);

Returns parameters of a section identified by the ID.

Parameters

Parameter | Description
ID | Section ID.

Return Values

Returns an instance of CDBResult.

See Also

  • CDBResult
  • Section fields

    Example

    <?
$res = CIBlockSection::GetByID($_GET["GID"]);
if ($ar_res = $res->GetNext())
    echo $ar_res['NAME'];
?>


GetNavChain - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockSection::GetNavChain

CDBResult
CIBlockSection::GetNavChain(
 int IBLOCK_ID,
 int SECTION_ID
);
Returns the path from the root to the section identified by the SECTION_ID.

Parameters

Parameter | Description
IBLOCK_ID | Information block ID. Used to check that the section SECTION_ID is the child of this information block. If null, no check is performed.
SECTION_ID | The ID of the section path to which is required.

Return Values

Returns an instance of CDBResult with fields of the information block section.

See Also

  • CDBResult
  • Section fields

    Example

    <?
$nav = CIBlockSection::GetNavChain(false, $SECTION_ID);
while($nav->ExtractFields("nav_")):
?> &raquo;
  <?if($SECTION_ID == $nav_ID):?>
    <?echo $nav_NAME?>
  <?else:?>
    <a class="navchain"
     href="<?=$APPLICATION->GetCurPage()?>?IBLOCK_ID=<?=$IBLOCK_ID?>&SECTION_ID=<?=$nav_ID?>#tb"><?echo $nav_NAME?></a>
  <?endif?>
<?endwhile;?>
    © 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Add - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockType::Add

bool
CIBlockType::Add(
 array arFields
);

The method creates a new type of information blocks. This method cannot be called as a static function.

Parameters

Parameter | Description
arFields | Array of pairs field=>value. Contains values of the information block type fields. The array entry arFields["LANG"] should contain an array of the language-dependent parameters of information block type.

Return Values

The method returns true on success. In case of failure, it returns false and sets the property LAST_ERROR to the error description.

See Also

  • CIBlockType::Update
  • Information block type fields

    Example

    <?
$arFields = Array(
    'ID'=>'catalog',
    'SECTIONS'=>'Y',
    'IN_RSS'=>'N',
    'SORT'=>100,
    'LANG'=>Array(
        'en'=>Array(
        'NAME'=>'Catalog',
        'SECTION_NAME'=>'Sections',
        'ELEMENT_NAME'=>'Products')
        )
    );

$obBlocktype = new CIBlockType;
$DB->StartTransaction();
$res = $obBlocktype->Add($arFields);
if (!$res)
{
   $DB->Rollback();
   echo 'Error: '.$obBlocktype->LAST_ERROR.'<br>';
}
else
{
   $DB->Commit();
}
?>


CIBlockType - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockType

The CIBlockType class provides the programming interface to the information block types.

Methods

Method | Description
GetList | Returns a filtered list of types.
GetByID | Returns a type by the ID.
GetByIDLang | Returns the language settings of the information block type for the specified language.
Add | Adds a new type.
Update | Updates a set of the type parameters.
Delete | Delete the block type.


CIBlockType::Update - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockType::Update

bool
CIBlockType::Update(
 string ID,
 array arFields
);

The method modifies the information block type parameters.

Parameters

Parameter | Description
ID | Information block type ID.
arFields | Array of pairs field=>value. Contains values of the information block type fields. The array entry arFields["LANG"] should contain an array of the language-dependent parameters of information block type.

Return Values

The method returns true on success. In case of failure, it returns false and sets the property LAST_ERROR to the error description.

See Also

  • CIBlockType::Add
  • Information block type fields

    Example

    <?
$arFields = Array(
    'SECTIONS'=>'Y',
    'IN_RSS'=>'N',
    'SORT'=>100,
    'LANG'=>Array(
        'en'=>Array(
            'NAME'=>'Catalog',
            'SECTION_NAME'=>'Sections',
            'ELEMENT_NAME'=>'Products'
            )
        )
    );

$obBlocktype = new CIBlockType;
$DB->StartTransaction();
$res = $obBlocktype->Update('catalog', $arFields);
if(!$res)
{
   $DB->Rollback();
   echo 'Error: '.$obBlocktype->LAST_ERROR.'<br>';
}
else
   $DB->Commit();
?>


Delete - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockType::Delete

bool
CIBlockType::Delete(
 string ID
);

Deletes the information block type.

Parameters

Parameter | Description
ID | Information block type ID.

Return Values

Returns true on success, of false otherwise.

Example

<?
$DB->StartTransaction();
if (!CIBlockType::Delete('catalog'))
{
    $DB->Rollback();
    echo 'Delete error!';
}
$DB->Commit();
?>


GetByID - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockType::GetByID

CDBResult
CIBlockType::GetByID(
 string ID
);

Returns the information block type by its ID.

Parameters

Parameter | Description
ID | Information block type ID.

Return Values

Returns an instance of CDBResult.

See Also

  • CDBResult
  • Information block type fields


GetByID - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockType::GetByIDLang

mixed
CIBlockType::GetByIDLang(
 string ID,
 string LANGUAGE_ID,
 bool bFindAny = true
);

The method returns the language settings of the information block type by its ID for the specified language. If the requested language settings cannot be found and the parameter bFindAny is true, the method returns settings of the default language.

Parameters

Parameter | Description
ID | Information block type ID.

Return Values

Returns an array of the information block type fields on success, or false otherwise.

See Also

  • Information block type fields

    Example

    <?
$db_iblock_type = CIBlockType::GetList();
while($ar_iblock_type = $db_iblock_type->Fetch())
{
   if ($arIBType = CIBlockType::GetByIDLang($ar_iblock_type["ID"], LANG))
   {
      echo htmlspecialcharsex($arIBType["NAME"])."<br>";
   }
}
?>


GetList - Bitrix Site Manager - Content Management & Portal Solutions

CIBlockType::GetList

CDBResult
CIBlockType::GetList(
 array arOrder = Array("SORT"=>"ASC"),
 array arFilter = Array()
);

Returns a sorted and filtered list of information block types.

Parameters

Parameter Description
arOrder Array of the fields for sorting. Contains pairs "sorting field"=>"sorting direction". The sorting field can be one of the following:
  • id - type ID;
  • sort - sort weight.
arFilter An array of the format Array("filtering field"=>"value" [, ...]). The filtering field can be the following:
  • ID - by the type ID.
Optional. By default, fields are not sorted.

Return Values

Returns an instance of CDBResult

See Also

  • CDBResult
  • Information block type fields

    Example

    <?
$db_iblock_type = CIBlockType::GetList();
while($ar_iblock_type = $db_iblock_type->Fetch())
{
   if($arIBType = CIBlockType::GetByIDLang($ar_iblock_type["ID"], LANG))
   {
      echo htmlspecialcharsex($arIBType["NAME"])."<br>";
   }
}
?>


_CIBElement - Bitrix Site Manager - Content Management & Portal Solutions

_CIBElement

_CIBElement is the helper class for handling objects returned by calls to CIBlockResult::GetNextElement. This class is recommended for obtaining the element parameters since the methods of this class provide the extensive functionality for the information block elements handling.

Methods

Method | Description
GetFields | Returns the fields of an element.
GetProperties | Returns values of a set of the element properties.
GetProperty | Returns the value of an element property.
GetGroups | Returns a list of sections to which the element is bound.


_CIBElement::GetFields - Bitrix Site Manager - Content Management & Portal Solutions

_CIBElement::GetFields

array
_CIBElement::GetFields();

Returns an array of fields converted to the HTML-safe format. Variables #IBLOCK_ID# etc. are replaced with their corresponding values in fields LIST_PAGE_URL and DETAIL_PAGE_URL, so these fields will contain valid links.

Return Values

Returns an array with the with the information block element fields: Array("field"=>"value" [, ...]).

See Also

  • Information block element fields
  • CIBlockResult::GetNext
  • CIBlockElement::GetList

    Example

    <?
$res = CIBlockElement::GetByID($_GET["PID"]);
if($obRes = $res->GetNextElement())
{
  $ar_res = $obRes->GetFields();
  echo '<a href="'.$ar_res['DETAIL_PAGE_URL'].'">'.$ar_res['NAME'].'</a>';
}
?>


_CIBElement::GetGroups - Bitrix Site Manager - Content Management & Portal Solutions

_CIBElement::GetGroups

CDBResult
_CIBElement::GetGroups();

Returns the information block sections to which this element is bound.

Return Values

Returns an instance of CDBResult with the section fields.

See Also

  • Section fields
  • CDBResult
  • CIBlockElement::GetElementGroups

    Example

    <?
$res = CIBlockElement::GetByID($_GET["PID"]);
if($obRes = $res->GetNextElement())
{
  $ar_res = $obRes->GetGroups();
  print_r($ar_res);
}
?>


_CIBElement::GetProperties - Bitrix Site Manager - Content Management & Portal Solutions

_CIBElement::GetProperties

array
_CIBElement::GetProperties(
   arOrder = Array("sort" => "asc"),
   arFilter = Array()
);

The method returns property values of this information block element.

Parameters

Parameter Description
arOrder Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • id - property ID;
  • name - property name;
  • active - property active state;
  • sort - property sort weight.
order is the sort order. Can be asc for ascending sorts or desc for descending.
arFilter Optional additional filter in the form of Array("Filtered field"=>"Value", ...). The Filtered field can be the following:
  • NAME - by the property name;
  • ID - by the property ID;
  • ACTIVE - by the property active state (Y|N). By default, only the active properties are returned; set this field empty to obtain all properties;
  • PROPERTY_TYPE - by the property type;
  • CODE - by the property mnemonic code;
  • EMPTY - by empty fields (Y|N). By default, all properties are returned, both with empty and meaningful properties.
By default, no additional filtering applied.

Return Values

The method returns the property values array with the key in the form of either symbolic code or the numeric ID and the value of an array containing the property fields and the additional keys and values:

  • "VALUE" => "property value or an array for a multiple property";
  • "VALUE_ENUM_ID" => "option ID for the LIST properties (array or a single value)";
  • "DESCRIPTION" => "property value description (array or a single value)";
  • "PROPERTY_VALUE_ID" => "property value ID (array or a single value)"

See Also

  • _CIBElement::GetProperties
  • CIBlockElement::GetProperty

    Example

    <?
include($_SERVER['DOCUMENT_ROOT'].'/bitrix/header.php');
if(CModule::IncludeModule('iblock'))
{
    $dbEl = CIBlockElement::GetList(Array(),
                                         Array("IBLOCK_TYPE"=>"catalog",
                                               "IBLOCK_ID"=>11));
    if($obEl = $dbEl->GetNextElement())
    {
        $props = $obEl->GetProperties();
        echo "<pre>";
        print_r($props);
        echo "</pre>";
    }
}
?>
<?include($_SERVER['DOCUMENT_ROOT'].'/bitrix/footer.php');?>

    Sample output:

    Array
(
    [27] => Array
        (
            [ID] => 27
            [TIMESTAMP_X] => 20041222191551
            [IBLOCK_ID] => 11
            [NAME] => Battery
            [ACTIVE] => Y
            [SORT] => 500
            [CODE] =>
            [DEFAULT_VALUE] =>
            [PROPERTY_TYPE] => L
            [ROW_COUNT] => 1
            [COL_COUNT] => 30
            [LIST_TYPE] => L
            [MULTIPLE] => Y
            [XML_ID] =>
            [FILE_TYPE] =>
            [MULTIPLE_CNT] => 5
            [TMP_ID] =>
            [WITH_DESCRIPTION] =>
            [LINK_IBLOCK_ID] => 0
            [VALUE_TYPE] => text
            [VALUE_ENUM] => Li-Mon
            [VALUE] => Array
                (
                    [0] => Li-Test
                    [1] => Li-NEW
                    [2] => Li-Mon
                )

            [~VALUE] => Array
                (
                    [0] => Li-Test
                    [1] => Li-NEW
                    [2] => Li-Mon
                )

            [DESCRIPTION] => Array
                (
                    [0] =>
                    [1] =>
                    [2] =>
                )

            [~DESCRIPTION] => Array
                (
                    [0] =>
                    [1] =>
                    [2] =>
                )

            [PROPERTY_VALUE_ID] => Array
                (
                    [0] => 53860
                    [1] => 53861
                    [2] => 53862
                )

            [VALUE_ENUM_ID] => Array
                (
                    [0] => 18
                    [1] => 19
                    [2] => 20
                )

            [~NAME] => Battery
            [~DEFAULT_VALUE] =>
        )

    [28] => Array
        (
            [ID] => 28
            [TIMESTAMP_X] => 20041222191551
            [IBLOCK_ID] => 11
            [NAME] => Screen
            [ACTIVE] => Y
            [SORT] => 500
            [CODE] =>
            [DEFAULT_VALUE] =>
            [PROPERTY_TYPE] => S
            [ROW_COUNT] => 1
            [COL_COUNT] => 30
            [LIST_TYPE] => L
            [MULTIPLE] => Y
            [XML_ID] =>
            [FILE_TYPE] =>
            [MULTIPLE_CNT] => 5
            [TMP_ID] =>
            [WITH_DESCRIPTION] =>
            [LINK_IBLOCK_ID] => 0
            [VALUE_TYPE] =>
            [VALUE_ENUM] =>
            [VALUE] => Color
            [~VALUE] => Color
            [DESCRIPTION] =>
            [~DESCRIPTION] =>
            [PROPERTY_VALUE_ID] => 32862
            [~NAME] => Screen
            [~DEFAULT_VALUE] =>
        )

    [29] => Array
        (
            [ID] => 29
            [TIMESTAMP_X] => 20041222191551
            [IBLOCK_ID] => 11
            [NAME] => PropertyX
            [ACTIVE] => Y
            [SORT] => 500
            [CODE] =>
            [DEFAULT_VALUE] =>
            [PROPERTY_TYPE] => N
            [ROW_COUNT] => 1
            [COL_COUNT] => 30
            [LIST_TYPE] => L
            [MULTIPLE] => Y
            [XML_ID] =>
            [FILE_TYPE] =>
            [MULTIPLE_CNT] => 5
            [TMP_ID] =>
            [WITH_DESCRIPTION] =>
            [LINK_IBLOCK_ID] => 0
            [VALUE_TYPE] =>
            [VALUE_ENUM] =>
            [VALUE] =>
            [~VALUE] =>
            [DESCRIPTION] =>
            [~DESCRIPTION] =>
            [PROPERTY_VALUE_ID] =>
            [~NAME] => PropertyX
            [~DEFAULT_VALUE] =>
        )
    [FORUM_TOPIC_ID] => Array
        (
            [ID] => 383
            [TIMESTAMP_X] => 20041223132810
            [IBLOCK_ID] => 11
            [NAME] => FORUM_TOPIC_ID
            [ACTIVE] => Y
            [SORT] => 500
            [CODE] => FORUM_TOPIC_ID
            [DEFAULT_VALUE] =>
            [PROPERTY_TYPE] => N
            [ROW_COUNT] => 1
            [COL_COUNT] => 30
            [LIST_TYPE] => L
            [MULTIPLE] => N
            [XML_ID] =>
            [FILE_TYPE] =>
            [MULTIPLE_CNT] => 5
            [TMP_ID] =>
            [WITH_DESCRIPTION] =>
            [LINK_IBLOCK_ID] => 0
            [VALUE_TYPE] =>
            [VALUE_ENUM] =>
            [VALUE] =>
            [~VALUE] =>
            [DESCRIPTION] =>
            [~DESCRIPTION] =>
            [PROPERTY_VALUE_ID] =>
            [~NAME] => FORUM_TOPIC_ID
            [~DEFAULT_VALUE] =>
        )
    [386] => Array
        (
            [ID] => 386
            [TIMESTAMP_X] => 20050119162457
            [IBLOCK_ID] => 11
            [NAME] => Photo
            [ACTIVE] => Y
            [SORT] => 500
            [CODE] =>
            [DEFAULT_VALUE] =>
            [PROPERTY_TYPE] => F
            [ROW_COUNT] => 1
            [COL_COUNT] => 30
            [LIST_TYPE] => L
            [MULTIPLE] => N
            [XML_ID] =>
            [FILE_TYPE] =>
            [MULTIPLE_CNT] => 5
            [TMP_ID] =>
            [WITH_DESCRIPTION] => Y
            [LINK_IBLOCK_ID] => 0
            [VALUE_TYPE] => text
            [VALUE_ENUM] =>
            [VALUE] => 2309
            [~VALUE] => 2309
            [DESCRIPTION] => HP
            [~DESCRIPTION] => HP
            [PROPERTY_VALUE_ID] => 53863
            [~NAME] => Photo
            [~DEFAULT_VALUE] =>
        )
)


_CIBElement::GetProperty - Bitrix Site Manager - Content Management & Portal Solutions

_CIBElement::GetProperty

array
_CIBElement::GetProperty(
   mixed ID
);

The method returns the property parameters and its values for this information block element.

Parameters

Parameter | Description
ID | Numeric (ID) or mnemonic code of the property to return.

Return Values

The method returns the property fields array and the additional keys and values:

  • "VALUE" => "property value or an array for a multiple property";
  • "VALUE_ENUM_ID" => "option ID for the LIST properties (array or a single value)";
  • "DESCRIPTION" => "property value description (array or a single value)";
  • "PROPERTY_VALUE_ID" => "property value ID (array or a single value)"

See Also

  • CIBlockElement::GetProperty()
  • _CIBElement::GetProperties()

    Example

    <?
$res = CIBlockElement::GetByID($_GET["PID"]);
if($obRes = $res->GetNextElement())
{
  $ar_res = $obRes->GetProperty("PHOTOS");
  print_r($ar_res);
}
?>

    Sample output:

    Array
(
    [ID] => 388
    [TIMESTAMP_X] => 20050119162457
    [IBLOCK_ID] => 11
    [NAME] => Photos with description
    [ACTIVE] => Y
    [SORT] => 500
    [CODE] =>
    [DEFAULT_VALUE] =>
    [PROPERTY_TYPE] => F
    [ROW_COUNT] => 1
    [COL_COUNT] => 30
    [LIST_TYPE] => L
    [MULTIPLE] => Y
    [XML_ID] =>
    [FILE_TYPE] =>
    [MULTIPLE_CNT] => 5
    [TMP_ID] =>
    [WITH_DESCRIPTION] => Y
    [LINK_IBLOCK_ID] => 0
    [VALUE_TYPE] => text
    [VALUE_ENUM] =>
    [VALUE] => Array
        (
            [0] => 2311
        )

    [~VALUE] => Array
        (
            [0] => 2311
        )

    [DESCRIPTION] => Array
        (
            [0] => Descr
        )

    [~DESCRIPTION] => Array
        (
            [0] => Descr
        )

    [PROPERTY_VALUE_ID] => Array
        (
            [0] => 53865
        )

    [~NAME] => Photos with description
    [~DEFAULT_VALUE] =>
)


Events

Event | Description
OnBeforeIBlockDelete | Called before an information block is deleted.
OnIBlockDelete | Called upon the deletion of an information block.
OnIBlockElementDelete | Called upon the deletion of an information block element.


OnAfterIBlockAdd event

event_handler(
 array &arFields
);
Fired after an attempt to add a new information block by a call to CIBlock::Add.

Parameters

Parameter | Description
arFields | An array of the new information block fields. The additional entry "RESULT" contains the value returned by the CIBlock::Add method. If an error occurred during the method execution, the entry "RESULT_MESSAGE" contains the error description.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

See Also

  • OnBeforeIBlockAdd event
  • CIBlock::Add
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnAfterIBlockAdd",
                Array("MyClass", "OnAfterIBlockAddHandler"));

class MyClass
{
    // create handler "OnAfterIBlockAdd"
    function OnAfterIBlockAddHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Redord ID=".
                           $arFields["ID"]." was added.");
        else
            AddMessage2Log("Error adding record ".
                           $arFields["ID"].
                           " (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnAfterIBlockElementAdd event

event_handler(
 array &arFields
);
Fired after an attempt to add a new information block element by a call to CIBlockElement::Add.

Parameters

Parameter | Description
arFields | An array of the new information block element fields. The additional entry "RESULT" contains the value returned by the CIBlockElement::Add method. If an error occurred during the method execution, the entry "RESULT_MESSAGE" contains the error description.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

See Also

  • OnBeforeIBlockElementAdd event
  • CIBlockElement::Add
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnAfterIBlockElementAdd",
                Array("MyClass", "OnAfterIBlockElementAddHandler"));

class MyClass
{
    // create handler "OnAfterIBlockElementAdd"
    function OnAfterIBlockElementAddHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Redord ID=".
                           $arFields["ID"]." added.");
        else
            AddMessage2Log("Error adding record ".
                           $arFields["ID"].
                           " (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnAfterIBlockElementUpdate event

event_handler(
 array &arFields
);
Fired after an attempt to modify the information block element by a call to CIBlockElement::Update.

Parameters

Parameter | Description
arFields | An array of the information block element fields to be updated. The additional entry "RESULT" contains the value returned by the CIBlockElement::Update method. If an error occurred during the method execution, the entry "RESULT_MESSAGE" contains the error description.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

See Also

  • OnBeforeIBlockElementUpdate event
  • CIBlockElement::Update
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnAfterIBlockElementUpdate",
                Array("MyClass", "OnAfterIBlockElementUpdateHandler"));

class MyClass
{
    // create handler "OnAfterIBlockElementUpdate"
    function OnAfterIBlockElementUpdateHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Redord ID=".
                           $arFields["ID"]." is modified.");
        else
            AddMessage2Log("Error updating record ".
                           $arFields["ID"].
                           " (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnAfterIBlockPropertyAdd event

event_handler(
 array &arFields
);
Fired after an attempt to add a new information block property by a call to CIBlockProperty::Add.

Parameters

Parameter | Description
arFields | An array of the new information block property fields. The additional entry "RESULT" contains the value returned by the CIBlockProperty::Add method. If an error occurred during the method execution, the entry "RESULT_MESSAGE" contains the error description.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

See Also

  • OnBeforeIBlockPropertyAdd event
  • CIBlockProperty::Add
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnAfterIBlockPropertyAdd", Array("MyClass", "OnAfterIBlockPropertyAddHandler"));

class MyClass
{
    // create handler "OnAfterIBlockPropertyAdd"
    function OnAfterIBlockPropertyAddHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Redord ID=".
                           $arFields["ID"]." added.");
        else
            AddMessage2Log("Error adding record ".
                           $arFields["ID"].
                           " (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnAfterIBlockPropertyUpdate event

event_handler(
 array &arFields
);
Fired after an attempt to modify the information block element property by a call to CIBlockProperty::Update.

Parameters

Parameter | Description
arFields | An array of fields of the updated information block element property. The additional entry "RESULT" contains the value returned by the CIBlockProperty::Update method. If an error occurred during the method execution, the entry "RESULT_MESSAGE" contains the error description.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

See Also

  • OnBeforeIBlockPropertyUpdate event
  • CIBlockProperty::Update
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnAfterIBlockPropertyUpdate",
                Array("MyClass", "OnAfterIBlockPropertyUpdateHandler"));

class MyClass
{
    // create handler "OnAfterIBlockPropertyUpdate"
    function OnAfterIBlockPropertyUpdateHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Redord ID=".
                           $arFields["ID"]." is modified.");
        else
            AddMessage2Log("Error updating record ".
                           $arFields["ID"].
                           " (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnAfterIBlockSectionAdd event

event_handler(
 array &arFields
);
Fired after an attempt to add a new information block section by a call to CIBlockSection::Add.

Parameters

Parameter | Description
arFields | An array of the new information block section fields. The additional entry "RESULT" contains the value returned by the CIBlockSection::Add method. If an error occurred during the method execution, the entry "RESULT_MESSAGE" contains the error description.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

See Also

  • OnBeforeIBlockSectionAdd event
  • CIBlockSection::Add
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnAfterIBlockSectionAdd",
                Array("MyClass", "OnAfterIBlockSectionAddHandler"));

class MyClass
{
    // create handler "OnAfterIBlockSectionAdd"
    function OnAfterIBlockSectionAddHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Redord ID=".
                           $arFields["ID"]." was added.");
        else
            AddMessage2Log("Error adding record ".
                           $arFields["ID"].
                           " (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnAfterIBlockSectionUpdate event

event_handler(
 array &arFields
);
Fired after an attempt to modify the information block section by a call to CIBlockSection::Update.

Parameters

Parameter | Description
arFields | An array of the information block element fields to be updated. The additional entry "RESULT" contains the value returned by the CIBlockSection::Update method. If an error occurred during the method execution, the entry "RESULT_MESSAGE" contains the error description.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

See Also

  • OnBeforeIBlockSectionUpdate event
  • CIBlockSection::Update
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnAfterIBlockSectionUpdate",
                Array("MyClass", "OnAfterIBlockSectionUpdateHandler"));

class MyClass
{
    // create handler "OnAfterIBlockSectionUpdate"
    function OnAfterIBlockSectionUpdateHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Redord ID=".
                           $arFields["ID"]." is modified.");
        else
            AddMessage2Log("Error updating record ".
                           $arFields["ID"].
                           " (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnAfterIBlockUpdate event

event_handler(
 array &arFields
);
Fired after an attempt to modify the information block by calling CIBlock::Update.

Parameters

Parameter | Description
arFields | An array of the information block fields to be updated. The additional entry "RESULT" contains the value returned by the CIBlock::Update method. If an error occurred during the method execution, the entry "RESULT_MESSAGE" contains the error description.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

See Also

  • OnBeforeIBlockUpdate event
  • CIBlock::Update
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnAfterIBlockUpdate",
                Array("MyClass",
                      "OnAfterIBlockUpdateHandler"));

class MyClass
{
    // create handler "OnAfterIBlockUpdate"
    function OnAfterIBlockUpdateHandler(&$arFields)
    {
        if($arFields["RESULT"])
            AddMessage2Log("Redord ID=".
                           $arFields["ID"]." is modified.");
        else
            AddMessage2Log("Error updating record ".
                           $arFields["ID"].
                           " (".$arFields["RESULT_MESSAGE"].").");
    }
}
?>


OnBeforeIBlockAdd

bool
event_handler(
   array &arParams
);
Fired from CIBlock::Add before the new information block is added. Can be used to cancel the operation or to redefine fields..

Parameters

Parameter | Description
arParams | An array of the new information block fields.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

Return Values

To cancel operation and terminate CIBlock::Add, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterIBlockAdd event
  • CIBlock::Add
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnBeforeIBlockAdd", Array("MyClass", "OnBeforeIBlockAddHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockAdd"
    function OnBeforeIBlockAddHandler(&$arFields)
    {
        if(strlen($arFields["CODE"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Enter the mnemonic code.");
            return false;
        }
    }
}
?>


OnBeforeIBlockDelete

bool
user_defined_handler(
 int ID
);

Called before an information block is deleted.

Parameters

Parameter | Description
ID | Information block ID

Return Values

The user-defined handler returns false to prevent the information block from deletion.

Example

<?
// Connect the handler
RegisterModuleDependences("iblock",
                          "OnBeforeIBlockDelete",
                          "catalog",
                          "CCatalog",
                          "OnIBlockDelete");

// Implement the handler
class CCatalog
{
  * * *

  function OnBeforeIBlockDelete($ID)
  {
    // Information blocks cannot be deleted.
    return false;
  }
}

?>


OnBeforeIBlockElementAdd

bool
event_handler(
   array &arParams
);
Fired from CIBlockElement::Add before the new information block is added. Can be used to cancel the operation or to redefine fields.

Parameters

Parameter | Description
arParams | An array of the new information block element fields.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

Return Values

To cancel operation and terminate CIBlockElement::Add, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterIBlockElementAdd event
  • CIBlockElement::Add
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnBeforeIBlockElementAdd", Array("MyClass", "OnBeforeIBlockElementAddHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockElementAdd"
    function OnBeforeIBlockElementAddHandler(&$arFields)
    {
        if(strlen($arFields["CODE"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Enter the mnemonic code.");
            return false;
        }
    }
}
?>


OnBeforeIBlockElementDelete

bool
event_handler(
 int ID
);
Fired before the information block element is deleted by CIBlockElement::Delete. A common task of this handler is to cancel or approve the deletion.

Parameters

Parameter | Description
ID | The ID of the element to be deleted.

Return Values

To cancel the element deletion and terminate CIBlockElement::Delete, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • CIBlockElement::Delete
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnBeforeIBlockElementDelete",
                Array("MyClass", "OnBeforeIBlockElementDeleteHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockElementDelete"
    function OnBeforeIBlockElementDeleteHandler($ID)
    {
        if($ID==1)
        {
            global $APPLICATION;
            $APPLICATION->throwException("the element ID=1 cannot be deleted.");
            return false;
        }
    }
}
?>


OnBeforeIBlockElementUpdate

bool
event_handler(
   array &arParams
);
Fired from CIBlockElement::Update before the information block element is modified. Can be used to cancel modification or to redefine fields.

Parameters

Parameter | Description
arParams | An array of the new information block element fields.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

Return Values

To cancel the update and terminate CIBlockElement::Update, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterIBlockElementUpdate event
  • CIBlockElement::Update
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnBeforeIBlockElementUpdate", Array("MyClass", "OnBeforeIBlockElementUpdateHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockElementUpdate"
    function OnBeforeIBlockElementUpdateHandler(&$arFields)
    {
        if(strlen($arFields["CODE"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Enter the mnemonic code. (ID:".$arFields["ID"].")");
            return false;
        }
    }
}
?>


OnBeforeIBlockPropertyAdd

bool
event_handler(
   array &arParams
);
Fired from CIBlockProperty::Add before the new information block property is added. Can be used to cancel operation or to redefine fields.

Parameters

Parameter | Description
arParams | An array of fields of the new information block property.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

Return Values

To cancel the operation and terminate CIBlockProperty::Add, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterIBlockPropertyAdd event
  • CIBlockProperty::Add
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnBeforeIBlockPropertyAdd", Array("MyClass", "OnBeforeIBlockPropertyAddHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockPropertyAdd"
    function OnBeforeIBlockPropertyAddHandler(&$arFields)
    {
        if(strlen($arFields["CODE"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Enter the mnemonic code.");
            return false;
        }
    }
}
?>


OnBeforeIBlockPropertyDelete

bool
event_handler(
 int ID
);
Fired before the information block property is deleted by a call to CIBlockProperty::Delete. A common task of this handler is to cancel or approve the deletion.

Parameters

Parameter | Description
ID | The ID of the property to be deleted.

Return Values

To cancel deletion and terminate CIBlockProperty::Delete, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • CIBlockProperty::Delete
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnBeforeIBlockPropertyDelete",
                Array("MyClass", "OnBeforeIBlockPropertyDeleteHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockPropertyDelete"
    function OnBeforeIBlockPropertyDeleteHandler($ID)
    {
        if($ID==1)
        {
            global $APPLICATION;
            $APPLICATION->throwException("The property ID=1 cannot be deleted.");
            return false;
        }
    }
}
?>


OnBeforeIBlockPropertyUpdate

bool
event_handler(
 array &arParams
);
Fired from CIBlockProperty::Update before the information block property become modified. Can be used to cancel modification or to redefine fields.

Parameters

Parameter | Description
arParams | An array of the information block property fields.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

Return Values

To cancel the update and terminate CIBlockProperty::Update throw an exception by calling $APPLICATION->ThrowException() within the handler and return false.

See Also

  • OnAfterIBlockPropertyUpdate event
  • CIBlockProperty::Update
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnBeforeIBlockPropertyUpdate", Array("MyClass", "OnBeforeIBlockPropertyUpdateHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockPropertyUpdate"
    function OnBeforeIBlockPropertyUpdateHandler(&$arFields)
    {
        if(strlen($arFields["CODE"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Enter the mnemonic code. (ID:".$arFields["ID"].")");
            return false;
        }
    }
}
?>


OnBeforeIBlockSectionAdd

bool
event_handler(
   array &arParams
);
Fired from CIBlockSection::Add before the information block section is inserted. Can be used to decline insertion or to redefine fields.

Parameters

Parameter | Description
arParams | An array of the new information block section fields.

Note
The parameter(s) of this handler are references to the original variables. Hence, altering their values from within the handler causes changing values of the source variables passed to the handler.

Return Values

To cancel insertion and terminate CIBlockSection::Add, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterIBlockSectionAdd event
  • CIBlockSection::Add
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnBeforeIBlockSectionAdd", Array("MyClass", "OnBeforeIBlockSectionAddHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockSectionAdd"
    function OnBeforeIBlockSectionAddHandler(&$arFields)
    {
        if(strlen($arFields["CODE"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Enter the mnemonic code.");
            return false;
        }
    }
}
?>


OnBeforeIBlockSectionDelete

bool
event_handler(
 int ID
);
Fired before a section is deleted by calling CIBlockSection::Delete. A common task of this handler is to cancel or approve the deletion.

Parameters

Parameter | Description
ID | The ID of the section to be deleted.

Return Values

To cancel the section deletion and terminate the method CIBlockSection::Delete , throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • CIBlockSection::Delete
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnBeforeIBlockSectionDelete",
                Array("MyClass", "OnBeforeIBlockSectionDeleteHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockSectionDelete"
    function OnBeforeIBlockSectionDeleteHandler($ID)
    {
        if($ID==1)
        {
            global $APPLICATION;
            $APPLICATION->throwException("section ID=1 cannot be deleted.");
            return false;
        }
    }
}
?>


OnBeforeIBlockSectionUpdate

bool
event_handler(
 array &arParams
);
Fired from the method CIBlockSection::Update before an information block section is modified. Can be used to decline modifying a section or to redefine fields.

Parameters

Parameter | Description
arParams | An array of fields of the information block section to be updated.

Note
The parameter of this handler is a reference to the original variable. Hence, altering the value(s) from within the handler causes changing values of the source variable passed to the handler.

Return Values

To cancel the information block section update and terminate the method CIBlockSection::Update, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterIBlockSectionUpdate event
  • CIBlockSection::Update
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnBeforeIBlockSectionUpdate", Array("MyClass", "OnBeforeIBlockSectionUpdateHandler"));

class MyClass
{
    // create handler "OnBeforeIBlockSectionUpdate"
    function OnBeforeIBlockSectionUpdateHandler(&$arFields)
    {
        if(strlen($arFields["CODE"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Enter the mnemonic code. (ID:".$arFields["ID"].")");
            return false;
        }
    }
}
?>


OnBeforeIBlockUpdate

bool
event_handler(
 array &arParams
);
Fired from CIBlock::Update before the information block is modified. Can be used to decline modifying a block or to redefine fields.

Parameters

Parameter | Description
arParams | An array of fields of the information block to be updated.

Note
The parameter of this handler is a reference to the original variable. Hence, altering the value(s) from within the handler causes changing values of the source variable passed to the handler.

Return Values

To cancel the information block update and terminate the method CIBlock::Update, throw an exception by calling $APPLICATION->ThrowException() and return false.

See Also

  • OnAfterIBlockUpdate event
  • CIBlock::Update
  • Handling events

    Example

<?
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock",
                "OnBeforeIBlockUpdate",
                Array("MyClass", "OnBeforeIBlockUpdateHandler"));

class MyClass
{
    // create handler for "OnBeforeIBlockUpdate"
    function OnBeforeIBlockUpdateHandler(&$arFields)
    {
        if(strlen($arFields["CODE"])<=0)
        {
            global $APPLICATION;
            $APPLICATION->throwException("Enter the mnemonic code. (ID:".$arFields["ID"].")");
            return false;
        }
    }
}
?>


OnIBlockDelete

user_defined_handler(
 int ID
);

Called at the moment an information block is deleted.

Parameters

Parameter | Description
ID | Information block ID.

Example

<?
// Connect the handler
RegisterModuleDependences("iblock",
                          "OnIBlockDelete",
                          "catalog",
                          "CCatalog",
                          "OnIBlockDelete");

// Implement the handler
class CCatalog
{
  * * *

  function OnIBlockDelete($ID)
  {
    // Now the handler is called upon deletion
    return CCatalog::Delete($ID);
  }
}

?>


OnIBlockElementDelete

user_defined_handler(
 int ID
);

Called when an information block element is deleted.

Parameters

Parameter | Description
ID | Information block element ID.

Example

<?
// Connect the handler
RegisterModuleDependences("iblock",
                          "OnIBlockElementDelete",
                          "catalog",
                          "CCatalogProduct",
                          "OnIBlockElementDelete");

// Implement the handler
class CCatalogProduct
{
  * * *

  function OnIBlockElementDelete($PRODUCT_ID)
  {
    // Now the handler is called upon deletion
    global $DB;
    echo "Deleting...";
    return True;
  }
}
?>


Information block functions for use in the public section - Bitrix Site Manager - Content Management & Portal Solutions

Functions for use in the public section

Function | Description
GetIBlockList | Returns a list of information blocks; allows using the filter.
GetIBlock | Returns an information block by its ID.
GetIBlockElementListEx | Returns a list of elements; allows using the filter.
GetIBlockElementList | Returns a list of information block elements.
GetIBlockElement | Returns an element by its ID.
GetIBlockSectionList | Returns a list of information block sections.
GetIBlockSection | Returns a section by its ID.


GetIBlock - Bitrix Site Manager - Content Management & Portal Solutions

GetIBlock

array
GetIBlock(
 string ID,
 type = ""
);

The function returns an information block by its ID.

Parameters

Parameter | Description
ID | Information block ID.
type | Type of the information block. Specified in the module settings. If present, the selected block is checked to match this type. Optional. By default, no restrictions applied.

Return Values

The function returns an array of the information block fields. All returned fields are HTML compliant and safe. Variables #SITE_DIR# and #IBLOCK_ID# are replaced with their corresponding values (fields LIST_PAGE_URL and DETAIL_PAGE_URL). If no block is found, false is returned.

Remarks

The function succeeds only if a block is active and is bound to the current site.

See Also

  • Fields of information blocks

    • Example

    <?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

$APPLICATION->SetTitle("Products");

// check if the module is installed and get the block with the ID of $BID and type of catalog
if(CModule::IncludeModule("iblock") && ($arIBlock = GetIBlock($_GET["BID"], "catalog")))
{
   // make the page title same as the block name
   $APPLICATION->SetTitle($arIBlock["NAME"]);
   // add title to the navigation chain
   $APPLICATION->AddChainItem($arIBlock["NAME"], $arIBlock["LIST_PAGE_URL"]);

   // other operations
   // ....
}
else
   ShowError("Cannot find the information block.");

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
?>


GetIBlockElement - Bitrix Site Manager - Content Management & Portal Solutions

GetIBlockElement

array
GetIBlockElement(
 int ID,
 string type = ""
);

The function returns an information block element by its ID.

Parameters

Parameter | Description
ID | Element ID.
type | Type of an element. Specified in the module settings. If present, the selected element is checked to match this type. Optional. By default, no restrictions applied.

Return Values

The function returns an array of the information block fields and the following fields:

  • IBLOCK_NAME - information block name;
  • PROPERTIES - array of property values. Has property symbolic codes as indices (specified in the information block settings). If the code is not specified, the unique ID of a property is used.

Value of each property is an array of the following format:

Array(
"NAME" => "property name",
"DEFAULT_VALUE" => "default property value",
"VALUE" => "property value or an array of values for multiple property sets",
"VALUE_ENUM_ID" => "ID of the property value for the type LIST"
)

If no element can be found, the function returns false.

Remarks

Variables #SITE_DIR#, #IBLOCK_ID#, #EXTERNAL_ID# and #ID# are replaced with their corresponding values (fields LIST_PAGE_URL and DETAIL_PAGE_URL). If no block is found, false is returned.

See Also

  • Fields of information blocks

    • Example

    <?
require($_SERVER['DOCUMENT_ROOT'].'/bitrix/header.php');

$APPLICATION->SetTitle('Product description');

// include the module and select the element of the type product by its ID
$arIBlockElement = false;
if (CModule::IncludeModule('iblock') &&
   ($arIBlockElement = GetIBlockElement($ID, 'product')))
{
   // set the page title according to the element name
   $APPLICATION->SetTitle($arIBlockElement['NAME']);
   // add title to the navigation chain; make it a link to the current information block
   $APPLICATION->AddChainItem($arIBlockElement['IBLOCK_NAME'],
                              'products.php?ID='.$arIBlockElement['IBLOCK_ID']);

   // show the detailed image
   echo ShowImage($arIBlockElement['DETAIL_PICTURE'], 150, 150, 'border="0"', '', true);
   // render the detailed description
   echo $arIBlockElement['DETAIL_TEXT'].'<br>';
   // render the PRICE property
   echo $arIBlockElement['PROPERTIES']['PRICE']['VALUE'].'<br>';

   // display the other properties
   $arProps = $arIBlockElement['PROPERTIES'];
   foreach($arProps as $property_code=>$arValue)
   {
      // skip if the property value is empty of the property name is PRICE
      if ($property_code=='PRICE' ||
         (!is_array($arValue['VALUE']) && strlen($arValue['VALUE'])<=0) ||
         (is_array($arValue['VALUE']) && count($arValue['VALUE'])<=0)
    )
         continue;

      // display a pair "Name:Value"
      if(!is_array($arValue['VALUE']))
         echo $arValue['NAME'].": ".$arValue['VALUE'];
      else
      {
         echo $arValue['NAME'].': ';
         foreach($arValue['VALUE'] as $val)
         {
            echo $val.'<br>';
         }
      }
   }
}
else
   echo ShowError('Cannot find element');

require($_SERVER["DOCUMENT_ROOT"].'/bitrix/footer.php");
?>


GetIBlockElementList - Bitrix Site Manager - Content Management & Portal Solutions

GetIBlockElementList

CIBlockResult
GetIBlockElementList(
 int iblock_id,
 int section_id = false,
 array order = Array("SORT"=>"ASC"),
 int cnt = 0,
 array arFilter = Array()
);

The function returns active elements of the information block defined by iblock_id.

Parameters

Parameter | Description
iblock_id | The ID of the information block to search for elements.
section_id | The ID of the section to search for elements. Set section_id to 0 to obtain elements from the information block root. Optional. By default (false), the function selects all records without any restrictions.
order Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • sort - sort weight;
  • timestamp_x - modification date;
  • name - name;
  • id - element ID;
  • active_from - date the element is active from;
  • active_to - date until which the element is active.
order is the sort order. Can be asc for ascending sorts or desc for descending.

Default value is Array("sort"=>"asc"). Full list of sorting fields and additional information can be found in CIBlockElement::GetList()
cnt | Maximum number of the returned records. Optional. All records are returned by default.
arFilter Optional additional filter by fields in the form of Array("Filtered field"=>"Value", ...). The Filtered field can be one of the following:
  • ID - by the ID;
  • ACTIVE - by the active state (Y|N);
  • NAME - by names (wildcards [%_] allowed);
  • PREVIEW_TEXT - by short text (wildcards [%_] allowed);
  • DETAIL_TEXT - by detailed description (wildcards [%_] allowed);
  • SEARCHABLE_CONTENT - by all searchable content. This includes title, short and detailed descriptions (wildcards [%_] allowed);
  • CODE - by mnemonic identifier (wildcards [%_] allowed);
  • SORT - by sort weight;
  • EXTERNAL_ID - by external ID (wildcards [%_] allowed);
  • TIMESTAMP_X - by modification date;
  • DATE_CREATE - by creation date;
  • DATE_ACTIVE_FROM - by date of beginning of the active state;
  • DATE_ACTIVE_TO - by the date the active state expires;
  • ACTIVE_DATE - do filter by active state dates (DATE_ACTIVE_FROM and DATE_ACTIVE_TO), can be Y or N;
  • IBLOCK_ID - by the information block ID;
  • IBLOCK_CODE - by the information block mnemonic code (wildcards [%_] allowed);
  • IBLOCK_LID - by language (wildcards [%_] allowed);
  • IBLOCK_TYPE - by the block type (wildcards [%_] allowed);
  • IBLOCK_ACTIVE - by the block active state (wildcards [%_] allowed);
  • SECTION_ID - by the parent section;
  • PROPERTY_<property_ID> - by the property value. Wildcards ([%_]) allowed. When searching the "LIST" properties, the search is performed by the ID, not by value ;
  • PROPERTY_<property_ID>_VALUE - by the values for the "LIST" properties. Wildcards ([%_]) allowed. The search is performed by the string value, not by the ID;
  • CATALOG_<CATALOG_FIELD>_<PRICE_TYPE> - by the field CATALOG_FIELD of the price type PRICE_TYPE (price type code). CATALOG_FIELD can be PRICE - price, CURRENCY - currency.
All the filter fields except SECTION_ID and ACTIVE_DATE may have the conditions specified before the name.

The fields SECTION_ID and ACTIVE_DATE may have negation sign ("!") before the name.

The "filter values" are a single value or an array.

The default parameter value is an empty array.
Full list of sorting fields and additional information can be found in CIBlockElement::GetList()

Return Values

The function returns an instance of CIBlockResult with active elements, i.e. those having the flag Active set, valid active period and pertaining to the active parent information blocks of the current site.

Remarks

To facilitate handling the function return values, you can use the method CDBResult::GetNext() returning an array of the information block element fields. All fields returned by this method are HTML compliant and safe. Variables #SITE_DIR#, #IBLOCK_ID#, #EXTERNAL_ID# and #ID# are replaced with their corresponding values (fields LIST_PAGE_URL and DETAIL_PAGE_URL). If the result is empty or the end of collection is reached, false is returned. Other methods of the CDBResult class can also be used, but keep in mind that they do not substitute variables like #SITE_DIR# with their values.

See Also

  • Fields of information block elements
  • GetIBlockElementListEx

    • Example

    <?
if(CModule::IncludeModule("iblock"))
{
   // select 10 elements from the section $ID of the information block $BID
   $items = GetIBlockElementList($_GET['BID'],
                                 $_GET['ID'], Array("SORT"=>"ASC"), 10);
   $items->NavPrint("Products");
   while($arItem = $items->GetNext())
   {
      echo $arItem["NAME"]."<br>";
      echo $arItem["PREVIEW_TEXT"]."<br>";
   }
   $items->NavPrint("Products");
}
?>


GetIBlockElementListEx - Bitrix Site Manager - Content Management & Portal Solutions

GetIBlockElementListEx

CIBlockResult
GetIBlockElementListEx (
 string type,
 mixed TypesInc = Array(),
 mixed TypesExc = Array(,
 array Order = Array("SORT"=>"ASC"),
 int cnt = 0,
 array arFilter = Array(),
 array arSelect = Array(),
 mixed arGroupBy = false
);

The function returns active elements of the information block type defined by type. The elements returned are active within the current site.

Parameters

Parameter | Description
type | Type of information blocks to search for elements.
TypesInc Allows to set the filter that describes information blocks included in the selection. The filter uses the ID or mnemonic code of an information block as the match criteria. You can use either a single value or an array of values here.
This parameter is optional. By default, all elements of information blocks of the matching type is selected.
Example: "product_news".
TypesExc Similar to TypesInc, but sets the filter to exclude the matching information blocks.
This parameter is optional. By default, all elements of information blocks of the matching type is selected.
Example: Array("company_news", "product_news", 22).
Order Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • sort - sort weight;
  • timestamp_x - modification date;
  • name - name;
  • id - element ID;
  • active_from - date the element is active from;
  • active_to - date until which the element is active.
order is the sort order. Can be asc for ascending sorts or desc for descending.

Default value is Array("sort"=>"asc"). Full list of sorting fields and additional information can be found in CIBlockElement::GetList()
cnt | Maximum number of the returned records. Optional. All records are returned by default.
arFilter Optional additional filter by fields in the form of Array("Filtered field"=>"Value", ...). The Filtered field can be the following:
  • ID - by the ID;
  • ACTIVE - by the active state (Y|N);
  • NAME - by names (wildcards [%_] allowed);
  • PREVIEW_TEXT - by short text (wildcards [%_] allowed);
  • DETAIL_TEXT - by detailed description (wildcards [%_] allowed);
  • SEARCHABLE_CONTENT - by all searchable content. This includes title, short and detailed descriptions (wildcards [%_] allowed);
  • CODE - by mnemonic identifier (wildcards [%_] allowed);
  • SORT - by sort weight;
  • EXTERNAL_ID - by external ID (wildcards [%_] allowed);
  • TIMESTAMP_X - by modification date;
  • DATE_CREATE - by creation date;
  • DATE_ACTIVE_FROM - by date of beginning of the active state;
  • DATE_ACTIVE_TO - by the date the active state expires;
  • ACTIVE_DATE - do filter by active state dates (DATE_ACTIVE_FROM and DATE_ACTIVE_TO), can be Y or N;
  • IBLOCK_ID - by the information block ID;
  • IBLOCK_CODE - by the information block mnemonic code (wildcards [%_] allowed);
  • IBLOCK_LID - by language (wildcards [%_] allowed);
  • IBLOCK_TYPE - by the block type (wildcards [%_] allowed);
  • IBLOCK_ACTIVE - by the block active state (wildcards [%_] allowed);
  • SECTION_ID - by the parent section;
  • PROPERTY_<property_ID> - by the property value. Wildcards ([%_]) allowed. When searching the "LIST" properties, the search is performed by the ID, not by value ;
  • PROPERTY_<property_ID>_VALUE - by the values for the "LIST" properties. Wildcards ([%_]) allowed. The search is performed by the string value, not by the ID;
  • CATALOG_<CATALOG_FIELD>_<PRICE_TYPE> - by the field CATALOG_FIELD of the price type PRICE_TYPE (price type code). CATALOG_FIELD can be PRICE - price, CURRENCY - currency.
All the filter fields except SECTION_ID and ACTIVE_DATE may have the conditions specified before the name.

The fields SECTION_ID and ACTIVE_DATE may have negation sign ("!") before the name.

The "filter values" are a single value or an array.

The default parameter value is an empty array.
Full list of sorting fields and additional information can be found in CIBlockElement::GetList()
arSelect Array containing the element fields to retrieve. Allows to get the property values immediately. To do so, set the name of one of the fields to PROPERTY_<PROPERTY_CODE> where PROPERTY_CODE is the ID or mnemonic code. The result will contain values of the element properties as fields:
  • PROPERTY_<PROPERTY_CODE>_VALUE - property value;
  • PROPERTY_<PROPERTY_CODE>_ID - element value ID;
  • PROPERTY_<PROPERTY_CODE>_ENUM_ID - value ID (for properties of the LIST type).
Obtaining the element price values is also possible if the Commercial Catalog module is installed. Set one of the fields to CATALOG_GROUP_<PROPERTY_CODE> where PROPERTY_CODE is the ID of the price type.

By default, all the element fields are retrieved.
arGroupBy Array of fields for grouping. If specified, the selection becomes grouped by these fields, and the result contains the CNT field (number of grouped elements). If an empty array is passed, the function returns the number of elements in the CNT field.

Grouping is possible by the element fields as well as the property values. If the latter is the case, set one of the grouping fields to PROPERTY_<PROPERTY_CODE> where PROPERTY_CODE is the ID or mnemonic code of the properties.

Optional. By default, records are not grouped.

Return Values

The function returns an instance of CIBlockResult with active elements, i.e. those having the flag Active set, valid active period and pertaining to the active parent information blocks of the current site.

Remarks

To facilitate handling the function return values, you can use the method CDBResult::GetNext() returning an array of the information block element fields. All fields returned by this method are HTML compliant and safe. Variables #SITE_DIR#, #IBLOCK_ID#, #EXTERNAL_ID# and #ID# are replaced with their corresponding values (fields LIST_PAGE_URL and DETAIL_PAGE_URL). If the result is empty or the end of collection is reached, false is returned. Other methods of the CDBResult class can also be used, but keep in mind that they do not substitute variables like #SITE_DIR# with their values.

See Also

  • CIBlockElement::GetList()
  • Fields of information block elements
  • GetIBlockElementList

    • Example

    <?
if(CModule::IncludeModule("iblock"))
{
   // select 15 elements of the type "news"
   // from the information block "company_news"
   $items = GetIBlockElementListEx("news", "company_news", Array(),
                                   Array("DATE_ACTIVE_FROM"=>"DESC",
                                         "SORT"=>"ASC",
                                         "NAME" => "ASC"),
                                   15);

   // page navigation
   $items->NavPrint("Company news");
   // loop on news
   while ($arItem = $items->GetNext())
   {
     // display a link to the detailed view
      echo "<a href='".$aritem["detail_page_url"]."'>".$aritem["name"]."</a>";
     // display data
      echo $arItem["DATE_ACTIVE_FROM"]."<br>";
     // display the preamble image with the link to the detailed view
      echo ShowImage($arItem["PREVIEW_PICTURE"], 100, 100,
                     "border='0'", $arItem["DETAIL_PAGE_URL"]);
     // display the preamble
      echo $arItem["PREVIEW_TEXT"]."<hr>";
   }
   $items->NavPrint("Company news");
}
?>

    <?
// Display news for today (DATE_ACTIVE_FROM >= today):
$items = GetIBlockElementListEx("news", Array(), Array(),
              Array("SORT"=>"ASC", "ID" => "DESC"), 15,
              Array(
                ">=DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CSite::GetDateFormat("SHORT")))
              )
          );

// Display news for yesterday (DATE_ACTIVE_FROM >= yesterday && DATE_ACTIVE_FROM < today):
$items = GetIBlockElementListEx("news", Array(), Array(),
              Array("SORT"=>"ASC", "ID" => "DESC"), 15,
              Array(
                ">=DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CSite::GetDateFormat("SHORT")),
                                           mktime(0,0,0,date("m"), date("d")-1, date("Y"))),
                "<DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CSite::GetDateFormat("SHORT")),
                                          mktime(0,0,0,date("m"), date("d"), date("Y")))
              )
          );

// Display news for 01.01.2003 (DATE_ACTIVE_FROM >= 01.01.2003 && DATE_ACTIVE_FROM < 02.01.2003):
$items = GetIBlockElementListEx("news", Array(), Array(),
              Array("SORT"=>"ASC", "ID" => "DESC"), 15,
              Array(
                ">=DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CSite::GetDateFormat("SHORT")),
                                           mktime(0,0,0,1,1,2003)),
                "<DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CSite::GetDateFormat("SHORT")),
                                          mktime(0,0,0,1,2,2003))
              )
          );
?>


GetIBlockList - Bitrix Site Manager - Content Management & Portal Solutions

GetIBlockList

CDBResult
GetIBlockList (
 string type,
 mixed TypesInc = array(),
 mixed TypesExc = array(),
 array Order = array("SORT"=>"ASC"),
 int cnt = 0
);

The function returns information blocks of the type type. The blocks returned are active within the current site.

Parameters

Parameter | Description
type | Type of information blocks.
TypesInc Allows to set the filter that describes information blocks included in the selection. The filter uses the ID or mnemonic code of an information block as the match criteria. You can use either a single value or an array of values here.
This parameter is optional. By default, all elements of information blocks of the matching type is selected.
Example: "product_news".
TypesExc Similar to TypesInc, but sets the filter to exclude the matching information blocks.
This parameter is optional. By default, all elements of information blocks of the matching type is selected.
Example: Array("company_news", "product_news", 22).
Order Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • id - element ID;
  • sort - sort weight;
  • timestamp_x - modification date;
  • name - name.
order is the sort order. Can be asc for ascending sorts or desc for descending.

Default value is Array("sort"=>"asc").
cnt | Maximum number of the returned records. Optional. All records are returned by default.

Return Values

The function returns an instance of CIBlockResult with active blocks of the current site (from within which the function is called), i.e. those having the flag Active set.

Remarks

To facilitate handling the function return values, you can use the method CDBResult::GetNext() returning an array of the information block fields. All fields returned by this method are HTML compliant and safe. Variables #SITE_DIR# and #IBLOCK_ID# are replaced with their corresponding values (fields LIST_PAGE_URL and DETAIL_PAGE_URL). If the result is empty or the end of collection is reached, false is returned.
Other methods of the CDBResult class can also be used, but keep in mind that they do not substitute variables like #SITE_DIR# with their values.

See Also

  • Fields of an information block

    • Example

    <?
if(CModule::IncludeModule("iblock"))
{
   // select all information blocks of the type "catalog"
   $iblocks = GetIBlockList("catalog");
   while($arIBlock = $iblocks->GetNext()) // loop on all blocks
   {
      // do not call function htmlspecialchars($arIBlock["NAME"]),
      // as the method GetNext() does
      echo "Name: ".$arIBlock["NAME"]."<br>";
   }
}

?>

    <?
if(CModule::IncludeModule("iblock"))
{
   // select 5 information blocks of the type "news" sorted by name
   // except those with the mnemonic code "company_news"
   $iblocks = GetIBlockList(
               "news",
               Array(),
               "company_news",
               Array("name"=>"asc"),
               5);

   // loop on information blocks
   while($arIBlock = $iblocks->GetNext()):
   ?>
       // make a link to the news page
       <a href="<?echo $arIBlock["LIST_PAGE_URL"]?>"><?echo $arIBlock["NAME"]?></a><br>
       <?
       // select 5 last news from each block
       $items = GetIBlockElementList(
                   $arIBlock["ID"],
                   false,
                   Array("ACTIVE_FROM"=>"desc", "sort"=>"asc"),
                   5);
       while($arItem = $items->GetNext())
       {
            // display news
       }
   endwhile;
}
?>


GetIBlockSection - Bitrix Site Manager - Content Management & Portal Solutions

GetIBlockSection

array
GetIBlockSection(
 int ID,
 string type = ""
);

The function returns an information block section.

Parameters

Parameter | Description
ID | Section ID.
type | Optional type of information blocks to search for a section. Specified in the module settings. If present, the selected section is checked to match the type. By default, no restrictions applied.

Return Values

The function returns an array of the information block section fields and a field IBLOCK_NAME (name of an information block). All fields returned by this method are HTML compliant and safe. If sections cannot be found, false is returned.

Remarks

The function succeeds only if a section is active, is contained in an active information block and is bound to the current site.

See Also

  • Fields of information block section

    • Example

    <?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

$APPLICATION->SetTitle("Section view");

// include the module and select a section
// of information blocks of the type product
if (CModule::IncludeModule("iblock") &&
    ($arIBlockSection = GetIBlockSection($_GET['ID'], 'product')))
{
   // make the page title same as the section name
   $APPLICATION->SetTitle($arIBlockSection["NAME"]);
   // add the name and link to the current information block
   $APPLICATION->AddChainItem($arIBlockSection["IBLOCK_NAME"],
                              "products.php?ID=".$arIBlockElement["IBLOCK_ID"]);
   // display the image
   echo ShowImage($arIBlockSection["PICTURE"], 150, 150,
                  "border='0'", "", true);
   // display the detailed description
   echo $arIBlockSection["DESCRIPTION"]."<br>";
}
else
   echo ShowError("Cannot find section");

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
?>


GetIBlockSectionList - Bitrix Site Manager - Content Management & Portal Solutions

GetIBlockSectionList

CDBResult
GetIBlockSectionList (
 int iblock_id,
 int section_id = false,
 array order = Array("LEFT_MARGIN"=>"ASC"),
 int cnt = 0,
 array arFilter = Array()
);

The function returns active sections of an information block iblock_id.

Parameters

Parameter | Description
iblock_id | The ID of an information block to search for sections.
section_id The ID of the parent section. To obtain the root sections of an information block, set the parameter section_id to 0.

Optional. By default (false), all records are returned without restrictions.
order Optional sort order. Array of the format Array(by1=>order1[, by2=>order2 [, ..]]) where by is the field for sorting. The field can have the following values:
  • sort - sort weight;
  • timestamp_x - modification date;
  • name - name;
  • id - section ID;
  • left_margin - applies the through sorting (see Remarks);
  • depth_level - section nesting level.
order is the sort order. Can be asc for ascending sorts or desc for descending.

Default value is Array("sort"=>"asc"). Full list of sorting fields and additional information can be found in CIBlockElement::GetList()
cnt | Maximum number of the returned records. Optional. All records are returned by default.
arFilter Optional additional filter by fields in the form of Array("Filtered field"=>"Value", ...). The Filtered field can be the following:
  • ACTIVE - by the active state (Y|N);
  • GLOBAL_ACTIVE - by the active state with respect to the active state of parent sections (Y|N);
  • NAME - by name (wildcards [%_] allowed);
  • CODE - by mnemonic code (wildcards [%_] allowed);
  • EXTERNAL_ID - by the external ID (wildcards [%_] allowed);
  • IBLOCK_ID - by the information block ID;
  • DEPTH_LEVEL - by nesting level;
  • SECTION_ID - by parent section;
  • LEFT_MARGIN, RIGHT_MARGIN - by left or right margin (see Remarks);
  • ID - by the ID;
  • PROPERTY - by values of the properties of the child elements; PROPERTY is an array of the format Array("property ID"=>"value", ...).
All the filter fields may have the conditions specified before the name.

By default, no additional filtering applied.

Full list of sorting fields and additional information can be found in CIBlockElement::GetList()

Return Values

The function returns an instance of CDBResult containing the active sections, i.e. those of active information blocks and contained in active parent sections.

Remarks

  1. To facilitate handling the function return values, you can use the method CDBResult::GetNext() returning an array of the information block element fields. All fields returned by this method are HTML compliant and safe. If the result is empty or the end of collection is reached, false is returned.
  2. The sorting field left_margin (the so-called "through sorting") is calculated based on the field sort, nesting level and the parent level sort weight. The difference between sort and left_margin is that the sort is defined by the user to sort sections within a single parent section, while the left_margin is calculated automatically and is used for sorting within the whole information block.

See Also

  • Fields of information block sections

    • Example

    <?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

$APPLICATION->SetTitle("Catalog");

if(CModule::IncludeModule("iblock"))
{
   // if $ID is not specified or is not a number, it is assumed to be 0;
   // select root sections
   $ID = IntVal($_GET['ID']);
   // select sections from the information block $BID and section $ID
   $items = GetIBlockSectionList($_GET['BID'], $ID,
                                 Array("sort"=>"asc"), 10);
   while($arItem = $items->GetNext())
   {
      echo '<a href="catalog.php?BID='.urlencode($_GET['BID']).
           '&ID='.$arItem['ID'].'">'.$arItem["NAME"].'</a><br>';
      echo $arItem["DESCRIPTION"]."<br>";
   }
}
else
   ShowError("The module is not installed");

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
?>


Functions - Bitrix Site Manager - Content Management & Portal Solutions

Functions

This sections contains functions that can be used to display forms and results of polls in the public section.

Function | Description
ShowCurrentVote | Emits the HTML code of the current poll of the specified channel.
ShowCurrentVoteResults | Emits the HTML code of the diagram displaying results of the current poll of the specified channel.
ShowPrevVoteResults | Emits the HTML code of the diagram displaying results of the previous poll of the specified channel.
ShowVote | Emits the HTML code of the poll form.
ShowVoteResults | Emits the HTML code of the diagram displaying results of the specified poll.
GetAnyAccessibleVote | Returns the ID of a poll, vote or survey in which the current user did not take part yet.
GetCurrentVote | Returns the ID of the current vote in the channel.
GetPrevVote | Returns the ID of the previous poll in the channel.
GetVoteDataByID | Returns information describing the poll by its ID.
GetVoteList | Returns a selection of polls from the database.
IsUserVoted | Determines if a user had already took part in the poll and is not permitted to vote again or not.


GetAnyAccessibleVote - Bitrix Site Manager - Content Management & Portal Solutions

GetAnyAccessibleVote

GetAnyAccessibleVote([lid])

The function returns the ID of a poll, vote or survey in which the current user did not take part yet. The function respects the user permissions; the current user must be granted the permission to vote (>=2).

Parameters

Parameter | Description
lid | Site of a vote channel.

Example

File vote_any.php that can be used in the public section of the site.

<?
require_once(
    $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
// Display a form with the first poll that a user did not take part in yet.
// If a user did, redirect to a page with the results of this poll
if (CModule::IncludeModule("vote") && $VOTING_OK=="Y")
{
    $VOTE_DIR = COption::GetOptionString("vote", "VOTE_DIR", "");
    $z = CLang::GetByID(LANG);
    $zr = $z->Fetch();
    $LANG_DIR = $zr["DIR"];
    $LANG_DIR = TrimExAll($LANG_DIR,"/");
    $VOTE_DIR = TrimExAll($VOTE_DIR,"/");
    LocalRedirect
      ("/".$LANG_DIR."/".$VOTE_DIR."/vote_result.php?VOTE_ID=". $PUBLIC_VOTE_ID."&VOTING_OK=".$VOTING_OK);
}

if (strlen($APPLICATION->GetTitle())<=0)
    $APPLICATION->SetTitle(GetMessage("VOTE_VOTING_TITLE"));

require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?><?
if (CModule::IncludeModule("vote"))
{
    $VID = GetAnyAccessibleVote();
    ShowVote($VID);
}
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetCurrentVote - Bitrix Site Manager - Content Management & Portal Solutions

GetCurrentVote

GetCurrentVote(
 GROUP_SYMBOLIC_NAME, [
 lid, [
 access]]
)

The function returns the ID of the current vote in the channel.

Parameters

Parameter | Description
GROUP_SYMBOLIC_NAME | Symbolic name of the channel.
lid | Site ID. By default, the current site ID is used.
access Minimum allowed permission of the current user to access a vote. The following values allowed:
  • 0 - access denied;
  • 1 - view results;
  • 2 - vote.
The default value is 1. This means that the function GetCurrentVote returns the ID of the current vote if only the current user is allowed to view the poll results.

  • Example

    The following example displays a form with the current vote of the specified channel.

    <?
function ShowCurrentVote($GROUP_SYMBOLIC_NAME, $lid=LANG)
{
    $CURRENT_VOTE_ID = GetCurrentVote($GROUP_SYMBOLIC_NAME, $lid, 2);
    if (intval($CURRENT_VOTE_ID)>0)
        ShowVote($CURRENT_VOTE_ID);
}
?>


GetPrevVote - Bitrix Site Manager - Content Management & Portal Solutions

GetPrevVote

GetPrevVote(
 GROUP_SYMBOLIC_NAME, [
 level, [
 lid]]
);

The function returns the ID of the previous poll in the channel.

Parameters

Parameter | Description
GROUP_SYMBOLIC_NAME | Symbolic name of the channel.
level | Level of the poll for which the ID is to be returned (1 - previous, 2 - poll before previous etc.). The default value is 1.
lid | Site ID. By default, the current site ID is used.

Example

The following example displays the diagram of results of the previous poll.

<?
function ShowPrevVoteResults($GROUP_SYMBOLIC_NAME, $level=1, $lid=LANG)
{
    $PREV_VOTE_ID = GetPrevVote($GROUP_SYMBOLIC_NAME, $level, $lid);
    if (intval($PREV_VOTE_ID) > 0)
        ShowVoteResults($PREV_VOTE_ID);
}
?>


GetVoteDataByID - Bitrix Site Manager - Content Management & Portal Solutions

GetVoteDataByID

GetVoteDataByID(
  int VOTE_ID,
  array &arChannel,
  array &arVote,
  array &arQuestions,
  array &arAnswers,
  array &arDropDown,
  array &arMultiSelect,
  array &arGroupAnswers,
  string getGroupAnswers
)

The function returns information describing the poll by its ID.

Parameters

Parameter | Description
VOTE_ID | Vote (poll) ID.
arChannel Array describing the channel of the poll. The array has the following keys.
  • ID - channel ID;
  • SYMBOLIC_NAME - symbolic name;
  • ACTIVE - active state flag ["Y"|"N"];
  • TITLE - name of the channel;
  • LID - site ID;
  • C_SORT - sort weight;
  • TIMESTAMP_X - modification date of the channel.
arVote Array describing the specified poll. The array has the following keys.
  • ID - poll ID;
  • CHANNEL_ID - poll channel ID;
  • C_SORT - sort weight;
  • ACTIVE - active state flag ["Y"|"N"];
  • TIMESTAMP_X - modification date of the poll;
  • DATE_START - starting date of the poll;
  • DATE_END - end date of the poll;
  • COUNTER - number of votings made in this poll;
  • TITLE - name of the poll;
  • DESCRIPTION - poll description;
  • DESCRIPTION_TYPE - type of poll description ["html"|"text"]
  • IMAGE_ID - image ID;
  • EVENT1 - event type identifier "event1";
  • EVENT2 - event type identifier "event2";
  • EVENT3 - auxiliary event type identifier "event3";
  • UNIQUE_TYPE - voter uniqueness: 0 - unrestricted; 1 - single voting within a session; 2 - single voting within a session or with a known cookie; 3 - single voting within a session or with a known cookie or from an IP address;
  • KEEP_IP_SEC - number of seconds during which a visitor is disallowed to vote again from the same IP address;
  • TEMPLATE - template used to display the poll form;
  • RESULT_TEMPLATE - template used to display the poll results;
  • QUESTIONS - number of questions;
  • LAMP - flag: "red" means the poll is inactive or outdated; "green" - the poll is active and its date is within the poll date bounds.
arQuestions Array of arrays each describing a single question. The arrays has the following keys.
  • ID - question ID;
  • ACTIVE - active state flag ["Y"|"N"];
  • C_SORT - sort weight;
  • QUESTION - text of the question;
  • QUESTION_TYPE - type of the text ["html"|"text"]
  • IMAGE_ID - image ID;
  • DIAGRAM - denotes the question is to be included in the results diagram ["Y"|"N"];
  • TEMPLATE - template used to display the question result;
  • TIMESTAMP_X - modification date.
arAnswers Arrays of answers. Each key of the array is a question ID. Each value is a list of arrays each describing a single answer. Each array has the following keys.
  • ID - answer ID;
  • ACTIVE - active state flag ["Y"|"N"]
  • TIMESTAMP_X - modification date;
  • QUESTION_ID - question ID;
  • C_SORT - sort weight;
  • MESSAGE - text displayed both beside the answer control in the poll form and in the diagram;
  • COUNTER - counts how many times this answer has been selected;
  • FIELD_TYPE - control type: 0 - radio, 1 - checkbox, 2 - dropdown list; 3 - multiselect list, 4 - text; 5 - textarea;
  • FIELD_WIDTH - control width;
  • FIELD_HEIGHT - control height;
  • FIELD_PARAM - additional control attributes (style, class);
  • COLOR - color of the diagram element (e.g. #FFOOCC).
arDropDown Array describing all controls of the type "2" (drop-down list). Keys are the question ID's. Values are arrays with the following keys:
  • REFERENCE - option text;
  • REFERENCE_ID - option ID.
arMultiSelect Array describing all controls of the type "3" (multiselect list). Keys are the question ID's. Values are arrays with the following keys:
  • REFERENCE - option text;
  • REFERENCE_ID - option ID.
arGroupAnswers Array describing variants of answer of all controls of the type "4" (text) and "5" (textarea). Keys are the question ID's. Values are arrays with the following keys:
  • MESSAGE - answer text;
  • COUNTER - number of answers.
getGroupAnswers | Specifies whether the array arGroupAnswers is to be returned. If set to "Y", the function GetVoteDataByID returns this array. If "N", this array is not returned.

Return Values

The function GetVoteDataByID returns the string with the poll ID. If the passed poll ID is correct, the ID value is non-zero.

Example

The following example displays a form with the required poll according to the user permissions.

<?
function ShowVote($VOTE_ID, $template1="")
{
    global $MESS, $VOTING_LAMP, $VOTING_OK, $USER_ALREADY_VOTE;
    global $USER_GROUP_PERMISSION, $VOTE_USER_ID, $VOTE_PERMISSION;
    $VOTE_ID = GetVoteDataByID($VOTE_ID,
                               $arChannel, $arVote, $arQuestions,
                               $arAnswers, $arDropDown, $arMultiSelect,
                               $arGroupAnswers, "N");
    if (intval($VOTE_ID)>0)
    {
        $perm = CVoteChannel::GetGroupPermission($arChannel["ID"]);
        if (intval($perm) >= 2)
        {
            $template = (strlen($arVote["TEMPLATE"])<=0) ?
                            "default.php" : $arVote["TEMPLATE"];
            $VOTE_PERMISSION = CVote::UserGroupPermission($arChannel["ID"]);
            require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/vote/include.php");
            @include_once(
                GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/lang/",
                                "/".$template));
            $path = COption::GetOptionString("vote",
                                             "VOTE_TEMPLATE_PATH",
                                             "/bitrix/php_interface/include/vote/show/");
            if (strlen($template1)>0) $template = $template1;
            @include($_SERVER["DOCUMENT_ROOT"].$path.$template);
        }
    }
}
?>

The following example obtains the poll information.

<?
$VOTE_ID = GetVoteDataByID($PUBLIC_VOTE_ID,
                           $arChannel,
                           $arVote,
                           $arQuestions,
                           $arAnswers,
                           $arDropDown,
                           $arMultiSelect,
                           $arGroupAnswers, "N",
                           $template, $res_template);
$VOTE_ID = intval($VOTE_ID);
// if the poll ID is valid...
if ($VOTE_ID>0 && $arVote["LAMP"]=="green")
{
    ...
}
?>


GetVoteList - Bitrix Site Manager - Content Management & Portal Solutions

GetVoteList

GetVoteList([
 GROUP_SYMBOLIC_NAME, [
 strSqlOrder]]
);

The function returns a selection of polls from the database.

Parameters

Parameter | Description
GROUP_SYMBOLIC_NAME | Symbolic name of the channel. If omitted, the function returns a selection of polls of all channels.
strSqlOrder | SQL string containing the sorting parameters. The default value is "ORDER BY C.C_SORT, C.ID, V.DATE_START desc".

Example

The following is the example of the file vote_list.php used in the public section.

<?
// Display a list of polls (archive)
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("vote"))
    require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/vote/include.php");
if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle(GetMessage("VOTE_LIST_TITLE"));
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?><?
if (CModule::IncludeModule("vote"))
{
    $votes = GetVoteList(); // list of polls
    // a display template
    require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/include/vote/list/default.php");
}
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


IsUserVoted - Bitrix Site Manager - Content Management & Portal Solutions

IsUserVoted

IsUserVoted (VOTE_ID)

The function returns true if a user had already took part in the poll and is not permitted to vote again or false otherwise.

Parameters

Parameter | Description
VOTE_ID | Poll ID.

Example

The following is the example of the file vote_now.php used in the public section.

<?
// Display a form with the current poll of a channel if a user did not vote yet.
// If a user did, redirect to a page with the results of the current poll
require_once(
    $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("vote"))
{
    $VID = GetCurrentVote("SURVEY");
    if ($VOTING_OK=="Y" || IsUserVoted($VID))
        $ALREADY_VOTED = "Y";
    else
        $ALREADY_VOTED = "N";
}

if (strlen($APPLICATION->GetTitle())<=0)
    $APPLICATION->SetTitle(GetMessage("VOTE_VOTING_TITLE"));

require_once(
    $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?><?
if (CModule::IncludeModule("vote"))
{
    if ($ALREADY_VOTED == "Y")
        ShowVoteResults($VID); else ShowVote($VID);
}
require_once(
    $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


ShowCurrentVote - Bitrix Site Manager - Content Management & Portal Solutions

ShowCurrentVote

ShowCurrentVote(
 GROUP_SYMBOLIC_NAME, [
 lid]
);

The function emits the HTML code of the current poll of the specified channel.

Parameters

Parameter | Description
GROUP_SYMBOLIC_NAME | Symbolic name of the channel.
lid | Site ID. By default, the current site ID is used.

Example

The following is the example of the file vote_current.php used in the public section.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
// Display a form with the current poll of the channel.
// Then redirect to a page with the results of the poll
if (CModule::IncludeModule("vote") && $VOTING_OK=="Y")
{
    $VOTE_DIR = COption::GetOptionString("vote", "VOTE_DIR", "");
    $z = CLang::GetByID(LANG);
    $zr = $z->Fetch();
    $LANG_DIR = $zr["DIR"];
    $LANG_DIR = TrimExAll($LANG_DIR,"/");
    $VOTE_DIR = TrimExAll($VOTE_DIR,"/");
    LocalRedirect(
        "/".$LANG_DIR."/".$VOTE_DIR."/vote_result.php?VOTE_ID=".$PUBLIC_VOTE_ID."&VOTING_OK=Y");
}
if (strlen($APPLICATION->GetTitle())<=0)
    $APPLICATION->SetTitle(GetMessage("VOTE_VOTING_TITLE"));
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?><?
if (CModule::IncludeModule("vote")) ShowCurrentVote("ANKETA");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


ShowCurrentVoteResults - Bitrix Site Manager - Content Management & Portal Solutions

ShowCurrentVoteResults

ShowCurrentVoteResults (
 GROUP_SYMBOLIC_NAME, [
 lid]
);

The function emits the HTML code of the diagram displaying results of the current poll of the specified channel.

Parameters

Parameter | Description
GROUP_SYMBOLIC_NAME | Symbolic name of the channel.
lid | Site ID. By default, the current site ID is used.


ShowPrevVoteResults - Bitrix Site Manager - Content Management & Portal Solutions

ShowPrevVoteResults

ShowPrevVoteResults (
 GROUP_SYMBOLIC_NAME, [
 level, [
 lid]]
);

The function emits the HTML code of the diagram displaying results of the previous poll of the specified channel.

Parameters

Parameter | Description
GROUP_SYMBOLIC_NAME | Symbolic name of the channel.
level | Level of the poll for which the diagram is to be displayed (1 - previous, 2 - poll before previous etc.). The default value is 1.
lid | Site ID. By default, the current site ID is used.

Example

The following is the example of the file vote_prev.php used in the public section.

<?
// Display results of the previous poll of the specified group.

require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (strlen($APPLICATION->GetTitle())<=0)
    $APPLICATION->SetTitle(GetMessage("VOTE_PREV_VOTING_TITLE"));

$APPLICATION->AddChainItem(GetMessage("VOTE_VOTES_LIST"), "vote_list.php");
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?><?
if (CModule::IncludeModule("vote"))
    ShowPrevVoteResults("ANKETA");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


ShowVote - Bitrix Site Manager - Content Management & Portal Solutions

ShowVote

ShowVote(
 VOTE_ID, [
 template]
);

The function emits the HTML code of the poll form.

Parameters

Parameter | Description
VOTE_ID | Poll ID.
template | Name of the template file used to display the poll. If omitted, the template specified in the poll settings is used instead.

Example

The following is the example of the file vote.php used in the public section.

<?
// Display a poll form by its ID
require_once(
    $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("vote") && $VOTING_OK=="Y")
{
    $VOTE_DIR = COption::GetOptionString("vote", "VOTE_DIR", "");
    $z = CLang::GetByID(LANG);
    $zr = $z->Fetch();
    $LANG_DIR = $zr["DIR"];
    $LANG_DIR = TrimExAll($LANG_DIR,"/");
    $VOTE_DIR = TrimExAll($VOTE_DIR,"/");
    LocalRedirect(
        "/".$LANG_DIR."/".$VOTE_DIR."/vote_result.php?VOTE_ID=".$PUBLIC_VOTE_ID."&VOTING_OK=Y");
}

if (strlen($APPLICATION->GetTitle())<=0)
    $APPLICATION->SetTitle(GetMessage("VOTE_VOTING_TITLE"));

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?><?
if (CModule::IncludeModule("vote"))
    ShowVote($VOTE_ID);

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


ShowVoteResults - Bitrix Site Manager - Content Management & Portal Solutions

ShowVoteResults

ShowVoteResults(
 VOTE_ID, [
 template]
);

The function emits the HTML code of the diagram displaying results of the specified poll.

Parameters

Parameter | Description
VOTE_ID | Poll ID.
template | Name of the template file used to display the poll results. If omitted, the template specified in the poll settings is used instead.

Example

The following is the example of the file vote_results.php used in the public section.

<?
// Display the poll results by its ID.
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle(GetMessage("VOTE_RESULTS_TITLE"));

//$APPLICATION->AddChainItem(GetMessage("VOTE_VOTES_LIST"), "vote_list.php");

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?><?
if (CModule::IncludeModule("vote"))
    ShowVoteResults($VOTE_ID);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


CSearch

The CSearch class is used to index the site information and perform searches.

Methods

Method | Description
ChangeIndex | The method updates the information concerning the specified module in the index.
ChangePermission | The function changes permissions to access the indexed information of the specified module.
CSearch | The CSearch constructor returns index records satisfying the passed query string and parameters.
DeleteIndex | The method deletes the specified information from the index.
Index | The method indexes an information item.
ReindexModule | The method re-indexes the information on the specified module.


CSearch, constructor

CSearch::CSearch

CDBResult
CSearch(
 string strQuery [,
 string LID [,
 string MODULE_ID [,
 string ITEM_ID [,
 string PARAM1 [,
 string PARAM2]]]]]
);

The CSearch constructor returns index records satisfying the passed query string and parameters. The record returned if only if the current user has permissions to access this information.

Parameters

Parameter | Description
strQuery | Query string. Must comply the query language.
LID | Site where the search is to be performed. If set to false (default), the method affects elements in all sites.
MODULE_ID | The ID of the module index of which is to be search. If set to false (default), the method searches all index.
ITEM_ID | Code of the indexed element. Used to restrict searches to elements with this code. If set to false (default), the method searches all index.
PARAM1 | Parameter of elements which are to be searched. If set to false (default), the method searches all index.
PARAM2 | Same as PARAM1.

Return Values

Set of records; each record has the following structure:

Array(
   [ID] => Index ID
   [DATE_CHANGE] => indexed element modification date
   [MODULE_ID] => module to which the element pertains
   [ITEM_ID] => Element ID
   [LID] => Site ID
   [URL] => Path of the element, relative to the site root (HTML-safe)
   [TITLE] => Element title (HTML-safe)
   [BODY] => Element text (HTML-safe)
   [SEARCHABLE_CONTENT] => Element index (HTML-safe)
   [PARAM1] => Element parameter
   [PARAM2] => Element parameter
   [~URL] => Path of the element, relative to the site root
   [~TITLE] => element title
   [~BODY] => element text
   [~SEARCHABLE_CONTENT] => element index
   [TITLE_FORMATED] => Element title with words selected
   [BODY_FORMATED] => Element text with words selected
)

Example

Search a string in the forum of the current site.

<?
$q = "oyster or cod fillet";
$module_id = "forum"
$obSearch = new CSearch($q, LANG, $module_id);
if ($obSearch->errorno!=0):
  ?>
  <font class="text">Error in search string:</font>
  <?echo ShowError($obSearch->error);?>
  <font class="text">Fix the query and try again.</font>
  <?
else:
  while($arResult = $obSearch->GetNext())
  {
    <a href="<?echo $arResult["URL"]?>"><?echo $arResult["TITLE_FORMATED"]?></a><br>
    <?echo $arResult["BODY_FORMATED"]?><br>
    <hr size="1" color="#DFDFDF">
  }
endif;
?>


ChangeIndex

CSearch::ChangeIndex

void
ChangeIndex(
 string MODULE_ID,
 array arFields [,
 string ITEM_ID [,
 string PARAM1 [,
 string PARAM2 [,
 string LID]]]]
);

The method updates the information concerning the specified module in the index.

Parameters

Parameter | Description
MODULE_ID | The ID of the module whose index is to be updated.
arFields Array of new values for the search index. The array has the following keys:
  • "DATE_CHANGE" => element modification date;
  • "URL" => URL of an indexed element;
  • "TITLE" => element title;
  • "BODY" => text of an indexed element;
  • "SEARCHABLE_CONTENT" => index;
  • "PARAM1" => first parameter;
  • "PARAM2" => second parameter;
  • "PERMISSIONS" => array with user group ID's whose members have read permission to the index.
Unchanged entries can be omitted.
ITEM_ID | The ID of an element whose index is to be updated. If set to false (default), the method updates all elements.
PARAM1 | Parameter of an element whose index is to be updated. Used to limit the range of updated elements. If set to false (default), the method updates all elements.
PARAM2 | Same as PARAM1.
LID | Site of an indexed element. If set to false (default), the method updates elements in all sites.

Example

The example code shows how to update the index when changing the forum topic title.

<?
$new_title = "New title";
$fid = 5;    // Forum ID
$tid = 128;  // Topic ID
CSearch::ChangeIndex("forum",
                     array("TITLE" => $new_title),
                     false, $fid, $tid);
?>


ChangePermission

CSearch::ChangePermission

void
ChangePermission(
 string MODULE_ID,
 array arGroups [,
 string ITEM_ID [,
 string PARAM1 [,
 string PARAM2 [,
 string LID]]]]
);

The function changes permissions to access the indexed information of the specified module.

Parameters

Parameter | Description
MODULE_ID | The ID of the module permissions to elements of which are to be changed.
arGroups | Array with user group ID's allowed to read the indexed information.
ITEM_ID | The ID of an element permissions to which are to be changed. If set to false (default), the method changes permissions to any element.
PARAM1 | Parameter of an element permissions to which are to be changed. Used to limit the range of affected elements. If set to false (default), the method affects all elements.
PARAM2 | Same as PARAM1.
LID | Site of an element. If set to false (default), the method affects elements in all sites.

Example

Change permissions to access the indexed posts of the forum.

<?
$Forum_ID = 5;
$arGroups = CForum::GetAccessPermissions($Forum_ID);
$arGPerm = Array();
for ($i=0; $i < count($arGroups); $i++)
{
    if ($arGroups[$i][1]>="E")
    {
        $arGPerm[] = $arGroups[$i][0];
        if ($arGroups[$i][0]==2)
            break;
    }
}
CSearch::ChangePermission("forum", $arGPerm, false, $Forum_ID);
?>


DeleteIndex

CSearch::DeleteIndex

void
DeleteIndex(
 string MODULE_ID [,
 string ITEM_ID [,
 string PARAM1 [,
 string PARAM2 [,
 string LID]]]]
);

The method deletes the specified information from the index.

Parameters

Parameter | Description
MODULE_ID | The ID of the module whose index is to be deleted.
ITEM_ID | The ID of an element whose index is to be deleted. If set to false (default), the method deletes all appropriate elements.
PARAM1 | Parameter of an element whose index is to be deleted. Used to limit the range of deleted elements. If set to false (default), the method deleted all appropriate elements.
PARAM2 | Same as PARAM1.
LID | Site of an indexed element. If set to false (default), the method deletes the appropriate elements in all sites.

Example

Delete the index element after the file deletion.

<?
$path = "/en/my_files/file.php";
if (unlink($_SERVER["DOCUMENT_ROOT"].$path))
{
    if (CModule::IncludeModule("search"))
        CSearch::DeleteIndex("main", $path);
}
?>


Index

CSearch::Index

int
Index(
 string MODULE_ID,
 string ITEM_ID,
 array arFields [,
 bool bOverWrite]
);

The method indexes a single item of information (forum post, news etc). The combination (MODULE_ID, ITEM_ID) defines the indexed element.

Parameters

Parameter | Description
MODULE_ID | The ID of the module whose index is to be updated.
ITEM_ID | The ID of an indexed item.
arFields | Array with an item properties.
bOverWrite | Specifies to delete the indexed element if the element identified by pair (MODULE_ID, ITEM_ID) already exists.

Example

<?
CSearch::Index(
  "iblock",
  $ID,
  Array(
    "DATE_CHANGE"=>$arIBlockElement["DATE_CHANGE"],
    "TITLE"=>$arIBlockElement["NAME"],
    "LID"=>$arIBlockElement["LID"],
    "PERMISSION"=>$arGroups,
    "PARAM1"=>$arIBlockElement["IBLOCK_TYPE_ID"],
    "PARAM2"=>$IBLOCK_ID,
    "LID"=>$arIBlockElement["LID"],
    "PERMISSIONS"=>$arGroups,
    "URL"=>str_replace("#ID#", $arIBlockElement["ID"], $DETAIL_PAGE_URL),
    "BODY"=>$arIBlockElement["DETAIL_TEXT"]
  ),
  $bOverWrite
);
?>


ReindexModule

CSearch::ReindexModule

void
ReindexModule(
 string MODULE_ID [,
 bool bFull]
);

The method re-indexes the information on the specified module. The module can only be re-indexed if it had previously registered a handler of the OnReindex event of the Search module.

Parameters

Parameter | Description
MODULE_ID | The ID of the module whose index is to be recreated.
bFull | Specifies to perform a full re-index, all older index files deleted. Optional, false by default.

Example

<?
// register the "OnReindex" handler
RegisterModuleDependences("search", "OnReindex", "my_module", "CMyModule", "OnReindex");

// implement handler in CMyModule
function OnReindex()
{
  global $DB;
  $arResult = array();

  $strSql =
    "SELECT FT.ID, FT.TITLE, FT.MESSAGE, ".
    "  DATE_FORMAT(FT.POST_DATE, '%d.%m.%Y %H:%i:%s') as POST_DATE, FT.LID ".
    "FROM b_my_table FT ";

  $db_res = $DB->Query($strSql);
  while ($res = $db_res->Fetch())
  {
    $arResult[] = array(
      "ID" => $res["ID"],
      "LID" => $res["LID"],
      "DATE_CHANGE" => $res["POST_DATE"],
      "URL" => "/my_module/index.php?ID=".$res["ID"],
      "PERMISSIONS" => array(2),
      "TITLE" => $res["TITLE"],
      "BODY" => $res["POST_MESSAGE"]
      );
  }

  return $arResult;
}

// Force the module reindexing
CSearch::ReIndexModule("my_module");

?>


Installation

The following operations are required to install the module.
  1. Click the Install button of the statistics module on the Modules page.
  2. Provide the initial information:
    Parameter Description
    Recreate IP-to-country index Implies recreating the IP address database index.

    Note
    The IP address database contains over 60.000 records. Therefore, recreation of index will take some time. If your site is heavily loaded at the installation time, you are recommended to uncheck this option and re-index the database later using the Statistics module settings page.
    Hits counter initial value If you are integrating the statistics module into a working site with some statistics available, you can set the initial value for the hit counter. Among other things, this value will be used when displaying the statistics summary table in the public section (if you have chosen to display it).

    Note
    This option is available if the database does not contain tables of the Statistics module.
    Hosts counter initial value Same as above but specifies the initial value for the host counter.

    Note
    This option is available if the database does not contain tables of the Statistics module.
    Visitors counter initial value Same as above but specifies the initial value for the visitor counter.

    Note
    This option is available if the database does not contain tables of the Statistics module.
  3. After you click the Install button, the module tables will be created in the database and the required scripts copied.
  4. If you are connecting the module to a site that functions without the Bitrix Site Manager (e.g. when installing the Web Analytics edition), to collect the statistical information you have to include the following code to all the required files:
    • to the start of a page :

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/include_statistics_before.php");
?>
    • to the end of a page:

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/include_statistics_after.php");
?>


Terms and definitions

The below is the list of terms on which the ideology of the Statistics module is based.

List of Terms
Advertising campaigns
  • Advertising campaign
  • Advertising campaign identifiers (referer1, referer2)
  • Auxiliary AC event parameter (referer3)
  • Direct hit under advertising campaign
  • Return under advertising campaign
  • Advertising campaign traffic
  • Rate of advertising campaign visitors
  • Advertising campaign expenses
  • Advertising campaign income
  • Advertising campaign profit
  • Advertising campaign profitability
    •
    Events
  • Event
  • Event type
  • Event type identifiers (event1, event2)
  • Auxiliary event parameter (event3)
  • Special event parameter
  • CSV file handler
    •
    Visitors and users
  • Visitor
  • New visitor
  • User
  • Online visitors
    •
    Session related
  • UserAgent
  • Session
  • Host
  • Hit
  • Stop list
  • Activity limit
  • Cookie
  • Entrance point
  • Exit point
  • Referring site (page)
  • Full path
  • Path section
    •
    Search engines
  • Search phrase
  • Search engine
  • Search engine domain
  • Search engine UserAgent
  • Search engine hit
    •
    Internet
  • Subnet mask (in stop lists)
  • Logical AND
  • IP address
  • IP address octet
  • Browser language
  • HTTP request methods
  • Favorites
  • Error 404
    •
    Advertising campaign
    The Statistics module provides a mechanism for counting visitors of the site. Each visitor thread can be identified by a number of features:
    1. Presence of the two parameters referer1, referer2 in links to your site (or their synonyms defined in the module settings). Example: http://www.bitrixsoft.com/?referer1=bsm&referer2=doc.
    2. Search engines that bring you visitors.
    3. Referring page masks.
    4. Masks of pages of your site viewed by your visitors.
    For each visitor thread, the following indices are counted separately:
    1. Sessions.
    2. Hits.
    3. Hosts.
    4. Visitors.
    5. New visitors.
    6. Visitors who added the site to the Favorites.
    7. All events initialised by visitors of this advertising campaign.
    Most of these figures may have two different indices in the advertising campaign reports:
    • for direct hits under an advertising campaign;
    • for returns under an advertising campaign.

    Note
    Advertising campaign is identified only at the time of first hit of a session.

    Advertising campaign identifiers (referer1, referer2)
    Advertising campaign (AC) identifiers are the two arbitrary strings which allow to identify the AC and print its name in the human readable form rather than a numerical ID, as well as to group different AC's in reports. These identifiers can be provided:
    • manually, in the advertising campaign editing form;
    • Automatically. If, during the first hit of the session, page parameters contain referer1 and referer2 (or their synonyms) and the option Automatically create Ad campaigns of the Statistics module settings is enabled, new AC's will be automatically created with identifiers whose values are taken from parameters referer1 and referer2.
    Auxiliary AC event parameter (referer3)
    You can define this parameter (referer3) in links to your site together with the advertising campaign identifiers. Example:

    http://www.bitrixsoft.com/?referer1=bsm&referer2=doc&referer3=xxx
    If a visitor clicks this link, they will be registered under the advertising campaign with identifier "bsm/doc" and the auxiliary parameter "xxx", which can be viewed in the Sessions report. This parameter helps personalize visits occurring under advertising campaigns.
    Direct hit under advertising campaign
    A direct hit under an advertising campaign is a session opened when a visitor is identified as the one who came under an advertising campaign. That is, if you click the link http://www.bitrix.ru/?referer1=bsm&referer2=doc and enter the site, you will have your session opened, and you will be identified as an advertising campaign visitor: r1: bsm; r2: doc. You are considered an advertising campaign direct-hit visitor as long as the session is open.
    Return under advertising campaign
    A return under an advertising campaign is a session opened for a visitor after they have paid a direct hit visit under this advertising campaign. In other words, if you, after a direct visit under the specific advertising campaign, have never entered or identified under other advertising campaigns, all your subsequent visits will be registered as returns under the initial advertising campaign.
    Advertising campaign traffic
    This term is an aggregate of the following statistical parameters:
    1. Sessions.
    2. Hits.
    3. Hosts.
    4. Visitors.
    5. New visitors.
    6. Visitors who added the site to the Favorites.
    7. All events initialed by visitors of this advertising campaign.
    Rate of advertising campaign visitors
    Average hits per session. This figure is calculated individually for both direct-hit and return sessions.
    Advertising campaign expenses
    Amount of money spent for an advertising campaign. This value can be set in the advertising campaign settings.
    Advertising campaign income
    Amount of money which is the result of hits made by visitors under the advertising campaign.
    Advertising campaign profit
    Difference between income and expenses of the advertising campaign.
    Advertising campaign profitability
    Ratio of profit to expenses.
    Event
    An event is any action occurring within the site or outside of it. The Statistics module allows to collect information only on those events whose processing have been primarily programmed by the site developer (on how to register events, see the information on the class CStatEvent methods). Examples of events are: file download, exit to an external payment system, order payment, order cancellation, banner click, exit to any other site, navigating to a page of your site.
    Event type
    Each registered event has its own type. The event type is an aggregate of the following notions:
    • event type identifiers (event1, event2);
    • name;
    • description;
    • sort index;
    • storage time of events of this type;
    • storage time of the dynamics of events of this type on daily basis;
    • additional settings.
    Event type identifiers (event1, event2)
    The event type identifiers are two arbitrary string values allowing to identify the event type in the human readable form rather than a numerical ID, as well as to group different event types in reports. These identifiers can be provided:
    • manually, in the event type editing form.
    • Automatically, when creating events using methods CStatEvent::AddByEvents, CStatEvent::AddCurrent. If no event type with the identifiers passed to these methods exists, it will be automatically created.
    Auxiliary event parameter (event3)
    This parameter can be provided when creating an event using the appropriate methods. Values of the auxiliary event parameters can be viewed in the Events report which allows to view the event details. This parameter helps personalize each single event.
    Special event parameter
    Used to identify a visitor when the latter exits to another site (e.g. to an external payment system). Later, the special parameter can be used to register events occurring outside the site (e.g. payment for merchandise). For more details, see CStatEvent::Add and Creating Events. Value of this parameter is a string containing:
    • the portal short identifier (from the Statistics module settings);
    • the session ID;
    • the visitor ID;;
    • the two character country identifier;
    • the advertising campaign ID;
    • the flag indicating the direct hit or return under an advertising campaign;
    • the two character site identifier.
    Depending on the value of the parameter Encode additional parameter #EVENT_GID# for events (the Statistics module settings), the special parameter may have either the human readable or encoded form.
    CSV file handler
    Special PHP script serving to convert reports obtained from a payment system in any custom CSV format, to the standard CSV format accepted by the Statistics module for loading events. The standard CSV format allowed by the Statistics module contains:
    • the event type ID;
    • auxiliary event parameter;
    • date and time the event was generated;
    • special event parameter;
    • amount of money;
    • sign of the amount: "Y" - for positive values; "N" - for negative values.
    Visitor
    A visitor is the unique numerical identifier issued to a browser and stored in cookie (small files kept by browsers locally to store information given by web servers). If a browser (or any other software) does not support cookies (persistent and/or session), the system uses special mechanism to identify visitors, which is based on hash (MD5) calculated on the environment variables including IP address, browser settings, provider settings and other parameters uniquely identifying the visitor at the moment of entering the site.

    In other words, visitor is a browser (or any other software) that entered the site.

    The Statistics module uses different levels of visitor uniqueness. The Statistics menu offers unique visitors per day, as well as unique visitors for the whole period of keeping the statistics (from the moment of the module installation).

    Advertising campaigns (as well as hosts) preserves the visitor uniqueness within the advertising campaign. In both cases, new visitors are those who entered the site for the first time.
    New visitor
    A visitor from whom the unique identifier could not be acquired. Such visitors are admitted to enter the site for the first time.
    User
    Synonymic to this term are "user account", "user profile". A user is an aggregate of the following:
    • login;
    • password;
    • e-mail
    • first name;
    • last name;
    • personal information;
    • work information;
    • administrator's notes.
    At different times, A site visitor can be authorised as a different user.
    Online visitors
    Site visitors that generated at least one hit within the last N seconds. The N number can be specified in the Statistics module settings (the parameter On-line visitor interval).
    UserAgent
    A UserAgent is in fact the contents of the HTTP field UserAgent . The field is provided by the software communicating with a web server. Examples of such software are web browsers, download managers, offline browsers, search robots, etc. The software uses this field to identify itself during the communication. The contents of this field can be easily changed in many cases, many applications provide interface for doing it (for example, download manager FlashGet).

    Examples of UserAgent’s:
    • Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; NetCaptor 7.0.2 Final; .NET CLR 1.0.3705) - NetCaptor.
    • ReGet SE version 1.3.1* - ReGet.
    Session
    A session in the Bitrix Site Manager is interpreted as the PHP session. A session object is created when the visitor enters the site, and is terminated after the browser window is closed. Also, a new session is opened upon the user authorization (logging in) and is closed with the user session termination (logging out). Terms session and visit are identical. In other words, a session is a visit to the site.
    Host
    A host is the IP address of a site visitor. The Bitrix Site Manager supports various levels of uniqueness for hosts in different reports.

    The Statistics section displays the number of unique hosts (IP addresses) per day and the number of unique hosts for all the time of gathering the statistics (that is, since the module has been installed).

    Advertising campaigns consider the IP address unique within a single advertising campaign only. All visitors under an advertising campaign and their IP addresses are stored in a special table. A visitor or the corresponding IP address is unique within this table only. Most of the existing statistical systems offer the maximum deviation between the number of hosts and visitors of 10%. The Statistics module of the Bitrix Site Manager offers the unexampled deviation level of 3%.
    Hit
    A hit in the Bitrix Site Manager is interpreted as one page view. The following actions also generate a hit:
    • clicking a link and the consequent page loading;
    • page reload by pressing F5 or Ctrl+F5;
    • opening a non-existing page (producing error 404).
    Search phrase
    If a visitor typed a search phrase on a search engine, found your site in the search results and clicked on it, the visitor would navigate to your site. In this case, the visitor entered your site using the search phrase. All page views via search phrases are tracked in the Statistics module and displayed in the Search keywords report. In addition to search phrases, the system stores the referring site and page, or the address of the search engine page containing search results.
    Search engine
    A search engine is any search engine on the Internet. For example: Google, Altavista, Yahoo, etc. Any search engine has the following features:
    • own UserAgent string identifying the search engine robot;
    • group of domains (addresses of sites providing search facilities);
    • variable containing the search phrase.
    Search engine domain
    One of possibly many search engine domains. For example, the Google search engine offers many domains, to name a few:
    • www.google.com;
    • www.google.ru;
    • www.google.de, etc.
    Search engine UserAgent
    UserAgent of a special software called search bot. The search bots index your site by downloading pages and registering their contents in the search engine database. Such database records are used for searches later. Usually, each search engine has its own search bot with an individual UserAgent.
    Search engine hit
    A search engine hit is the indexing of a single page. All search engines have a set of tools for indexing resources on the Internet. The process of indexing is performed by the so-called search robots. Each robot is uniquely identified by its UserAgent. When the robot attempts to index a page on your site, it sends a request to a web server and then loads the HTML code of the page and analyses its contents. The Statistics module registers such page downloads as the search engine hits. The search robots are distinguished by their UserAgent's.
    Stop list
    A stop list is a set of records used to filter visitors. The purpose of stop list is to restrict user's access to the site resources, redirect to other pages or sites.
    Stop list record
    A set of parameters used to filter the visitor thread and apply the required action: redirect, show a message, etc.
    Subnet mask (in stop lists)
    In the TCP/IP terms, a subnet mask (or net mask) is a bit mask (set of flags) that specifies which bits of the IP address specify a particular IP network or a host within a subnetwork. For example, an IP address of 12.34.56.78 with a subnet mask of 255.255.0.0 specifies net 12.34.0.0.

    To extract the network ID (network address) from an arbitrary IP address using an arbitrary subnet mask, IP uses a mathematical operation called a logical AND comparison:

    IP address:   00001100 00100010 00111000 1001110 (012.034.056.078)
Subnet mask:  11111111 11111111 11100000 0000000 (255.255.224.000)
------------------------------------------------------------------
Network ID:   00001100 00100010 00100000 0000000 (012.034.032.000)

    A stop list record contains two records: network IP and subnet mask. A visitor is considered to match a stop list record if, having the subnet mask (of a stop list record) applied to their IP address, we get the network IP (of a stop list record).

    Example 1. Deny access to all visitors from IP of 206.191.49.66.

    1. Specify the following:
      • network IP = 206.191.49.66
      • subnet mask = 255.255.255.255
    2. When a visitor with IP of 206.191.49.66 enters the site, the following operation occurs:
      Visitor IP address: 11010001 10111111 11000001 1000010 (206.191.049.066)
Subnet mask:        11111111 11111111 11111111 1111111 (255.255.225.255)
------------------------------------------------------------------------
Result:             11010001 10111111 11000001 1000010 (206.191.049.066)
      If the result matches the network IP (of a stop list record), the visitor is found in the stop list. Thus, all visitors from 206.191.49.66 will match the stop list record.

    Example 2. Deny access to all visitors from subnet of 206.191.49.xxx (IP in the range from 206.191.49.1 to 206.191.49.255)

    1. specify:
      • network IP = 206.191.49.0
      • subnet mask = 255.255.255.0
    2. When a visitor with IP of 206.191.49.76 enters the site, the following operation occurs:
      Visitor IP address: 11010001 10111111 11000001 1001100 (206.191.049.076)
Subnet mask:        11111111 11111111 11111111 0000000 (255.255.225.000)
------------------------------------------------------------------------
Result:             11010001 10111111 11000001 0000000 (206.191.049.000)
      The result matches the network IP (of a stop list record), and consequently, the visitor is found in the stop list. Thus, all visitors with IP's from 206.191.49.1 to 206.191.49.255 will not be allowed to access the server.
    Logical AND
    The result of this operation behaves as follows:

    Operand 1:  0 1 1 0
Operand 2:  1 0 1 0
-------------------
Result:     0 0 1 0
    Referring site (page)
    A referring page or referring site is the URL of the previous webpage from which a link was followed; that is, any web resource having links to your site. If a visitor enters your site using the link on such a page, the referring site and page address are registered in the Statistics module as referring.
    Full path
    The site full path is one or more pages that a visitor opened consequently by clicking links on these pages. If a visitor opens more than one page from a source page (i.e. in a new browser window), the path may fork thus forming many different paths.
    Path section
    The Statistics module defines a path section as a set of pages consisting of the first page of the path and an arbitrary number of the subsequent pages.

    For example, if you open a page page1, then click a link to page2, and from the latter - to page3. This make a path consisting of the three segments:

    • page1
    • page1 –> page2
    • page1 -> page2 -> page3
    If, from the page3, you click a link to a page4 ("Shift" + left click in the Internet Explorer), and then open a page5 in the similar manner, you will form 2 paths, each consisting of the 4 segments, the first 3 of which are identical.
    IP address

    Every machine that is on a network (a local network, or the Internet) has a unique IP number - four sets of numbers divided by period with up to three numbers in each set. In other words, the IP address is an identifier of a single network connection.

    An IP address consists of 32 bits (IPv4) or 256 bits (IPv6). Rather than working with 32 bits at a time, it is a common practice to segment the 32 bits of an IP address into four 8-bit fields called octets. Each octet is converted to a decimal number in the range 0-255 and separated by a dot. This format is called dotted decimal notation. For example: decimal 128.10.2.30 for 10000000 00001010 00000010 00011110.

    The IP addresses form the basic type of addressing used to identify each sender or receiver of information that is sent in packet across the Internet. On the server side, the IP addresses are assigned by system administrators, and automatically (or by users) on client side.

    Each country has a definite range of IP addresses assigned. This allows to determine the visitor's country by the IP address.

    IP address octet
    Part of an IP address, in the range 0-255.
    Browser language

    Many browsers has an option to set languages in which a user would like to see pages. For example, the Internet Explorer offers this option in the menu:

    "Tools" -> "Internet Options..." -> "General" tab -> click "Languages"

    Error 404
    The 404 error message is an HTTP standard response code indicating that the client was able to communicate with the server, but the server either could not find the file that was requested, or was unwilling to fulfill the request for it and did not wish to reveal the reason why.

    You can customize the way this error is handled. For example, with Apache, you have to create a file .htaccess at the site root (or in the catalog where the requested page is located) with the following directive:

    ErrorDocument 404 /404_handler.php
    In this case, when a 404 error occurs, the server will execute the script /404_handler.php, which allows to handle the situation.

    To register the 404 errors with the Statistics module, initialise the constant ERROR_404 with "Y" before the page epilogue:

    define("ERROR_404", "Y");
    HTTP request methods
    There are several HTTP request methods: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT. Most commonly used are: GET, POST, HEAD.
    • GET

      Information transfered using the GET method is appended onto the end of the action URI being requested. The most common method used today. Example:

      http://www.mysite.com/script.php?site_id=en&date1=2

      Variables and values are passed in pairs "variable=value" separated with "&". Each value must come URL ecoded.

    • POST

      The data to transfer is included in the body of the request.

    • HEAD

      Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.

    Cookie
    A cookie is a small piece of data which is sent from a web server to a web browser and stored locally on the user's machine. Commonly used to check the user's identify; store the time of last visit, preferences, the shopping cart ID etc.
    Entrance point
    The entrance point is the first hit (page viewed) in the session.
    Exit point
    The entrance point is the last hit (page viewed) in the session.
    Activity limit

    In the Statistics module settings, you can specify the activity limit. Exceeding the limit means a visitor exceeded the maximum number of hits for the certain period of time. If this is the case, the HTTP status "503 Service Unavailable" is set back to a visitor. Such an effect can be achieved by including the file /bitrix/activity_limit.php.

    This function is generally used to lower the site load generated by search robots, offline browsers etc. If a search bot receives the 503 status, it reduces the site indexing frequency. You can disable activity limit checks for a search engine in its settings. The activity limit can play a part to repulse ddos attacks, but this is not a remedy since server resources are used to control the activity limit.

    Favorites
    Favorites is a folder in Internet Explorer and other browsers used to store shortcuts of web sites you wish to return to. When creating an entry in the Favorites, a client's browser send a request for the file /favicon.ico containing an image to be associated with the URL. This feature enables to register such events in the Statistics module.

    There is a weak point in this technology. Many browsers (Firefox, NetCaptor, MyIE) request the favorite icon irrespective of the user's wish to add the site to the Favorites. This does not apply to Internet Explorer. Since most users run Internet Explorer, the mistake is insignificant.


Environment variables

The Statistics module implements the following session variables.
Variable | Description
$_SESSION["SESS_SESSION_ID"] | Session ID.
$_SESSION["SESS_GUEST_ID"] | Visitor ID.
$_SESSION["SESS_GUEST_NEW"] | "Y" - first time visit; "N" otherwise.
$_SESSION["SESS_COUNTRY_ID"] | Double-symbol identifier of the visitor country.
$_SESSION["SESS_ADV_ID"] | ID of an advertising campaign under the direct hit.
$_SESSION["SESS_LAST_ADV_ID"] | ID of the last advertising campaign that a visitor had either made a direct hit or returned.
$_SESSION["SESS_LAST_USER_ID"] | User ID upon authorization.
$_SESSION["SESS_LAST_USER_AUTH"] | "Y" - authorized last visit; "N" - not authorized.
$_SESSION["SESS_GUEST_FAVORITES"] | "Y" - visitor added the site to Favorites; "N" - not added.
$_SESSION["FROM_SEARCHER_ID"] | ID of a referring search engine.
$_SESSION["SESS_SEARCH_PHRASE"] | Search phrase that brought a visitor to the site.
$_SESSION["SESS_SEARCHER_ID"] | ID of the search engine robot that is currently indexing the site.


Classes

Class | Description
CAdv | Used with advertising campaigns.
CAutoDetect | Helps search for unknown UserAgent's.
CCountry | Used to obtain information on the traffic on country basis.
CGuest | Used to obtain information on the site visitors.
CHit | Serves to obtain information on visitor hits.
CPage | Helps obtain information on visits and attendance of the site pages.
CPath | Helps obtain information on site paths.
CPhrase | Used to obtain information on search phrases.
CReferer | Used to obtain information on referred sites.
CSearcher | Used with search engines.
CSearcherHit | Used to obtain information on hits of search engine (indexed pages).
CSession | Helps obtain information about the visitor sessions.
CStatEvent | Used to add, delete and manage events.
CStatEventType | Used with event types.
CStatistics | Contains basic methods used with the Statistic module.
CStopList | Used with the stop list.
CTraffic | Helps obtain information on the site attendance.
CUserOnline | Used to obtain information on recent visitors of the site and their sessions.


CAdv

The CAdv class is used with advertising campaigns.

Methods

Method | Description
Delete | Deletes an advertising campaign.
GetByID | Returns settings of an advertising campaign.
GetDropdownList | Returns the list of advertising campaigns for using with the drop-down lists (SelectBox function), or with the multiple selection lists (SelectBoxM function).
GetDynamicList | Returns information about the advertising campaign traffic on daily basis.
GetEventList | Returns the list of the event types initialised by visitors who entered the site on a specific advertising campaign.
GetList | Returns the list of advertising campaigns containing the calculated statistical figures and all the information about traffic.
GetSimpleList | Returns a brief list of advertising campaigns.
Reset | Clears statistical information on an advertising campaign.

See Also

  • About advertising campaigns
  • The advertising campaigns report


Delete

CAdv::Delete

bool
CAdv::Delete(
 int adv_id
)

The method Delete deletes an advertising campaign.

Parameters

Parameter | Description
adv_id | The ID of the advertising campaign to be deleted.

See Also

  • About advertising campaigns
  • CAdv::Reset

Example

<?
$adv_id = 1;
if (CAdv::Delete($adv_id))
    echo "Advertising campaign #".$adv_id." has been deleted.";
?>


GetByID

CAdv::GetByID

CDBResult
CAdv::GetByID(
 int adv_id
)

The method GetByID returns settings of an advertising campaign.

Parameters

Parameter | Description
adv_id | The ID of the advertising campaign whose parameters are to be returned.

Structure of the returned record

Array
(
    [ID] => ID
    [REFERER1] => the ID of referer1
    [REFERER2] => the ID of referer2
    [DATE_FIRST] => date of the first direct hit
    [DATE_LAST] => date of the late direct hit or return
    [COST] => expenses
    [REVENUE] => profit
    [DESCRIPTION] => description
    [PRIORITY] => priority
    [EVENTS_VIEW] => event list display modes, possible values:
        link - as a link to the list
        list - as a list
        event1 - grouped by event1
        event2 - grouped by event2
    [GUESTS] => total number of the direct hit visitors
    [NEW_GUESTS] => total number of the new direct hit visitors
    [FAVORITES] => total number of the direct hit visitors who added the site to Favorites
    [C_HOSTS] => total number of the direct hit hosts
    [SESSIONS] => total number of the direct hit sessions
    [HITS] => total number of the direct hits
    [GUESTS_BACK] => total number of the returned visitors
    [FAVORITES_BACK] => total number of the returned visitors who added the site to Favorites
    [HOSTS_BACK] => total number of the hosts on return
    [SESSIONS_BACK] => total number of the sessions on return
    [HITS_BACK] => total number of the hits on return
)

See Also

  • About advertising campaigns

Example

<?
$adv_id = 1;
if ($rs = CAdv::GetByID($adv_id))
{
    $ar = $rs->Fetch();
    // print the advertising campaign settings
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetDropdownList

CAdv::GetDropdownList

CDBResult
CAdv::GetDropdownList(
 string order = "ORDER BY REFERER1, REFERER2"
)

The method GetDropdownList returns the list of advertising campaigns (AC) for using with the drop-down lists (SelectBox function), or with the multiple selection lists (SelectBoxM function).

Parameters

Parameter | Description
order | The SQL code that can be used to set arbitrary sorting of the advertising campaigns list.

Structure of the returned record

Array
(
    [REFERENCE_ID] => ID of AC
    [REFERENCE] => [ID of AC] referer1 / referer2
)

See Also

  • About advertising campaigns
  • CAdv::GetList
  • CAdv::GetSimpleList
  • SelectBox
  • SelectBoxM

Example

<?
// single selection drop-down list
echo SelectBox("ADV_ID", CAdv::GetDropdownList(), "", intval($ADV_ID));

// multiple selection list box with 20 visible items
echo SelectBoxM("arADV_ID[]", CAdv::GetDropdownList(), $arADV_ID, "", false, 20);
?>


GetDynamicList

CAdv::GetDynamicList

CDBResult
CAdv::GetDynamicList(
 int adv_id,
 string &by = "s_date",
 string &order = "desc",
 array &max_min,
 array filter = array()
)

The method GetDynamicList returns information about the advertising campaign traffic on daily basis.

Parameters

Parameter | Description
adv_id | The ID of the advertising campaign whose parameters are to be returned.
by Sorting field. Possible values:
  • s_date - date.
order Sort order. Possible values:
  • asc - ascending;
  • desc - descending.
max_min Reference to an array containing minimum and maximum dates of the returned list. The array has the following structure:
Array
(
    [DATE_FIRST] => minimum date
    [MIN_DAY] => day of the minimum date (1-31)
    [MIN_MONTH] => month of the minimum date (1-12)
    [MIN_YEAR] => year of the minimum date

    [DATE_LAST] => maximum date
    [MAX_DAY] => day of the maximum date (1-31)
    [MAX_MONTH] => month of the maximum date (1-12)
    [MAX_YEAR] => year of the maximum date
)
filter Array used to filter the resulting list. The following keys are possible in this array:
  • DATE_1 - date "from";
  • DATE_2 - date "till".

Structure of the returned record

Array
(
    [DATE_STAT] => date
    [DAY] => day (1-31)
    [MONTH] => month (1-12)
    [YEAR] => year
    [GUESTS] => number of the direct hit visitors
    [NEW_GUESTS] => number of the new direct hit visitors
    [FAVORITES] => number of the direct hit visitors who added the site to Favorites
    [C_HOSTS] => number of the direct hit hosts
    [SESSIONS] => number of the direct hit sessions
    [HITS] => number of the direct hits
    [GUESTS_BACK] => number of the returned visitors
    [FAVORITES_BACK] => number of the returned visitors who added the site to Favorites
    [HOSTS_BACK] => number of the hosts on return
    [SESSIONS_BACK] => number of the sessions on return
    [HITS_BACK] => number of the hits on return
)

See Also

  • About advertising campaigns

Example

<?
$adv_id = 1;

// set the filter to match the December of 2005
$arFilter = array(
    "DATE1" => "01.12.2005",
    "DATE2" => "31.12.2005"
    );

// obtain the set of records
$rs = CAdv::GetDynamicList(
    $adv_id,
    ($by="s_date"),
    ($order="desc"),
    $arMaxMin,
    $arFilter,
    $is_filtered
    );

// print the array containing minimum and maximum dates
echo "<pre>"; print_r($arMaxMin); echo "</pre>";

// print all the records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetEventList

CAdv::GetEventList

CDBResult
CAdv::GetEventList(
 int adv_id,
 string &by = "s_counter",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetEventList returns the list of the event types initialised by visitors who entered the site on a specific advertising campaign (AC).

Parameters

Parameter | Description
adv_id | The ID of the advertising campaign whose parameters are to be returned.
by Sorting field. Possible values:
  • s_id - the ID of the event type;
  • s_event1 - the event1 identifier of the event type;
  • s_event2 - the event2 identifier of the event type;
  • s_sort - the event type sort index;
  • s_name - the name of the event type;
  • s_counter - the number of events initialised by the direct hit visitors who entered the site on the adv_id advertising campaign;
  • s_counter_back - the number of events initialised by the returned visitors who entered the site on the adv_id advertising campaign;
  • s_def - default sorting (to be printed in the appropriate table).
order Sort order. Possible values:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys are possible in this array:
  • ID* - the ID of the event type;
  • ID_EXACT_MATCH - if set to "N", the ID can be an entry in the identifier string (loose match);
  • EVENT1* - the event1 identifier of the event type;
  • EVENT1_EXACT_MATCH - if set to "Y", the EVENT1 must match exactly;
  • EVENT2* - the event2 identifier of the event type;
  • EVENT2_EXACT_MATCH - if set to "Y", the EVENT2 must match exactly;
  • KEYWORDS* - name and description of the event type;
  • KEYWORDS_EXACT_MATCH - if set to "Y", the KEYWORDS must match exactly;
  • DATE1_PERIOD - starting date of the period;
  • DATE2_PERIOD - ending date of the period;
  • COUNTER_PERIOD_1 - if either DATE1_PERIOD or DATE2_PERIOD is set, this field may contain the minimum value of the range of quantity of events initialised by the direct hit visitors who entered the site on the adv_id advertising campaign;
  • COUNTER_PERIOD_2 - if either DATE1_PERIOD or DATE2_PERIOD is set, this field may contain the maximum value of the range of quantity of events initialised by the direct hit visitors who entered the site on the adv_id advertising campaign;
  • COUNTER_BACK_PERIOD_1 - if either DATE1_PERIOD or DATE2_PERIOD is set, this field may contain the minimum value of the range of quantity of events initialised by the returned visitors who entered the site on the adv_id advertising campaign;
  • COUNTER_BACK_PERIOD_2 - if either DATE1_PERIOD or DATE2_PERIOD is set, this field may contain the maximum value of the range of quantity of events initialised by the returned visitors who entered the site on the adv_id advertising campaign;
  • MONEY_PERIOD_1 - if either DATE1_PERIOD or DATE2_PERIOD is set, this field may contain the minimum value of the range of amount of money initialised by the direct hit visitors who entered the site on the adv_id advertising campaign;
  • MONEY_PERIOD_2 - if either DATE1_PERIOD or DATE2_PERIOD is set, this field may contain the maximum value of the range of amount of money initialised by the direct hit visitors who entered the site on the adv_id advertising campaign.
* - complex logic is allowed
is_filtered | If this variable contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => the ID of the event type;
    [EVENT1] => the event1 identifier;
    [EVENT2] => the event2 identifier;
    [C_SORT] => sorting;
    [NAME] => name;
    [EVENT] => either the name or the ID of event1 / event2;
    [DESCRIPTION] => description;
    [COUNTER] => total number of events of this type occurred on direct hit under the AC;
    [COUNTER_BACK] => total number of events of this type occurred on return under the AC;
    [COUNTER_TODAY] => total number of events of this type occurred on direct hit under the AC for today;
    [COUNTER_YESTERDAY] => total number of events of this type occurred on direct hit under the AC for yesterday;
    [COUNTER_BEF_YESTERDAY] => total number of events of this type occurred on direct hit under the AC for the day before yesterday;
    [COUNTER_PERIOD] => total number of events of this type occurred on direct hit under the AC for the period;
    [COUNTER_BACK_TODAY] => total number of events of this type occurred on return under the AC for today;
    [COUNTER_BACK_YESTERDAY] => total number of events of this type occurred on return under the AC for yesterday;
    [COUNTER_BACK_BEF_YESTERDAY] => total number of events of this type occurred on return under the AC for the day before yesterday;
    [COUNTER_BACK_PERIOD] => total number of events of this type occurred on return under the AC for the period;
    [MONEY] => total value of events of this type occurred on direct hit under the AC;
    [MONEY_TODAY] => total value of events of this type occurred on direct hit under the AC for today;
    [MONEY_YESTERDAY] => total value of events of this type occurred on direct hit under the AC for yesterday;
    [MONEY_BEF_YESTERDAY] => total value of events of this type occurred on direct hit under the AC for the day before yesterday;
    [MONEY_PERIOD] => total value of events of this type occurred on direct hit under the AC for the period;
    [MONEY_BACK] => total value of events of this type occurred on return under the AC;
    [MONEY_BACK_TODAY] => total value of events of this type occurred on return under the AC for today;
    [MONEY_BACK_YESTERDAY] => total value of events of this type occurred on return under the AC for yesterday;
    [MONEY_BACK_BEF_YESTERDAY] => total value of events of this type occurred on return under the AC for the day before yesterday;
    [MONEY_BACK_PERIOD] => total value of events of this type occurred on return under the AC for the period.
)

See Also

  • About advertising campaigns
  • About events

Example

<?
$adv_id = 1;

// filter by event types "download / file1" and "download / file2"
// and obtain the additional information for December 2005
$arFilter = array(
    "EVENT1"       => "download",
    "EVENT2"       => "file1 | file2",
    "DATE1_PERIOD" => "01.12.2005",
    "DATE2_PERIOD" => "31.12.2005"
    );

// obtain the set of records
$rs = CAdv::GetEventList(
    $adv_id,
    ($by="s_counter"),
    ($order="desc"),
    $arFilter,
    $is_filtered
    );

// print all the records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CAdv::GetList

CDBResult
CAdv::GetList(
 string &by = "SESSIONS",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered,
 mixed limit = "",
 array &referer_group,
 string &sql
)

The method GetList returns the list of advertising campaigns (AC) containing the calculated statistical figures and all the information about traffic.

Parameters

Parameter | Description
by Sorting field. Possible values:
  • ID - the ID of the advertising campaign;
  • PRIORITY - priority;
  • REFERER1 - the referer1 identifier of the AC;
  • REFERER2 - the referer2 identifier of the AC;
  • C_TIME_FIRST - date and time when the AC started (the first direct hit);
  • C_TIME_LAST - the last direct hit or return under the AC;
  • ADV_TIME - duration of the AC (difference C_TIME_LAST - C_TIME_FIRST);
  • ATTENT - rate of attentiveness of visitors on direct hit under this AC;
  • ATTENT_BACK - rate of attentiveness of returned visitors under this AC;
  • NEW_VISITORS - ratio of visitors who first entered the site under this AC to the total number of those entered the site under this AC;
  • RETURNED_VISITORS - percent of visitors who returned to the site after the direct hit under this AC;
  • VISITORS_PER_DAY - average number of visitors per day;
  • COST - expenses for the AC;
  • REVENUE - revenue of the AC;
  • BENEFIT - profit of the AC;
  • ROI - profitability of the AC;
  • SESSION_COST - average cost of session (expenses to the number of sessions on direct hit);
  • VISITOR_COST - average cost of a visitor (expenses to the number of visitors on direct hit);
  • GUESTS - total number of direct hit visitors;
  • GUESTS_BACK - total number of returned visitors;
  • NEW_GUESTS - total number of new visitors who entered the site under this AC;
  • FAVORITES - total number of the direct hit visitors who added the site to Favorites when entered under this AC;
  • FAVORITES_BACK - total number of visitors who added the site to Favorites when returned under this AC;
  • C_HOSTS - total number of hosts on direct hit under the AC;
  • HOSTS_BACK - total number of the on-return hosts under the AC;
  • SESSIONS - total number of sessions on direct hit under the AC;
  • SESSIONS_BACK - total number of the on-return sessions under the AC;
  • HITS - total number of the direct hits under the AC;
  • HITS_BACK - total number of the on-return hits under the AC;
  • GUESTS_TODAY - number of the direct hit visitors for today;
  • GUESTS_BACK_TODAY - number of the returned visitors for today;
  • NEW_GUESTS_TODAY - number of the new visitors for today;
  • FAVORITES_TODAY - number of the direct hit visitors who added the site to Favorites for today;
  • FAVORITES_BACK_TODAY - number of the returned visitors who added the site to Favorites for today;
  • C_HOSTS_TODAY - number of the direct hit hosts for today;
  • HOSTS_BACK_TODAY - number of the on-return hosts for today;
  • SESSIONS_TODAY - number of the direct hit sessions for today;
  • SESSIONS_BACK_TODAY - number of the on-return sessions for today;
  • HITS_TODAY - number of direct hits for today;
  • HITS_BACK_TODAY - number of on-return hits for today;
  • GUESTS_YESTERDAY - number of the direct hit visitors for yesterday;
  • GUESTS_BACK_YESTERDAY - number of the returned visitors for yesterday;
  • NEW_GUESTS_YESTERDAY - number of the new visitors for yesterday;
  • FAVORITES_YESTERDAY - number of the direct hit visitors who added the site to Favorites for yesterday;
  • FAVORITES_BACK_YESTERDAY - number of the returned visitors who added the site to Favorites for yesterday;
  • C_HOSTS_YESTERDAY - number of the direct hit hosts for yesterday;
  • HOSTS_BACK_YESTERDAY - number of the on-return hosts for yesterday;
  • SESSIONS_YESTERDAY - number of the direct hit sessions for yesterday;
  • SESSIONS_BACK_YESTERDAY - number of the on-return sessions for yesterday;
  • HITS_YESTERDAY - number of direct hits for yesterday;
  • HITS_BACK_YESTERDAY - number of on-return hits for yesterday;
  • GUESTS_BEF_YESTERDAY - number of the direct hit visitors for the day before yesterday;
  • GUESTS_BACK_BEF_YESTERDAY - number of the returned visitors for the day before yesterday;
  • NEW_GUESTS_BEF_YESTERDAY - number of the new visitors for the day before yesterday;
  • FAVORITES_BEF_YESTERDAY - number of the direct hit visitors who added the site to Favorites for the day before yesterday;
  • FAVORITES_BACK_BEF_YESTERDAY - number of the returned visitors who added the site to Favorites for the day before yesterday;
  • C_HOSTS_BEF_YESTERDAY - number of the direct hit hosts for the day before yesterday;
  • HOSTS_BACK_BEF_YESTERDAY - number of the on-return hosts for the day before yesterday;
  • SESSIONS_BEF_YESTERDAY - number of the direct hit sessions for the day before yesterday;
  • SESSIONS_BACK_BEF_YESTERDAY - number of the on-return sessions for the day before yesterday;
  • HITS_BEF_YESTERDAY - number of direct hits for the day before yesterday;
  • HITS_BACK_BEF_YESTERDAY - number of on-return hits for the day before yesterday;
  • GUESTS_PERIOD - number of the direct hit visitors within the time period specified in the filter;
  • GUESTS_BACK_PERIOD - number of the returned visitors within the time period specified in the filter;
  • NEW_GUESTS_PERIOD - number of the new visitors within the time period specified in the filter;
  • FAVORITES_PERIOD - number of the direct hit visitors who added the site to Favorites within the time period specified in the filter;
  • FAVORITES_BACK_PERIOD - number of the returned visitors who added the site to Favorites within the time period specified in the filter;
  • C_HOSTS_PERIOD - number of the direct hit hosts within the time period specified in the filter;
  • HOSTS_BACK_PERIOD - number of the on-return hosts within the time period specified in the filter;
  • SESSIONS_PERIOD - number of the direct hit sessions within the time period specified in the filter;
  • SESSIONS_BACK_PERIOD - number of the on-return sessions within the time period specified in the filter;
  • HITS_PERIOD - number of direct hits within the time period specified in the filter;
  • HITS_BACK_PERIOD - number of on-return hits within the time period specified in the filter.
order Sort order. Possible values:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys are possible in this array:
  • GROUP - list of possible values:
    • referer1 - the AC list will be grouped by the referer1 identifier of the AC;
    • referer2 - the AC list will be grouped by the referer2 identifier of the AC.
  • ID* - the ID of the AC;
  • ID_EXACT_MATCH - if set to "N", the ID can be an entry in the identifier string (loose match);
  • DATE1_PERIOD - minimum value of the period for which the information is to be obtained;
  • DATE2_PERIOD - maximum value of the period for which the information is to be obtained;
  • DATE1_FIRST - first value of the range to match against the field "AC starting date";
  • DATE2_FIRST - last value of the range to match against the field "AC starting date";
  • DATE1_LAST - first value of the range to match against the field "AC ending date";
  • DATE2_LAST - last value of the range to match against the field "AC ending date";
  • REFERER1* - the referer1 identifier of the AC;
  • REFERER1_EXACT_MATCH - if set to "Y", the REFERER1 must match exactly;
  • REFERER2* - the referer2 identifier of the AC;
  • REFERER2_EXACT_MATCH - if set to "Y", the REFERER2 must match exactly;
  • PRIORITY1 - first value of the range to match against the field "AC Priority";
  • PRIORITY2 - last value of the range to match against the field "AC Priority";
  • NEW_GUESTS1 - first value of the range to match against the field "AC new visitors";
  • NEW_GUESTS2 - last value of the range to match against the field "AC new visitors";
  • GUESTS_BACK - tells by which field visitors are to be sorted:
    • N - on direct hit;
    • Y - on return.
  • GUESTS1 - first value of the range to match against the field "Direct-hit or on-return visitors" (depends on the GUESTS_BACK state flag);
  • GUESTS2 - last value of the range to match against the field "Direct-hit or on-return visitors" (depends on the GUESTS_BACK state flag);
  • FAVORITES_BACK - tells by which field visitors who added the site to Favorites are to be sorted:
    • N - on direct hit;
    • Y - on return.
  • FAVORITES1 - first value of the range to match against the field "Direct-hit or on-return visitors who added the site to Favorites" (depends on the FAVORITES_BACK state flag);
  • FAVORITES2 - last value of the range to match against the field "Direct-hit or on-return visitors who added the site to Favorites" (depends on the FAVORITES_BACK state flag);
  • HOSTS_BACK - tells how hosts are to be sorted:
    • N - on direct hit;
    • Y - on return.
  • HOSTS1 - first value of the range to match against the field "Direct-hit or on-return hosts" (depends on the HOSTS_BACK state flag);
  • HOSTS2 - last value of the range to match against the field "Direct-hit or on-return hosts" (depends on the HOSTS_BACK state flag);
  • SESSIONS_BACK - tells how sessions are to be sorted:
    • N - on direct hit;
    • Y - on return.
  • SESSIONS1 - first value of the range to match against the field "Direct-hit or on-return sessions" (depends on the SESSIONS_BACK state flag);
  • SESSIONS2 - last value of the range to match against the field "Direct-hit or on-return sessions" (depends on the SESSIONS_BACK state flag)
  • HITS_BACK - tells how hits are to be sorted:
    • N - on direct hit;
    • Y - on return.
  • HITS1 - first value of the range to match against the field "Direct or on-return hits" (depends on the HITS_BACK state flag);
  • HITS2 - last value of the range to match against the field "Direct or on-return hits" (depends on the HITS_BACK state flag);
  • COST1 - first value of the range to match against the field "AC expenses";
  • COST2 - last value of the range to match against the field "AC expenses";
  • REVENUE1 - first value of the range to match against the field "AC revenue";
  • REVENUE2 - last value of the range to match against the field "AC revenue";
  • BENEFIT1 - first value of the range to match against the field "AC profit";
  • BENEFIT2 - last value of the range to match against the field "AC profit";
  • ROI1 - first value of the range to match against the field "AC profitability";
  • ROI2 - last value of the range to match against the field "AC profitability";
  • ATTENT1 - first value of the range to match against the field "Rate of attentiveness of AC visitors";
  • ATTENT2 - last value of the range to match against the field "Rate of attentiveness of AC visitors";
  • VISITORS_PER_DAY1 - first value of the range to match against the field "Average number of visitors per day";
  • VISITORS_PER_DAY2 - last value of the range to match against the field "Average number of visitors per day";
  • DURATION1 - first value of the range to match against the field "AC duration";
  • DURATION2 - last value of the range to match against the field "AC duration";
  • CURRENCY - currency of the AC financial figures;
  • DESCRIPTION* - description of the AC;
  • DESCRIPTION_EXACT_MATCH - if set to "Y", the DESCRIPTION must match exactly.
* - complex logic is allowed
is_filtered | If this variable contains "true" on return, the resulting list is filtered.
limit | Maximum number of the AC's to return. If set to "", the number of AC's will be limited to that specified in the parameter Maximum number of records displayed in tables in the Statistics module settings.
referer_group Reference to an array initialised only if grouping by referer1 or referer2 (if filter["GROUP"]="referer1" or filter["GROUP"]="referer2"). The array has the following structure:
[referer1 or referer2] => Array
    (
        [REFERER1] => referer1 or
        [REFERER2] => referer2

        [GUESTS_TODAY] => number of the direct hit visitors for today
        [GUESTS_BACK_TODAY] => number of the returned visitors for today
        [NEW_GUESTS_TODAY] => number of the new visitors for today
        [FAVORITES_TODAY] => number of the direct hit visitors
                             who added the site to Favorites for today
        [FAVORITES_BACK_TODAY] => number of the returned visitors
                                  who added the site to Favorites for today
        [C_HOSTS_TODAY] => number of the direct hit hosts for today
        [HOSTS_BACK_TODAY] => number of the on-return hosts for today
        [SESSIONS_TODAY] => number of the direct hit sessions for today
        [SESSIONS_BACK_TODAY] => number of the on-return sessions for today
        [HITS_TODAY] => number of direct hits for today
        [HITS_BACK_TODAY] => number of on-return hits for today

        [GUESTS_YESTERDAY] => number of the direct hit visitors for yesterday
        [GUESTS_BACK_YESTERDAY] => number of the returned visitors for yesterday
        [NEW_GUESTS_YESTERDAY] => number of the new visitors for yesterday
        [FAVORITES_YESTERDAY] => number of the direct hit visitors
                                 who added the site to Favorites for yesterday
        [FAVORITES_BACK_YESTERDAY] => number of the returned visitors
                                      who added the site to Favorites for yesterday
        [C_HOSTS_YESTERDAY] => number of the direct hit hosts for yesterday
        [HOSTS_BACK_YESTERDAY] => number of the on-return hosts for yesterday
        [SESSIONS_YESTERDAY] => number of the direct hit sessions for yesterday
        [SESSIONS_BACK_YESTERDAY] => number of the on-return sessions for yesterday
        [HITS_YESTERDAY] => number of direct hits for yesterday
        [HITS_BACK_YESTERDAY] => number of on-return hits for yesterday

        [GUESTS_BEF_YESTERDAY] => number of the direct hit visitors for the day before yesterday
        [NEW_GUESTS_BEF_YESTERDAY] => number of the new visitors for the day before yesterday
        [FAVORITES_BEF_YESTERDAY] => number of the direct hit visitors
                                     who added the site to Favorites for the day before yesterday
        [C_HOSTS_BEF_YESTERDAY] => number of the direct hit hosts for the day before yesterday
        [SESSIONS_BEF_YESTERDAY] => number of the direct hit sessions for the day before yesterday
        [HITS_BEF_YESTERDAY] => number of direct hits for the day before yesterday
        [GUESTS_BACK_BEF_YESTERDAY] => number of the returned visitors for the day before yesterday
        [FAVORITES_BACK_BEF_YESTERDAY] => number of the returned visitors
                                          who added the site to Favorites for the day before yesterday
        [HOSTS_BACK_BEF_YESTERDAY] => number of the on-return hosts for the day before yesterday
        [SESSIONS_BACK_BEF_YESTERDAY] => number of the on-return sessions for the day before yesterday
        [HITS_BACK_BEF_YESTERDAY] => number of on-return hits for the day before yesterday

        [GUESTS_PERIOD] => number of the direct hit visitors for the time period
            (time period is set by initialising:
            filter["DATE1_PERIOD"] and/or filter["DATE2_PERIOD"])
        [GUESTS_BACK_PERIOD] => number of the returned visitors for the time period
        [NEW_GUESTS_PERIOD] => number of the new direct hit visitors for the time period
        [C_HOSTS_PERIOD] => number of the direct hit hosts for the time period
        [HOSTS_BACK_PERIOD] => number of the on-return hosts for the time period
        [FAVORITES_PERIOD] => number of the direct hit visitors
                              who added the site to Favorites for the time period
        [FAVORITES_BACK_PERIOD] => number of the returned visitors
                                   who added the site to Favorites for the time period
        [SESSIONS_PERIOD] => number of the direct hit sessions for the time period
        [SESSIONS_BACK_PERIOD] => number of the on-return sessions for the time period
        [HITS_PERIOD] => number of direct hits for the time period
        [HITS_BACK_PERIOD] => number of on-return hits for the time period
    )
sql | Reference to the resulting SQL query used to select advertising campaigns.

Structure of the returned record

Array
(
    [ID] => ID
    [PRIORITY] => priority
    [REFERER1] => the referer1 identifier
    [REFERER2] => the referer2 identifier
    [DESCRIPTION] => description
    [EVENTS_VIEW] => the event list display mode, possible values are:
        link - as a link to the list
        list - as a list
        event1 - grouped by event1
        event2 - grouped by event2

    [DATE_FIRST] => date and time of the first direct hit
    [DATE_LAST] => date and time of the last direct hit or return
    [ADV_TIME] => duration of the AC, in seconds

    [ATTENT] => rate of attentiveness of the direct hit visitors
    [ATTENT_BACK] => rate of attentiveness of the returned visitors
    [NEW_VISITORS] => percentage of new visitors
    [RETURNED_VISITORS] => percent of the direct hit visitors who returned to the site
    [VISITORS_PER_DAY] => average number of visitors per day

    [CURRENCY] => currency of financial figures
    [COST] => expenses
    [REVENUE] => revenue
    [BENEFIT] => profit
    [SESSION_COST] => cost of a session
    [VISITOR_COST] => cost of a visitor
    [ROI] => profitability

    [GUESTS] => total number of direct hit visitors
    [NEW_GUESTS] => total number of new direct hit visitors
    [FAVORITES] => total number of direct hit visitors who added the site to Favorites
    [C_HOSTS] => total number of direct hit hosts
    [SESSIONS] => total number of direct hit sessions
    [HITS] => total number of direct hits
    [GUESTS_BACK] => total number of returned visitors
    [FAVORITES_BACK] => total number of returned visitors who added the site to Favorites
    [HOSTS_BACK] => total number of on-return hosts
    [SESSIONS_BACK] => total number of on-return sessions
    [HITS_BACK] => total number of on-return hits

    [GUESTS_TODAY] => total number of direct hit visitors for today
    [GUESTS_BACK_TODAY] => total number of returned visitors for today
    [NEW_GUESTS_TODAY] => total number of new direct hit visitors for today
    [FAVORITES_TODAY] => total number of direct hit visitors who added the site to Favorites for today
    [FAVORITES_BACK_TODAY] => total number of returned visitors who added the site to Favorites for today
    [C_HOSTS_TODAY] => total number of direct hit hosts for today
    [HOSTS_BACK_TODAY] => total number of on-return hosts for today
    [SESSIONS_TODAY] => total number of direct hit sessions for today
    [SESSIONS_BACK_TODAY] => total number of on-return sessions for today
    [HITS_TODAY] => total number of direct hits for today
    [HITS_BACK_TODAY] => total number of on-return hits for today

    [GUESTS_YESTERDAY] => total number of direct hit visitors for yesterday
    [GUESTS_BACK_YESTERDAY] => total number of returned visitors for yesterday
    [NEW_GUESTS_YESTERDAY] => total number of new direct hit visitors for yesterday
    [FAVORITES_YESTERDAY] => total number of direct hit visitors who added the site to Favorites for yesterday
    [FAVORITES_BACK_YESTERDAY] => total number of returned visitors who added the site to Favorites for yesterday
    [C_HOSTS_YESTERDAY] => total number of direct hit hosts for yesterday
    [HOSTS_BACK_YESTERDAY] => total number of on-return hosts for yesterday
    [SESSIONS_YESTERDAY] => total number of direct hit sessions for yesterday
    [SESSIONS_BACK_YESTERDAY] => total number of on-return sessions for yesterday
    [HITS_YESTERDAY] => total number of direct hits for yesterday
    [HITS_BACK_YESTERDAY] => total number of on-return hits for yesterday

    [GUESTS_BEF_YESTERDAY] => total number of direct hit visitors for the day before yesterday
    [GUESTS_BACK_BEF_YESTERDAY] => total number of returned visitors for the day before yesterday
    [NEW_GUESTS_BEF_YESTERDAY] => total number of new direct hit visitors for the day before yesterday
    [FAVORITES_BEF_YESTERDAY] => total number of direct hit visitors who added the site to Favorites for the day before yesterday
    [FAVORITES_BACK_BEF_YESTERDAY] => total number of returned visitors who added the site to Favorites for the day before yesterday
    [C_HOSTS_BEF_YESTERDAY] => total number of direct hit hosts for the day before yesterday
    [HOSTS_BACK_BEF_YESTERDAY] => total number of on-return hosts for the day before yesterday
    [SESSIONS_BEF_YESTERDAY] => total number of direct hit sessions for the day before yesterday
    [SESSIONS_BACK_BEF_YESTERDAY] => total number of on-return sessions for the day before yesterday
    [HITS_BEF_YESTERDAY] => total number of direct hits for the day before yesterday
    [HITS_BACK_BEF_YESTERDAY] => total number of on-return hits for the day before yesterday

    [GUESTS_PERIOD] => total number of direct hit visitors for the period
    [GUESTS_BACK_PERIOD] => total number of returned visitors for the period
    [NEW_GUESTS_PERIOD] => total number of new direct hit visitors for the period
    [FAVORITES_PERIOD] => total number of direct hit visitors who added the site to Favorites
        for the period
    [FAVORITES_BACK_PERIOD] => total number of returned visitors who added the site to Favorites
        for the period
    [C_HOSTS_PERIOD] => total number of direct hit hosts for the period
    [HOSTS_BACK_PERIOD] => total number of on-return hosts for the period
    [SESSIONS_PERIOD] => total number of direct hit sessions for the period
    [SESSIONS_BACK_PERIOD] => total number of on-return sessions for the period
    [HITS_PERIOD] => total number of direct hits for the period
    [HITS_BACK_PERIOD] => total number of on-return hits for the period
)

See Also

  • About advertising campaigns
  • CAdv::GetSimpleList
  • CAdv::GetDropdownList

Example

<?
// filter by advertising campaigns whose referer1 contains "google"
// and obtain the additional information for December 2005
$arFilter = array(
    "REFERER1"     => "google",
    "DATE1_PERIOD" => "01.12.2005",
    "DATE2_PERIOD" => "31.12.2005"
    );

// obtain the set of records
$rs = CAdv::GetList(
    ($by="SESSIONS"),
    ($order="desc"),
    $arFilter,
    $is_filtered,
    "",
    $referer_group,
    $sql
    );

// print all the records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetSimpleList

CAdv::GetSimpleList

CDBResult
CAdv::GetSimpleList(
 string &by = "s_referer1",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetSimpleList returns a brief list of advertising campaigns (AC).

Parameters

Parameter | Description
by Sorting field. Possible values:
  • s_id - the ID of the AC;
  • s_referer1 - the referer1 identifier of the AC;
  • s_referer2 - the referer2 identifier of the AC;
  • s_description - the description of the AC.
order Sort order. Possible values:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys are possible in this array:
  • ID* - the ID of the AC;
  • ID_EXACT_MATCH - if set to "N", the ID can be an entry in the identifier string (loose match);
  • REFERER1* - the referer1 identifier of the AC;
  • REFERER1_EXACT_MATCH - if set to "Y", the REFERER1 must match exactly;
  • REFERER2* - the referer2 identifier of the AC;
  • REFERER2_EXACT_MATCH - if set to "Y", the REFERER2 must match exactly;
  • DESCRIPTION* - the description of the AC;
  • DESCRIPTION_EXACT_MATCH - if set to "Y", the DESCRIPTION must match exactly.
* - complex logic is allowed
is_filtered | If this variable contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => ID
    [REFERER1] => the referer1 identifier
    [REFERER2] => the referer2 identifier
    [DESCRIPTION] => description
)

See Also

  • About advertising campaigns
  • CAdv::GetList
  • CAdv::GetDropdownList

Example

<?
// select only those advertising campaigns whose referer1 contains "google"
$arFilter = array(
    "REFERER1" => "google"
    );

// obtain the set of records
$rs = CAdv::GetSimpleList(
    ($by="s_referer1"),
    ($order="desc"),
    $arFilter,
    $is_filtered
    );

// print all the records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


Reset

CAdv::Reset

bool
CAdv::Reset(
 int adv_id
)

The method Reset clears statistical information on an advertising campaign.

Parameters

Parameter | Description
adv_id | The advertising campaign ID.

See Also

  • About advertising campaigns
  • CAdv::Delete

Example

<?
$adv_id = 1;
if (CAdv::Reset($adv_id))
    echo "Information on the advertising campaign #".$adv_id." has been deleted.";
?>


CAutoDetect

The CAutoDetect class helps to search for unknown UserAgent's.

Methods

Method | Description
GetList | Returns a list of unknown UserAgent's.

See Also

  • The Autodetect report


GetList

CAutoDetect::GetList

CDBResult
CAutoDetect::GetList(
 string &by = "s_counter",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of unknown UserAgent's. The method analyses sessions, and selects all UserAgent's which cannot be related to none of the known search engines or browsers. The UserAgent's of the browsers can be specified in the Statistics module settings.

Parameters

Parameter | Description
by The field by which the sorting is to be performed. The following values are possible:
  • s_user_agent - UserAgent;
  • s_counter - number of sessions.
order Sort order. The following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • LAST - defines which sessions should be analyzed; the following values apply:
    • Y - today's sessions;
    • N - sessions of the previous days (not including today).
  • USER_AGENT* - the required UserAgent (mask or partial string);
  • USER_AGENT_EXACT_MATCH - if set to "Y", the USER_AGENT string must match exactly;
  • COUNTER1 - minimum value of the range to match against the "number of sessions" field;
  • COUNTER2 - maximum value of the range to match against the "number of sessions" field.

    * - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [USER_AGENT] => UserAgent
    [COUNTER] => number of sessions
)

See Also

  • The Autodetect report

Example

<?
// select information for today
$arFilter = array(
    "LAST" => "Y"
    );

// obtain the list
$rs = CAutoDetect::GetList(
    ($by = "s_counter"),
    ($order = "desc"),
    $arFilter = array(),
    $is_filtered
    );

// print entries
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CCountry

The CCountry class is used to obtain information on the traffic on country basis.

Methods

Method | Description
GetGraphArray | Returns data required to build the graph and the pie chart of the site attendance on country basis.
GetList | Returns a list of countries defined in the Statistics module.

See Also

  • The Countries report


GetGraphArray

CCountry::GetGraphArray

array
CCountry::GetGraphArray(
 array filter,
 array &legend
)

The method GetGraphArray returns data required to build the graph and the pie chart of the site attendance on country basis.

Parameters

Parameter Description
filter Array used to filter countries. The following keys are possible:
  • COUNTRY_ID - two-character country identifier;
  • DATE1 - minimum value of the time range;
  • DATE2 - maximum value of the time range.
legend Array containing summary figures on each country, and the line and sector colours for each country. The array has the following structure:
Array
(
    [country ID] => Array
        (
            [NAME] => name of the country
            [SESSIONS] => number of sessions within the time range
            [NEW_GUESTS] => number of new visitors within the time range
            [HITS] => number of hits within the time range
            [C_EVENTS] => number of events within the time range
            [TOTAL_SESSIONS] => total number of sessions
            [TOTAL_NEW_GUESTS] => total number of new visitors
            [TOTAL_HITS] => total number of hits
            [TOTAL_C_EVENTS] => total number of events
            [COLOR] => colour of the graph line and the pie chart sector
        )
    ...
)

Structure of the returned array

Array
(
    [date] => Array
        (
            [D] => day (1-31)
            [M] => month (1-12)
            [Y] => year
            [country ID] => Array
                (
                    [SESSIONS] => number of sessions per the country for the date
                    [NEW_GUESTS] => number of new visitors per the country for the date
                    [HITS] => number of hits per the country for the date
                    [C_EVENTS] => number of events per the country for the date
                )
            ...

        )
    ...
)

See Also

  • The Countries report

Example

<?
// filter data for UK for December 2005
$arFilter = Array(
    "COUNTRY_ID" => "uk",
    "DATE1"      => "01.12.2005",
    "DATE2"      => "31.12.2005"
    );

// obtain the array of data on daily basis
$arDays = CCountry::GetGraphArray($arFilter, $arLegend);

// print the data
while (list($date, $arr) = each($arrDays))
{
    echo "Date: ".$date."<br>";
    echo "Data: <pre>"; print_r($arr); echo "</pre>";
}
?>


GetList

CCountry::GetList

CDBResult
CCountry::GetList(
 string &by = "s_name",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of countries defined in the Statistics module. The list of countries is loaded when re-indexing the IP database in the Statistics module settings.

Parameters

Parameter | Description
by Sorting field. The following values are possible:
  • s_id - two-character country identifier;
  • s_short_name - three-character country identifier;
  • s_name - name of the country;
  • s_sessions - total number of sessions for this country;
  • s_new_guests - total number of new visitors for this country;
  • s_hits - total number of hits for this country;
  • s_events - total number of events for this country.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the output. The following keys are possible:
  • ID* - two-character country identifier;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • SHORT_NAME* - three-character country identifier;
  • SHORT_NAME_EXACT_MATCH - if "Y", SHORT_NAME's must match exactly (strict match);
  • NAME* - name of the country;
  • NAME_EXACT_MATCH - if "Y", NAME_EXACT_MATCH's must match exactly (strict match);
  • SESSIONS1 - minimum value of the range for the "number of sessions" field;
  • SESSIONS2 - maximum value of the range for the "number of sessions" field;
  • NEW_GUESTS1 - minimum value of the range for the "number of new visitors" field;
  • NEW_GUESTS2 - maximum value of the range for the "number of new visitors" field;
  • HITS1 - minimum value of the range for the "number of hits" field;
  • HITS2 - maximum value of the range for the "number of hits" field;
  • EVENTS1 - minimum value of the range for the "number of events" field;
  • EVENTS2 - maximum value of the range for the "number of events" field.

    * - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => two-character country identifier
    [SHORT_NAME] => three-character country identifier
    [NAME] => name of the country
    [SESSIONS] => total number of sessions
    [NEW_GUESTS] => total number of new visitors
    [HITS] => total number of hits
    [C_EVENTS] => total number of events
    [REFERENCE_ID] => the REFERENCE_ID parameter for use with SelectBox and SelectBoxM
    [REFERENCE] => the REFERENCE parameter for use with SelectBox and SelectBoxM
)

See Also

  • Settings of the Statistics module
  • SelectBox
  • SelectBoxM

Example

<?
// select countries with at least 100 sessions
$arFilter = array(
    "SESSIONS1" => 100
    );

// obtain the list
$rs = CCountry::GetList(
    ($by = "s_name"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>

<?
// single selection drop-down liat
echo SelectBox("COUNTRY_ID", CCountry::GetList(), "", intval($COUNTRY_ID));

// multiple selection list with 20 visible items
echo SelectBoxM("arCOUNTRY_ID[]", CCountry::GetList(), $arCOUNTRY_ID, "", false, 20);
?>


CGuest

The CGuest class is used to obtain information on the site visitors.

Methods

Method | Description
GetByID | Returns information on the specified visitor.
GetList | Returns a list of visitors.

See Also

  • Visitor
  • The Visitors report


GetByID

CGuest::GetByID

CDBResult
CGuest::GetByID(
 int guest_id
)

The method GetByID returns information on the specified visitor.

Parameters

Parameter | Description
guest_id | The visitor ID.

Structure of the returned record

Array
(
    [ID] => the visitor ID
    [FAVORITES] => [Y|N] means the site was added to Favorites
    [C_EVENTS] => number of events generated by this visitor
    [SESSIONS] => number of sessions of this visitor
    [HITS] => number of hits of this visitor
    [REPAIR] => [Y|N] means the visitor was "restored" after the data clean-up (Y)
    [FIRST_SESSION_ID] => the ID of the first session
    [FSESSION_TIME] => duration of the first session (sec.)
    [FSESSION_HITS] => number of hits within the first session
    [FIRST_DATE] => date and time of the first session
    [FIRST_URL_FROM] => URL of the page from which the visitor came for the first time
    [FIRST_URL_TO] => URL of the site page to which the visitor came for the first time
    [FIRST_URL_TO_404] => indicates the error 404 occurred on the page of the first visit
    [FIRST_SITE_ID] => the ID of the site of the first visit
    [FIRST_ADV_ID] => the ID of the advertising campaign under which the visitor came for the first time
    [FIRST_REFERER1] => the referer1 identifier of the advertising campaign FIRST_ADV_ID
    [FIRST_REFERER2] => the referer2 identifier of the advertising campaign FIRST_ADV_ID
    [FIRST_REFERER3] => the auxiliary parameter referer3 of the advertising campaign FIRST_ADV_ID
    [LAST_SESSION_ID] => the ID of the last session
    [LSESSION_TIME] => length of the last session (sec.)
    [LSESSION_HITS] => number of hits of the last session
    [LAST_DATE] => date and time of the last visit
    [LAST_USER_ID] => the user ID
    [USER_NAME] => first and last names of a user under which the visitor was last authorised
    [LOGIN] => login of a user under which the visitor was last authorised
    [LAST_USER_AUTH] => [Y|N] means the visitor was (or was not) authorised during the last session
    [LAST_URL_LAST] => URL of the last page
    [LAST_URL_LAST_404] => indicated the error 404 occurred at the last page
    [LAST_USER_AGENT] => the last UserAgent of the visitor
    [LAST_IP] => the visitor IP address of the last session
    [LAST_COOKIE] => the visitor Cookie of the last session
    [LAST_LANGUAGE] => the visitor browser languages of the last session
    [LAST_ADV_ID] => the advertising campaign ID of the last visit
    [LAST_ADV_BACK] => [Y|N]: Y - return, N - direct hit under the adv. campaign LAST_ADV_ID
    [LAST_REFERER1] => the identifier referer1 of the advertising campaign LAST_ADV_ID
    [LAST_REFERER2] => the identifier referer2 of the advertising campaign LAST_ADV_ID
    [LAST_REFERER3] => the auxiliary parameter referer3 of the advertising campaign LAST_ADV_ID
    [LAST_SITE_ID] => the ID of the last site
    [LAST_COUNTRY_ID] => the ID of the country during the last visit
    [COUNTRY_NAME] => the name of the country during the last visit
)

See Also

  • Visitor

Example

<?
$guest_id = 1;
if ($rs = CGuest::GetByID($guest_id))
{
    $ar = $rs->Fetch();
    // print the visitor parameters
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CGuest::GetList

CDBResult
CGuest::GetList(
 string &by = "s_last_date",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of visitors.

Parameters

Parameter | Description
by The field by which the returned list is to be sorted. The following values are possible:
  • s_id - the visitor ID;
  • s_events - total number of events generated by visitor;
  • s_sessions - total number of visitor sessions;
  • s_hits - total number of visitor hits;
  • s_first_site_id - the ID of the site of the first visit;
  • s_first_date - date and time of the first visit;
  • s_first_url_from - the page from which the visitor came for the first time;
  • s_first_url_to - the page to which the visitor came for the first time;
  • s_first_adv_id - the ID of advertising campaign of the first visit;
  • s_last_site_id - the ID of the site of the last visit;
  • s_last_date - date and time of the last visit;
  • s_last_user_id - the user ID;
  • s_last_url_last - URL of the last page;
  • s_last_user_agent - the last UserAgent of the visitor;
  • s_last_ip - the visitor IP address of the last session;
  • s_last_adv_id - the advertising campaign ID of the last visit;
  • s_last_country_id - the ID of the country during the last visit.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the visitor ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • REGISTERED - whether the visitor was ever authorised on the site (Y|N);
  • FIRST_DATE1 - minimum value of the range "date of the first visit";
  • FIRST_DATE2 - maximum value of the range "date of the first visit";
  • LAST_DATE1 - minimum value of the range "date of the last visit";
  • LAST_DATE2 - maximum value of the range "date of the last visit";
  • PERIOD_DATE1 - minimum value of the range of the visit date;
  • PERIOD_DATE2 - maximum value of the range of the visit date;
  • SITE_ID* - the ID of the site of the first or last visit;
  • SITE_ID_EXACT_MATCH - if "N", entry in the SITE_ID is sufficient (loose match);
  • FIRST_SITE_ID* - the ID of the site of the first visit;
  • FIRST_SITE_ID_EXACT_MATCH - if "N", entry in the FIRST_SITE_ID is sufficient (loose match);
  • LAST_SITE_ID* - the ID of the site of the last visit;
  • LAST_SITE_ID_EXACT_MATCH - if "N", entry in the LAST_SITE_ID is sufficient (loose match);
  • URL* - pages: from or to which the visitor came for the first time; and the last viewed page;
  • URL_EXACT_MATCH - if "Y", the URL must match exactly (strict match);
  • URL_404 - whether the error 404 occurred at the first or last page: Y|N;
  • USER_AGENT* - the visitor UserAgent during the last visit;
  • USER_AGENT_EXACT_MATCH - if "Y", the USER_AGENT must match exactly (strict match);
  • ADV - whether the visitor ever came under the advertising campaign (which is not NA/NA), possible values:
    • Y - the visitor came at least once under known advertising campaign;
    • N - the visitor never came under known advertising campaign.
  • ADV_ID - the ID of the advertising campaign of the first or last visit (can be both direct hit and return);
  • REFERER1* - the identifier referer1 of the advertising campaign of the first or last visit;
  • REFERER1_EXACT_MATCH - if "Y", the REFERER1 must match exactly (strict match);
  • REFERER2* - the identifier referer2 of the advertising campaign of the first or last visit;
  • REFERER2_EXACT_MATCH - if "Y", the REFERER2 must match exactly (strict match);
  • REFERER3* - the auxiliary parameter referer3 of the advertising campaign of the first or last visit;
  • REFERER3_EXACT_MATCH - if "Y", the REFERER3 must match exactly (strict match);
  • EVENTS1 - minimum number of the visitor generated events;
  • EVENTS2 - maximum number of the visitor generated events;
  • SESS1 - minimum number of the visitor generated sessions;
  • SESS2 - maximum number of the visitor generated sessions;
  • HITS1 - minimum number of the visitor generated hits;
  • HITS2 - maximum number of the visitor generated hits;
  • FAVORITES - whether the visitor added the site to Favorites (Y|N);
  • IP - the visitor IP during the last session;
  • LANG - the visitor browser languages of the last session;
  • COUNTRY_ID* - the ID of the country during the last visit;
  • COUNTRY_ID_EXACT_MATCH - if "Y", the COUNTRY_ID must match exactly (strict match);
  • COUNTRY* - name of the country;
  • COUNTRY_EXACT_MATCH - if "Y", the COUNTRY must match exactly (strict match);
  • USER* - ID, login, first/last names of a user under which the visitor was last authorised;
  • USER_EXACT_MATCH - if "Y", the USER must match exactly (strict match);
  • USER_ID* - the user ID under which the visitor was last authorised;
  • USER_ID_EXACT_MATCH - if "Y", the USER_ID must match exactly (strict match).

* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => the visitor ID
    [FAVORITES] => [Y|N] means the site was added to Favorites
    [C_EVENTS] => number of events generated by this visitor
    [SESSIONS] => number of sessions of this visitor
    [HITS] => number of hits of this visitor
    [FIRST_SESSION_ID] => the ID of the first session
    [FIRST_DATE] => date and time of the first session
    [FIRST_URL_FROM] => URL of the page from which the visitor came for the first time
    [FIRST_URL_TO] => URL of the site page to which the visitor came for the first time
    [FIRST_URL_TO_404] => indicates the error 404 occurred on the page of the first visit
    [FIRST_SITE_ID] => the ID of the site of the first visit
    [FIRST_ADV_ID] => the ID of the advertising campaign under which the visitor came for the first time
    [FIRST_REFERER1] => the referer1 identifier of the advertising campaign FIRST_ADV_ID
    [FIRST_REFERER2] => the referer2 identifier of the advertising campaign FIRST_ADV_ID
    [FIRST_REFERER3] => the auxiliary parameter referer3 of the advertising campaign FIRST_ADV_ID
    [LAST_SESSION_ID] => the ID of the last session
    [LAST_DATE] => date and time of the last visit
    [LAST_USER_ID] => the user ID
    [LAST_USER_AUTH] => [Y|N] means the visitor was (or was not) authorised during the last session
    [LAST_URL_LAST] => URL of the last page
    [LAST_URL_LAST_404] => indicated the error 404 occurred at the last page
    [LAST_USER_AGENT] => the last UserAgent of the visitor
    [LAST_IP] => the visitor IP address of the last session
    [LAST_LANGUAGE] => the visitor browser languages of the last session
    [LAST_ADV_ID] => the advertising campaign ID of the last visit
    [LAST_ADV_BACK] => [Y|N]: Y - return, N - direct hit under the adv. campaign LAST_ADV_ID
    [LAST_REFERER1] => the identifier referer1 of the advertising campaign LAST_ADV_ID
    [LAST_REFERER2] => the identifier referer2 of the advertising campaign LAST_ADV_ID
    [LAST_REFERER3] => the auxiliary parameter referer3 of the advertising campaign LAST_ADV_ID
    [LAST_SITE_ID] => the ID of the last site
    [LAST_COUNTRY_ID] => the ID of the country during the last visit
    [LAST_COUNTRY_NAME] => the name of the country during the last visit
                           (if filter["COUNTRY_ID"] is set)
)

See Also

  • Visitor

Example

<?
// select visitors with UserAgent == "Opera"
$arFilter = array(
    "USER_AGENT" => "Opera"
    );

// obtain the list
$rs = CGuest::GetList(
    ($by = "s_id"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CHit

The CHit class serves to obtain information on visitor hits.

Methods

Method | Description
GetByID | Returns information on the specified user hit.
GetList | Returns a list of visitor hits.

See Also

  • Hit
  • The Visitor Hits report


GetByID

CHit::GetByID

CDBResult
CHit::GetByID(
 int hit_id
)

The method GetByID returns information on the specified user hit.

Parameters

Parameter | Description
hit_id | The hit ID.

Structure of the returned record

Array
(
    [ID] => the hit ID
    [SESSION_ID] => the session ID
    [DATE_HIT] => date and time of the hit
    [GUEST_ID] => the visitor ID
    [NEW_GUEST] => [Y|N] flag "new visitor" (Y)
    [USER_ID] => the ID of a user under which the visitor was authorised (at the time of hit or before)
    [USER_AUTH] => [Y|N] flag indicating the visitor was authorised at the time of hit
    [URL] => hit page
    [URL_404] => whether the error 404 occurred on the hit page
    [URL_FROM] => URL from which the visitor came
    [IP] => the IP address of the visitor at the time of hit
    [METHOD] => the HTTP request method
    [COOKIES] => contents of visitor's Cookie at the time of hit
    [USER_AGENT] => the visitor's UserAgent at the time of hit
    [STOP_LIST_ID] => the ID of the stop list record for the visitor(if applicable)
    [COUNTRY_ID] => the country ID (two-character identifier) of the visitor at the time of hit (defined by the IP address)
    [COUNTRY_NAME] => name of the visitor country at the time of hit (defined by the IP address)
    [SITE_ID] => the site ID (two-character identifier)
    [LOGIN] => the user login under which the visitor was authorised (at the time of hit or before)
    [USER_NAME] => first and last names of a user under which the visitor was authorised (at the time of hit or before)
)

See Also

  • Hit

Example

<?
$hit_id = 1;
if ($rs = CHit::GetByID($hit_id))
{
    $ar = $rs->Fetch();
    // print the hit parameters
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CHit::GetList

CDBResult
CHit::GetList(
 string &by = "s_id",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of visitor hits.

Parameters

Parameter | Description
by The field by which the returned list is to be sorted. The following values are possible:
  • s_id - the hit ID;
  • s_site_id - the site ID;
  • s_session_id - the session ID;
  • s_date_hit - date ant time when the hit occurred;
  • s_user_id - the ID of a user under which the visitor was authorised (at the time of hit or before);
  • s_guest_id - the visitor ID;
  • s_ip - the IP address of the visitor;
  • s_url - the page where the hit occurred;
  • s_country_id - the ID of the visitor country.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the hit ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • GUEST_ID* - the visitor ID;
  • GUEST_ID_EXACT_MATCH - if "N", entry in the GUEST_ID is sufficient (loose match);
  • NEW_GUEST - the "new visitor" flag; possible values:
    • Y - first time visitor (in the scope of the portal);
    • N - old visitor.
  • SESSION_ID* - the session ID;
  • SESSION_ID_EXACT_MATCH - if "N", entry in the SESSION_ID is sufficient (loose match);
  • STOP_LIST_ID* - the ID of the stop list record for the visitor (if applicable);
  • STOP_LIST_ID_EXACT_MATCH - if "N", entry in the SESSION_ID is sufficient (loose match);
  • URL* - the page where the hit occurred;
  • URL_EXACT_MATCH - if "Y", the USER_AGENT must match exactly (strict match);
  • URL_404 - whether the error 404 occurred on the hit page (Y|N);
  • USER* - ID, login, first/last names of a user under which the visitor was authorised (at the time of hit or before);
  • USER_EXACT_MATCH - if "Y", the USER_AGENT must match exactly (strict match);
  • REGISTERED - whether the visitor was authorised on the site at the time of hit or before (Y|N);
  • DATE_1 - first value of the hit generation time range (time from which the hit could be generated);
  • DATE_2 - last value of the hit generation time range (time till which the hit could be generated);
  • IP* - the visitor IP address at the time of hit;
  • IP_EXACT_MATCH - if "Y", the IP must match exactly (strict match);
  • USER_AGENT* - the visitor UserAgent at the time of hit;
  • USER_AGENT_EXACT_MATCH - if "Y", the USER_AGENT must match exactly (strict match);
  • COUNTRY_ID* - the visitor country ID at the time of hit;
  • COUNTRY_ID_EXACT_MATCH - if "Y", the COUNTRY_ID must match exactly (strict match);
  • COUNTRY* - name of the country;
  • COUNTRY_EXACT_MATCH - if "Y", the COUNTRY must match exactly (strict match);
  • COOKIE* - Cookie contents at the time of hit;
  • COOKIE_EXACT_MATCH - if "Y", the COOKIE must match exactly (strict match);
  • STOP - the visitor was added to the stop list (Y|N);
  • SITE_ID* - the site ID;
  • SITE_ID_EXACT_MATCH - if "N", entry in the SITE_ID is sufficient (loose match).

* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => the hit ID
    [SESSION_ID] => the session ID
    [DATE_HIT] => date and time of the hit
    [GUEST_ID] => the visitor ID
    [NEW_GUEST] => [Y|N] flag "new visitor" (Y)
    [USER_ID] => the ID of a user under which the visitor was authorised (at the time of hit or before)
    [USER_AUTH] => [Y|N] flag indicating the visitor was authorised at the time of hit
    [URL] => hit page
    [URL_404] => whether the error 404 occurred on the hit page
    [URL_FROM] => URL from which the visitor came
    [IP] => the IP address of the visitor at the time of hit
    [METHOD] => the HTTP request method
    [COOKIES] => contents of visitor's Cookie at the time of hit
    [USER_AGENT] => the visitor's UserAgent at the time of hit
    [STOP_LIST_ID] => the ID of the stop list record for the visitor(if applicable)
    [COUNTRY_ID] => the country ID (two-character identifier) of the visitor at the time of hit (defined by the IP address)
    [COUNTRY_NAME] => name of the visitor country at the time of hit (defined by the IP address)
    [SITE_ID] => the site ID (two-character identifier)
    [LOGIN] => the user login under which the visitor was authorised (at the time of hit or before)
    [USER_NAME] => first and last names of a user under which the visitor was authorised (at the time of hit or before)
)

See Also

  • Hit

Example

<?
// select hits of session #1056
$arFilter = array(
    "SESSION_ID" => 1056
    );

// obtain the list of records
$rs = CHit::GetList(
    ($by = "s_id"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CPage

The CPage class helps to obtain information on visits and attendance of the site pages.

Methods

Method | Description
GetDynamicList | Returns information about the attendance of the specified page on daily basis.
GetList | Returns the list of visited pages (or catalogs), and the information on their attendance.

See Also

  • The Sections and Pages report


GetDynamicList

CPage::GetDynamicList

CDBResult
CPage::GetDynamicList(
 string url,
 string &by = "s_date",
 string &order = "desc",
 array filter = array()
)

The method GetDynamicList returns information about the attendance of the specified page on daily basis.

Parameters

Parameter | Description
url | Full path to the page or catalog whose information is required.
by Sorting field; the following values are possible:
  • s_date - date.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • DATE1 - the earliest date and time of the time period for which the information is to be returned;
  • DATE2 - the latest date and time of the time period;
  • ADV* - the ID of the advertising campaign (AC). This field allows to return only pages or catalogs that has been viewed by visitors under the specified AC, and obtain the attendance information only for these visitors;
  • ADV_EXACT_MATCH - if "N", entry in the ADV is sufficient (loose match);
  • ADV_DATA_TYPE - tells to retrieve information depending on the visit status (applicable if filter["ADV"] is present); the following values can be used:
    • B - return information on visitors returned under the specified AC;
    • P - return information on direct-hit visitors under the specified AC.
    If none of the values is specified, the information on both returned and direct-hit visitors will be returned.

* - complex logic allowed.

Structure of the returned record

Array
(
    [DATE_STAT] => date
    [DAY] => day ordinal (1-31)
    [MONTH] => month ordinal (1-12)
    [YEAR] => year
    [COUNTER] => hit count for the page url
    [ENTER_COUNTER] => how many times the page url was the entrance point
    [EXIT_COUNTER] => how many times the page url was the exit point
)

See Also

  • Entry point
  • Exit point

Example

<?
$url = "http://www.bitrixsoft.com/about/index.php";

// set the filter to match December 2005
// we want direct hits under AC's 1 or 2
$arFilter = array(
    "DATE1" => "01.12.2005",
    "DATE2" => "31.12.2005",
    "ADV"   => "1 | 2",
    "ADV_DATA_TYPE" => "P"
    );

// obtain the list of records
$rs = CPage::GetDynamicList(
    $url,
    ($by="s_date"),
    ($order="desc"),
    $arFilter,
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CPage::GetList

CDBResult
CPage::GetList(
 string counter_type = "",
 string &by = "s_last_date",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns the list of visited pages (or catalogs), and the information on their attendance.

Parameters

Parameter | Description
counter_type Type of counter. The following values apply:
  • ENTER_COUNTER - how many times the page was the entrance point;
  • EXIT_COUNTER - how many times the page was the exit point.
By default, the counter keeps total hits on a page (catalog), including both entrance and exit points.
by Sorting field; the following values are possible:
  • s_url - page (catalog);
  • s_counter - counter.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • DATE1 - the earliest date and time of the time period for which the information is to be returned;
  • DATE2 - the latest date and time of the time period;
  • DIR - specifies to return only pages or catalogs; the following values can be used:
    • Y - include catalogs only;
    • N - include pages only.
  • URL* - Full path to the page or catalog whose information is required;
  • URL_EXACT_MATCH - if "Y", the URL must match exactly (strict match);
  • URL_404 - whether the error 404 occurred on the required page (Y|N);

    This field cannot be used with catalogs.

  • ADV* - the ID of the advertising campaign (AC). This field allows to return only pages or catalogs that has been viewed by visitors under the specified AC, and obtain the attendance information only for these visitors;
  • ADV_EXACT_MATCH - if "N", entry in the ADV is sufficient (loose match);
  • ADV_DATA_TYPE - tells to retrieve information depending on the visit status:
    • B - return information on visitors returned under the specified AC;
    • P - return information on direct-hit visitors under the specified AC;
    • S - both returned and direct-hit visitors.
  • SITE_ID* - the site ID;
  • SITE_ID_EXACT_MATCH - if "N", entry in the SITE_ID is sufficient (loose match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [URL] => page (section)
    [DIR] => [Y|N] flag: page (N) or catalog (Y)
    [SITE_ID] => the site ID
    [URL_404] => the error 404 flag
    [COUNTER] => hit count for the page (catalog) url
                 (if only counter_type != ENTER_COUNTER
                  and counter_type != EXIT_COUNTER)
    [ENTER_COUNTER] => how many times the url was the entry point
                       (if only
                       counter_type = ENTER_COUNTER)
    [EXIT_COUNTER] => how many times the url was the exit point
                      (if only
                      counter_type = EXIT_COUNTER)
)

See Also

  • Entry point
  • Exit point

Example

<?
// obtain information on the page
$arFilter = array(
    "URL" => "http://www.bitrixsoft.com/about/index.php",
    "URL_EXACT_MATCH" => "Y"
    );

// retrieve the list of records
$rs = CPage::GetList(
    "",
    ($by = "s_last_date"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CPath

The CPath class helps obtain information on site paths.

Methods

Method | Description
GetByID | Returns a record from the table containing full site paths and path sections, on daily basis.
GetList | Returns a record from the path table according to the criteria specified.

See Also

  • The Site Paths report
  • Full path
  • Path section


GetByID

CPath::GetByID

CDBResult
CPath::GetByID(
 int id
)

The method GetByID returns a record from the table containing full site paths and path sections, on daily basis.

Parameters

Parameter | Description
id | The ID of the record to be returned.

Structure of the returned record

Array
(
    [ID] => the ID of the record in the site path table
    [PATH_ID] => the path ID
    [PARENT_PATH_ID] => the parent path ID
    [DATE_STAT] => date
    [COUNTER] => path click count
    [COUNTER_ABNORMAL] => path click count
                          without having received HTTP_REFERER
                          from the browser (see Referrer page)
    [COUNTER_FULL_PATH] => path click count
                           for pages listed in [PAGES]
    [PAGES] => pages that comprise the full path
    [FIRST_PAGE] => first page of the path
    [FIRST_PAGE_404] => indicates the error 404 occurred at the first page of the path
    [FIRST_PAGE_SITE_ID] => the ID of the site of the first page
    [PREV_PAGE] => penultimate page of the path
    [PREV_PAGE_HASH] => hash (crc32) of the penultimate page
    [LAST_PAGE] => last page
    [LAST_PAGE_404] => indicates the error 404 at the last page
    [LAST_PAGE_SITE_ID] => the ID of the site of the last page
    [LAST_PAGE_HASH] => hash (crc32) of the last page
    [STEPS] => number of pages in the path
               (number of pages in [PAGES])
)

See Also

  • Full path
  • Path section

Example

<?
$path_id = 1;
if ($rs = CPath::GetByID($path_id))
{
    $ar = $rs->Fetch();
    // print path section parameters
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CPath::GetList

CDBResult
CPath::GetList(
 int parent_id = "",
 string counter_type = "COUNTER_FULL_PATH",
 string &by = "s_counter",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a record from the table containing full site paths and path sections, on daily basis, according to the criteria specified.

Parameters

Parameter | Description
parent_id | The parent path section ID (preceding to this).
counter_type Type of counter:
  • COUNTER_FULL_PATH - full path click count;
  • COUNTER - path section click count.
by Sorting field; the following values are possible:
  • s_counter - value of counter counter_type;
  • s_last_page - last page of path section (applicable if counter_type = COUNTER);
  • s_pages - all pages of full path (applicable if counter_type = COUNTER_FULL_PATH).
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • PATH_ID* - the path section ID;
  • PATH_ID_EXACT_MATCH - if "N", entry in the PATH_ID is sufficient (loose match);
  • DATE1 - the earliest date and time of the time period for which the information is to be returned;
  • DATE2 - the latest date and time of the time period;
  • FIRST_PAGE* - first page in the path;
  • FIRST_PAGE_EXACT_MATCH - if "Y", the FIRST_PAGE must match exactly (strict match);
  • FIRST_PAGE_SITE_ID - the ID of the site of the first page in the path;
  • FIRST_PAGE_SITE_ID_EXACT_MATCH - if "N", entry in the PATH_ID is sufficient (loose match);
  • FIRST_PAGE_404 - indicates the error 404 occurred on the first page (Y|N);
  • LAST_PAGE* - the last page of the path;
  • LAST_PAGE_EXACT_MATCH - if "Y", the LAST_PAGE must match exactly (strict match);
  • LAST_PAGE_SITE_ID* - the ID of the site of the last page in the path;
  • LAST_PAGE_SITE_ID_EXACT_MATCH - if "N", entry in the LAST_PAGE_SITE_ID is sufficient (loose match);
  • LAST_PAGE_404 - indicates the error 404 occurred on the last page (Y|N);
  • PAGE* - arbitrary page of the path;
  • PAGE_EXACT_MATCH - if "N", entry in the PAGE is sufficient (loose match);
  • PAGE_SITE_ID - the ID of the site of arbitrary page;
  • PAGE_404 - indicates the error 404 occurred on arbitrary page (Y|N);
  • ADV* - the ID of an advertising campaign whose visitors' information is required;
  • ADV_EXACT_MATCH - if "N", entry in the ADV is sufficient (loose match);
  • ADV_DATA_TYPE - tells to retrieve information depending on the visit status:
    • P - return information on direct-hit visitors under the specified AC;
    • B - return information on visitors returned under the specified AC;
    • S - both returned and direct-hit visitors.
  • STEPS1 - minimum pages in the path;
  • STEPS2 - maximum pages in the path.
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

The structure varies depending on the counter_type.

  • if counter_type is COUNTER:
    Array
(
    [PATH_ID] => the path section ID
    [LAST_PAGE] => the last page of the path section
    [LAST_PAGE_404] => [Y|N] indicates the error 404 occurred on the last page
    [LAST_PAGE_SITE_ID] => the ID of the site of the last page in the path
    [COUNTER] => path section click count
)
  • if counter_type is COUNTER_FULL_PATH:
    Array
(
    [PATH_ID] => the path ID
    [PAGES] => all pages of full path
    [COUNTER] => full path click count
)

See Also

  • Full path
  • Path section

Example

<?
// select information on full paths of visitors
// under advertising campaigns #1 or #2
$arFilter = array(
    "ADV" => "1 | 2"
    );

// obtain the list
$rs = CPath::GetList(
    "",
    "COUNTER_FULL_PATH",
    ($by = "s_counter"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CPhrase

The CPhrase class is used to obtain information on search phrases.

Methods

Method | Description
GetList | Returns a list of search phrases.

See Also

  • The search phrases report
  • About search phrases
  • About search engines


GetList

CPhrase::GetList

CDBResult
CPhrase::GetList(
 string &by = "s_id",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered,
 int &total,
 string &group_by,
 int &max
)

The method GetList returns a list of search phrases, optionally grouped by search phrase or search engine.

Parameters

Parameter | Description
by Sorting field. Depending on how the list is grouped, possible values of this parameters may vary.
  • grouping by search phrase (filter["GROUP"]="P"):
    • s_phrase - search phrase;
    • s_quantity - number of hits using a search phrase.
  • grouping by search engine (filter["GROUP"]="S"):
    • s_name - search engine;
    • s_quantity - number of hits from this search engine;
    • s_average_hits - average number of hits made by visitors from a search engine.
  • without grouping:
    • s_id - the record ID;
    • s_counter - counter;
    • s_site_id - the ID of the target site;
    • s_phrase - search phrase;
    • s_searcher_id - the ID of the search engine;
    • s_referer_id - the ID of the record from the referring page table;
    • s_date_hit - date of the hit;
    • s_url_to - target page;
    • s_session_id - the session ID.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID - the record ID;
  • ID_EXACT_MATCH - if set to "N", the ID can be an entry in the identifier string (loose match);
  • SESSION_ID - the session ID;
  • SESSION_ID_EXACT_MATCH - if set to "N", the SESSION_ID can be an entry in the identifier string (loose match);
  • SEARCHER_ID - the ID of the search engine;
  • SEARCHER_ID_EXACT_MATCH - if set to "N", the SEARCHER_ID can be an entry in the identifier string (loose match);
  • REFERER_ID - the ID of the record from the referring page table;
  • REFERER_ID_EXACT_MATCH - if set to "N", the REFERER_ID can be an entry in the identifier string (loose match);
  • SEARCHER* - name of the search engine;
  • SEARCHER_EXACT_MATCH - if set to "Y", the SEARCHER must match exactly;
  • DATE1 - the earliest date and time of the time period for which the information is to be returned;
  • DATE2 - the latest date and time of the time period;
  • PHRASE* - search phrase;
  • PHRASE_EXACT_MATCH - if set to "Y", the PHRASE must match exactly;
  • TO* - target page;
  • TO_EXACT_MATCH - if set to "Y", the TO must match exactly;
  • TO_404 - indicates the error 404 occurred on the target page (Y|N);
  • SITE_ID - the ID of the target site;
  • GROUP - how the resulting list is grouped; possible values:
    • P - grouping by the search phrase;
    • S - grouping by the search engine.
* - complex logic allowed.
is_filtered | If this variable contains "true" on return, the resulting list is filtered.
total | Total number of search phrases.
group_by How the list of search phrases is grouped. Possible values:
  • P - grouping by the search phrase;
  • S - grouping by the search engine.
max | Number of hits using the most popular search phrase.

Structure of the returned record

The structure of the returned record varies depending on the grouping.

  • grouping by search phrase (filter["GROUP"]="P"):
    Array
(
    [PHRASE] => search phrase
    [QUANTITY] => number of visits using this
                  search phrase
    [PERCENT] => percentage of total
                 visits by various search phrase
)
  • grouping by search engine (filter["GROUP"]="S"):
    Array
(
    [SEARCHER_ID] => the ID of the search engine
    [SEARCHER_NAME] => name of the search engine
    [QUANTITY] => number of visits using this search engine
    [PERCENT] => percentage of total visits using this search engine
    [AVERAGE_HITS] => average number of hits made by visitors
                      using a search engine
)
  • without grouping:
    Array
(
    [ID] => the ID of the record
    [PHRASE] => search phrase
    [DATE_HIT] => time
    [SESSION_ID] => the session ID
    [REFERER_ID] => the ID of the record from the referring page table
    [SEARCHER_ID] => the ID of the search engine
    [SEARCHER_NAME] => name of the search engine
    [URL_TO] => target page
    [URL_TO_404] => indicates the error 404 occurred on the target page (Y|N);
    [SITE_ID] => the ID of the target site
)

See Also

  • Search phrase
  • Search engine

Example

<?
// we want only search phrases
// used for searches within the site
// using the internal search
$arFilter = array(
    "SEARCHER_ID"  => 1
    );

// obtain the list of records
$rs = CPhrase::GetList(
    ($by = "s_id"),
    ($order = "desc"),
    $arFilter,
    $is_filtered,
    $total,
    $group_by,
    $max
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CReferer

The CReferer class is used to obtain information on referred sites.

Methods

Method | Description
GetList | Returns a list of referring pages.

See Also

  • The referring sites report
  • Referring site (page)


GetList

CReferer::GetList

CDBResult
CReferer::GetList(
 string &by = "s_id",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered,
 int &total,
 string &group_by,
 int &max
)

The method GetList returns a list of referring pages.

Parameters

Parameter | Description
by Sorting field. Depending on how the list is grouped, possible values of this parameters may vary.
  • grouping by referring page (filter["GROUP"]="U"):
    • s_url_from - referring page;
    • s_quantity - number of hits made from referring page;
    • s_average_hits - average number of hits made by visitors from a referring page.
  • grouping by referring domain (filter["GROUP"]="S"):
    • s_url_from - referring domain;
    • s_quantity - number of hits made from referring page;
    • s_average_hits - average number of hits made by visitors.
  • without grouping:
    • s_id - the record ID;
    • s_site_id - the ID of the target site;
    • s_url_from - referring page;
    • s_url_to - target page;
    • s_date_hit - date;
    • s_session_id - the session ID.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID - the record ID;
  • ID_EXACT_MATCH - if set to "N", the ID can be an entry in the identifier string (loose match);
  • SESSION_ID - the session ID;
  • SESSION_ID_EXACT_MATCH - if set to "N", the SESSION_ID can be an entry in the identifier string (loose match);
  • DATE1 - the earliest date and time of the time period for which the information is to be returned;
  • DATE2 - the latest date and time of the time period;
  • FROM_PROTOCOL - protocol of the referring page;
  • FROM_PROTOCOL_EXACT_MATCH - if set to "Y", the FROM_PROTOCOL must match exactly;
  • FROM_DOMAIN - domain of the referring page;
  • FROM_DOMAIN_EXACT_MATCH - if set to "Y", the FROM_DOMAIN must match exactly;
  • FROM_PAGE - referring page;
  • FROM_PAGE_EXACT_MATCH - if set to "Y", the FROM_PAGE must match exactly;
  • FROM - protocol + domain + referring page;
  • FROM_EXACT_MATCH - if set to "Y", the FROM must match exactly;
  • TO* - target page;
  • TO_EXACT_MATCH - if set to "Y", the TO must match exactly;
  • TO_404 - indicates the error 404 occurred on the target page (Y|N);
  • SITE_ID - the ID of the target site;
  • GROUP - how the resulting list is grouped; possible values:
    • S - grouping by the referring domain (site);
    • U - grouping by the referring page.
* - complex logic allowed.
is_filtered | If this variable contains "true" on return, the resulting list is filtered.
total | Total number of hits from the referring pages.
group_by How the returned list is grouped. Possible values:
  • U - grouping by the referring page;
  • S - grouping by the referring domain.
max | Number of hits from the most popular referring page.

Structure of the returned record

The structure of the returned record varies depending on the grouping.

  • grouping by referring page (filter["GROUP"]="U"):
    Array
(
    [URL_FROM] => referring page
    [QUANTITY] => number of visits from this referring page
    [PERCENT] => ratio of number of hits from this referring page to the total
                 hits from all referring sites
    [AVERAGE_HITS] => average number of hits made by visitors
                      from this referring page
)
  • grouping by referring domain (filter["GROUP"]="S"):
    Array
(
    [URL_FROM] => referring domain
    [QUANTITY] => number of visits from this referring domain
    [PERCENT] => ratio of number of hits from this referring domain to the total
                 hits from all referring sites
    [AVERAGE_HITS] => average number of hits made by visitors
                      from this referring domain
)
  • without grouping:
    Array
(
    [ID] => the record ID
    [URL_FROM] => referring page
    [DATE_HIT] => date
    [SESSION_ID] => the session ID
    [URL_TO] => target page
    [URL_TO_404] => indicates the error 404 occurred on the target page (Y|N)
    [SITE_ID] => the ID of the target site
)

See Also

  • Referring site (page)

Example

<?
// we want only hits from the "google" domains
// grouped by the referring domain
$arFilter = array(
    "FROM_DOMAIN"  => "google",
    "GROUP"        => "S"
    );

// obtain the list of records
$rs = CReferer::GetList(
    ($by = "s_url_from"),
    ($order = "desc"),
    $arFilter,
    $is_filtered,
    $total,
    $group_by,
    $max
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CSearcher

The CSearcher class is used with search engines.

Methods

Method | Description
GetByID | Returns information about the specified search engine.
GetDomainList | Returns a list of search engine domains.
GetDropdownList | Returns a list of search engines for use in a drop-down list or in a multiple selection list.
GetDynamicList | Returns the number of hits (indexed pages) for the specified search engine on daily basis.
GetList | Returns a list of search engines and their number of hits (indexed pages) for the specified period.

See Also

  • The Search engines report


GetByID

CSearcher::GetByID

CDBResult
CSearcher::GetByID(
 int searcher_id
)

The method GetByID returns information about the specified search engine.

Parameters

Parameter | Description
searcher_id | The search engine ID.

Structure of the returned record

Array
(
    [ID] => the search engine ID
    [DATE_CLEANUP] => date when the expired page indexing data
                      was cleaned up, on daily basis
    [TOTAL_HITS] => total number of indexed pages
    [SAVE_STATISTIC] => [Y|N] flag: whether to keep information
                                    on indexed pages or not
    [ACTIVE] => [Y|N] active state flag
    [NAME] => name of the search engine
    [USER_AGENT] => the search engine UserAgent
    [DIAGRAM_DEFAULT] => [Y|N] flag: whether to include the SE
                                     in graph and chart by default
    [HIT_KEEP_DAYS] => days to keep the search engine hits
    [DYNAMIC_KEEP_DAYS] => days to keep information on
                           site indexing, on daily basis
    [PHRASES] => number of visits from this search engine
                 using a search phrase
    [PHRASES_HITS] => number of hits from this search engine
                      using a search phrase
    [CHECK_ACTIVITY] => [Y|N] flag: whether to check the activity limit
                                    of this search engine while the site
                                    is being indexed
)

See Also

  • CSearcher::GetDomainList
  • Search engine

Example

<?
$searcher_id = 1;
if ($rs = CSearcher::GetByID($searcher_id))
{
    $ar = $rs->Fetch();
    // print the search engine parameters
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetDomainList

CSearcher::GetDomainList

CDBResult
CSearcher::GetDomainList(
 string &by = "s_id",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetDomainList returns a list of search engine domains.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_id - the domain ID;
  • s_domain - domain;
  • s_variable - variable name (separate multiple names with comma), containing the search phrase.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the domain ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • SEARCHER_ID* - the search engine ID;
  • SEARCHER_ID_EXACT_MATCH - if "N", entry in the SEARCHER_ID is sufficient (loose match);
  • DOMAIN* - domain;
  • DOMAIN_EXACT_MATCH - if "Y", the DOMAIN must match exactly (strict match);
  • VARIABLE* - variable name (separate multiple names with comma), containing the search phrase;
  • VARIABLE_EXACT_MATCH - if "Y", the VARIABLE must match exactly (strict match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => the domain ID
    [DOMAIN] => domain
    [VARIABLE] => variable name (separate multiple names
                  with comma), containing the search phrase
)

See Also

  • CSearcher::GetByID
  • Search engine domain

Example

<?
// select domains of the search engine #20
$arFilter = array(
    "SEARCHER_ID" => 20
    );

// obtain the list of records
$rs = CSearcher::GetDomainList(
    ($by = "s_id"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetDropdownList

CSearcher::GetDropdownList

CDBResult
CSearcher::GetDropdownList(
 string order = "ORDER BY NAME, ID"
)

The method GetDropdownList returns a list of search engines for use in a drop-down list (SelectBox function), or in a multiple selection list (SelectBoxM function).

Parameters

Parameter | Description
order | The SQL code that can be used to set arbitrary sorting of the advertising campaigns list.

See Also

  • CSearcher::GetList
  • Search engine

Example

<?
// single-selection list
echo SelectBox(
    "SEARCHER_ID",
    CSearcher::GetDropdownList(),
    "",
    intval($SEARCHER_ID)
    );

// multiple selection list of 20 visible items
echo SelectBoxM(
    "arSEARCHER_ID[]",
    CSearcher::GetDropdownList(),
    $arSEARCHER_ID,
    "",
    false,
    20
    );
?>


GetDynamicList

CSearcher::GetDynamicList

CDBResult
CSearcher::GetDynamicList(
 int searcher_id,
 string &by = "s_date",
 string &order = "desc",
 array &max_min,
 array filter = array()
)

The method GetDynamicList returns the number of hits (indexed pages) for the specified search engine on daily basis.

Parameters

Parameter | Description
searcher_id | The search engine ID.
by Sorting field. Possible values:
  • s_date - date.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
max_min Reference to an array containing the earliest and latest dates of the returned list. The array has the following structure:
Array
(
    [DATE_FIRST] => the earliest date
    [MIN_DAY] => day of the earliest date (1-31)
    [MIN_MONTH] => month of the earliest date (1-12)
    [MIN_YEAR] => year of the earliest date

    [DATE_LAST] => the latest date
    [MAX_DAY] => day the latest date (1-31)
    [MAX_MONTH] => month the latest date (1-12)
    [MAX_YEAR] => year the latest date
)
filter Array used to filter the resulting list. The following keys can be used in the array:
  • DATE1 - minimum value of the "date" field;
  • DATE2 - maximum value of the "date" field.

Structure of the returned record

Array
(
    [DATE_STAT] => date
    [DAY] => day ordinal (1-31)
    [MONTH] => month ordinal (1-12)
    [YEAR] => year
    [TOTAL_HITS] => hit count (number of indexed pages)
)

See Also

  • Search engine hit

Example

<?
$searcher_id = 1;

// Set the filter to match December 2005
$arFilter = array(
    "DATE1" => "01.12.2005",
    "DATE2" => "31.12.2005"
    );

// obtain the list of records
$rs = CSearcher::GetDynamicList(
    $searcher_id,
    ($by="s_date"),
    ($order="desc"),
    $arMaxMin,
    $arFilter
    );

// print the array with max and min dates
echo "<pre>"; print_r($arMaxMin); echo "</pre>";

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CSearcher::GetList

CDBResult
CSearcher::GetList(
 string &by = "s_today_hits",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered,
 mixed limit = false
)

The method GetList returns a list of search engines and their number of hits (indexed pages): for the whole time of keeping statistics, for the last 3 days, or for the specified period.

Parameters

Parameter | Description
by Sorting field. Possible values:
  • s_id - the search engine ID;
  • s_date_last - date of the last hit;
  • s_today_hits - today's hits;
  • s_yesterday_hits - yesterday's hits;
  • s_b_yesterday_hits - number of hits for day before yesterday;
  • s_total_hits - total hits;
  • s_period_hits - number of hits for the specified period (filter["DATE1"], filter["DATE2"]);
  • s_name - search engine name;
  • s_user_agent - the search engine UserAgent.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the search engine ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • ACTIVE - active state flag:
    • Y - active;
    • N - inactive.
  • SAVE_STATISTIC - flag: whether to save search engine hits or not (Y|N);
  • DIAGRAM_DEFAULT - flag: whether to include in graphs and charts by default (Y|N);
  • HITS1 - minimum hits to match against the field "number of hits";
  • HITS2 - maximum hits to match against the field "number of hits";
  • DATE1_PERIOD - the earliest date of an arbitrary period;
  • DATE2_PERIOD - the latest date of an arbitrary period;
  • DATE1 - the earliest date of the required search engine hits;
  • DATE2 - the latest date of the required search engine hits;
  • NAME* - search engine name;
  • NAME_EXACT_MATCH - if "Y", the NAME must match exactly (strict match);
  • USER_AGENT* - the search engine UserAgent;
  • USER_AGENT_EXACT_MATCH - if "Y", the USER_AGENT must match exactly (strict match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.
limit | Maximum number of search engines to return. If set to false, the number of search engines will be limited to that specified in the parameter Maximum number of records displayed in tables in the Statistics module settings.

Structure of the returned record

Array
(
    [ID] => the search engine ID
    [NAME] => name
    [USER_AGENT] => UserAgent
    [DIAGRAM_DEFAULT] => [Y|N] flag: whether to include in
                                     graphs and charts by default
    [DATE_LAST] => date of the last hit
    [TOTAL_HITS] => total hits
    [TODAY_HITS] => today's hits
    [YESTERDAY_HITS] => yesterday's hits
    [B_YESTERDAY_HITS] => number of hits for day before yesterday
    [PERIOD_HITS] => number of hits for the specified period
                     (filter["DATE1_PERIOD"], filter["DATE2_PERIOD"])
)

See Also

  • CSearcher::GetDropdownList
  • Search engine

Example

<?
// We want data on search engines #20 and #21
// also get additional information for December 2005
$arFilter = array(
    "ID"           => "20 | 21",
    "DATE1_PERIOD" => "01.12.2005",
    "DATE2_PERIOD" => "31.12.2005",
    );

// obtain the list of records
$rs = CSearcher::GetList(
    ($by = "s_today_hits"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CSearcherHit

The CSearcherHit class is used to obtain information on hits of search engine (indexed pages).

Methods

Method | Description
GetList | Returns a list of search engine hits.

See Also

  • The Search Engine Hits report
  • Search engine hit


GetList

CSearcherHit::GetList

CDBResult
CSearcherHit::GetList(
 string &by = "s_date_hit",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of search engine hits.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_id - the hit ID;
  • s_site_id - the site ID;
  • s_date_hit - the date the hit was made;
  • s_searcher_id - the search engine ID;
  • s_user_agent - the search engine UserAgent;
  • s_ip - the search engine IP address;
  • s_url - address of the indexed page.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the hit ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • SEARCHER_ID* - the search engine ID;
  • SEARCHER_ID_EXACT_MATCH - if "N", entry in the SEARCHER_ID is sufficient (loose match);
  • URL* - address of the indexed page;
  • URL_404 - indicates the error 404 occurred on the first page (Y|N);
  • SEARCHER* - name of the search engine;
  • SEARCHER_EXACT_MATCH - if "Y", the SEARCHER must match exactly (strict match);
  • DATE1 - the earliest date of the hit for which the information is to be returned;
  • DATE2 - the latest date of the hit for which the information is to be returned;
  • IP* - the search engine IP address;
  • IP_EXACT_MATCH - if "Y", the FIRST_PAGE must match exactly (strict match);
  • USER_AGENT* - the search engine UserAgent;
  • USER_AGENT_EXACT_MATCH - if "Y", the USER_AGENT must match exactly (strict match);
  • SITE_ID* - the site ID;
  • SITE_ID_EXACT_MATCH - if "Y", the SITE_ID must match exactly (strict match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => the hit ID
    [DATE_HIT] => date of the hit
    [SEARCHER_ID] => the search engine ID
    [SEARCHER_NAME] => name of the search engine
    [URL] => address of the indexed page
    [URL_404] => [Y|N] indicates the error 404 occurred on the indexed page
    [IP] => the search engine IP address
    [USER_AGENT] => the search engine UserAgent
    [HIT_KEEP_DAYS] => days to keep hits of the search engine
    [SITE_ID] => the site ID
)

See Also

  • Search engine hit

Example

<?
// we want pages indexed by search engines #20 and #21
$arFilter = array(
    "SEARCHER_ID" => "20 | 21"
    );

// obtain the list of records
$rs = CSearcherHit::GetList(
    ($by = "s_url"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CSession

The CSession class helps obtain information about the visitor sessions.

Methods

Method | Description
GetByID | Returns information about the specified session.
GetList | Returns a list of sessions.

See Also

  • The Visitor Sessions report


GetByID

CSession::GetByID

CDBResult
CSession::GetByID(
 int session_id
)

The method GetByID returns information about the specified session.

Parameters

Parameter | Description
session_id | The session ID.

Structure of the returned record

Array
(
    [ID] => the session ID
    [GUEST_ID] => the visitor ID
    [NEW_GUEST] => [Y|N] flag: new visitor
    [USER_ID] => the ID of a user under which the visitor
                 was last authorised
    [USER_AUTH] => [Y|N] flag: whether the visitor was authorised
                               during this session
    [LOGIN] => the user login under which the visitor
               was last authorised
    [USER_NAME] => first and last names of a user under which
                   the visitor was last authorised
    [C_EVENTS] => number of events occurred during this session
    [HITS] => number of hits occurred during this session
    [FAVORITES] => [Y|N] flag: the site was added to Favorites
    [URL_FROM] => the referring page of the first session hit
    [URL_TO] => the first page of the session
    [URL_TO_404] => [Y|N] indicates the error 404 occurred
                    on the first page of the session
    [URL_LAST] => the last page of the session
    [URL_LAST_404] => [Y|N] indicates the error 404 occurred
                      on the last page of the session
    [USER_AGENT] => the visitor UserAgent
    [DATE_STAT] => date and time the session started
    [DATE_FIRST] => date and time the first hit occurred
    [DATE_LAST] => date and time the last hit occurred
    [SESSION_TIME] => time difference between the first and last hits (sec.)
    [IP_FIRST] => the visitor IP address during the first hit
                  (in the form XXX.XXX.XXX.XXX)
    [IP_FIRST_NUMBER] => the visitor IP address during the first hit
                         (numerical)
    [IP_LAST] => the visitor IP address during the last hit
                 (in the form XXX.XXX.XXX.XXX)
    [IP_LAST_NUMBER] => the visitor IP address during the first hit
                        (numerical)
    [FIRST_HIT_ID] => the first hit ID
    [FIRST_SITE_ID] => the ID of the first hit site
    [LAST_HIT_ID] => the last hit ID
    [LAST_SITE_ID] => the ID of the last hit site
    [ADV_ID] => the advertising campaign ID
    [ADV_BACK] => [Y|N] flag: direct hit (N)
                  or return (Y) under an advertising campaign
    [REFERER1] => the referer1 identifier of an advertising campaign
    [REFERER2] => the referer2 identifier of an advertising campaign
    [REFERER3] => the referer3 auxiliary parameter of an advertising campaign
    [COUNTRY_ID] => the visitor country ID
    [COUNTRY_NAME] => name of the visitor country
    [STOP_LIST_ID] => the ID of the stop list record
                      for the visitor (if applicable)
    [PHPSESSID] => the PHP session identifier
)

See Also

  • Session

Example

<?
$session_id = 1;
if ($rs = CSession::GetByID($session_id))
{
    $ar = $rs->Fetch();
    // print session parameters
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CSession::GetList

CDBResult
CSession::GetList(
 string &by = "s_id",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of sessions.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_id - the session ID;
  • s_last_site_id - the ID of the last hit site;
  • s_first_site_id - the ID of the first hit site;
  • s_date_first - date and time the first hit occurred;
  • s_date_last - date and time the last hit occurred;
  • s_user_id - the ID of a user under which the visitor was last authorised;
  • s_guest_id - the visitor ID;
  • s_ip - the visitor IP address during the last hit;
  • s_hits - number of hits occurred during this session;
  • s_events - number of events occurred during this session;
  • s_adv_id - the ID of an advertising campaign that led the visitor to the site;
  • s_country_id - the visitor country ID;
  • s_url_last - the first page (hit) of the session;
  • s_url_to - the last page (hit) of the session.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the session ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • GUEST_ID* - the visitor ID;
  • GUEST_ID_EXACT_MATCH - if "N", entry in the GUEST_ID is sufficient (loose match);
  • NEW_GUEST - flag: new visitor (Y|N);
  • USER_ID* - the ID of a user under which the visitor was last authorised;
  • USER_ID_EXACT_MATCH - if "N", entry in the USER_ID is sufficient (loose match);
  • USER_AUTH - flag: whether the visitor was authorised during this session (Y|N);
  • USER* - ID, first and last names of a user under which the visitor was last authorised;
  • USER_EXACT_MATCH - if "Y", the USER must match exactly (strict match);
  • REGISTERED - flag: whether the visitor was authorised during this session or before (Y|N);
  • FAVORITES - flag: the site was added to Favorites (Y|N);
  • EVENTS1 - minimum number of events generated during the session;
  • EVENTS2 - maximum number of events generated during the session;
  • HITS1 - minimum number of hits generated during the session;
  • HITS2 - maximum number of hits generated during the session;
  • ADV - flag: whether the visitor came under an advertising campaign (Y|N);
  • ADV_ID* - the advertising campaign ID;
  • ADV_ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • ADV_BACK - flag: direct hit (N) or return (Y) under an advertising campaign;
  • REFERER1* - the referer1 identifier of an advertising campaign;
  • REFERER1_EXACT_MATCH - if "Y", the REFERER1 must match exactly (strict match);
  • REFERER2* - the referer2 identifier of an advertising campaign;
  • REFERER2_EXACT_MATCH - if "Y", the REFERER2 must match exactly (strict match);
  • REFERER3* - the referer3 auxiliary parameter of an advertising campaign;
  • REFERER3_EXACT_MATCH - if "Y", the REFERER3 must match exactly (strict match);
  • STOP - flag: whether the visitor was put in the stop list (Y|N);
  • STOP_LIST_ID* - the ID of the stop list record for the visitor (if applicable);
  • STOP_LIST_ID_EXACT_MATCH - if "N", entry in the STOP_LIST_ID is sufficient (loose match);
  • COUNTRY_ID* - the visitor country ID;
  • COUNTRY_ID_EXACT_MATCH - if "N", entry in the COUNTRY_ID is sufficient (loose match);
  • COUNTRY* - name of the visitor country;
  • COUNTRY_EXACT_MATCH - if "Y", the COUNTRY must match exactly (strict match);
  • IP* - the visitor IP address during the last hit;
  • IP_EXACT_MATCH - if "Y", the IP must match exactly (strict match);
  • USER_AGENT* - the visitor UserAgent;
  • USER_AGENT_EXACT_MATCH - if "Y", the USER_AGENT must match exactly (strict match);
  • DATE_START_1 - first value of the first hit generation time range (time from which the first hit could be generated);
  • DATE_START_2 - last value of the first hit generation time range (time till which the first hit could be generated);
  • DATE_END_1 - first value of the last hit generation time range (time from which the last hit could be generated);
  • DATE_END_2 - last value of the last hit generation time range (time till which the last hit could be generated);
  • URL_TO* - the first page of the session;
  • URL_TO_EXACT_MATCH - if "Y", the URL_TO must match exactly (strict match);
  • URL_TO_404 - indicates the error 404 occurred on the first page of the session (Y|N);
  • FIRST_SITE_ID* - the ID of the first hit site;
  • FIRST_SITE_ID_EXACT_MATCH - if "N", entry in the FIRST_SITE_ID is sufficient (loose match);
  • URL_LAST* - the last page of the session;
  • URL_LAST_EXACT_MATCH - if "Y", the URL_LAST must match exactly (strict match);
  • URL_LAST_404 - indicates the error 404 occurred on the last page of the session (Y|N);
  • LAST_SITE_ID* - the ID of the last hit site;
  • LAST_SITE_ID_EXACT_MATCH - if "N", entry in the LAST_SITE_ID is sufficient (loose match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => the session ID
    [GUEST_ID] => the visitor ID
    [NEW_GUEST] => [Y|N] flag: new visitor
    [USER_ID] => the ID of a user under which the visitor
                 was last authorised
    [USER_AUTH] => [Y|N] flag: whether the visitor was authorised
                               during this session
    [C_EVENTS] => number of events occurred during this session
    [HITS] => number of hits occurred during this session
    [FAVORITES] => [Y|N] flag: the site was added to Favorites
    [STOP_LIST_ID] => the ID of the stop list record
                      for the visitor (if applicable)
    [COUNTRY_ID] => the visitor country ID
    [USER_AGENT] => the visitor UserAgent

    [URL_FROM] => the referring page of the first session hit

    [DATE_STAT] => date of the first hit
    [DATE_FIRST] => time of the first hit
    [URL_TO] => the first page of the session
    [URL_TO_404] => [Y|N] indicates the error 404 occurred
                    on the first page of the session
    [FIRST_HIT_ID] => the first hit ID
    [FIRST_SITE_ID] => the ID of the first hit site
    [IP_FIRST] => the visitor IP address during the first hit
                  (in the form XXX.XXX.XXX.XXX)
    [IP_FIRST_NUMBER] => the visitor IP address during the first hit
                         (numerical)

    [DATE_LAST] => date and time the last hit occurred
    [URL_LAST] => the last page of the session
    [URL_LAST_404] => [Y|N] indicates the error 404 occurred
                      on the last page of the session
    [LAST_HIT_ID] => the last hit ID
    [LAST_SITE_ID] => the ID of the last hit site
    [IP_LAST] => the visitor IP address during the last hit
                 (in the form XXX.XXX.XXX.XXX)
    [IP_LAST_NUMBER] => the visitor IP address during the first hit
                        (numerical)

    [ADV_ID] => the advertising campaign ID
    [ADV_BACK] => [Y|N] flag: direct hit (N)
                  or return (Y) under an advertising campaign
    [REFERER1] => the referer1 identifier of an advertising campaign
    [REFERER2] => the referer2 identifier of an advertising campaign
    [REFERER3] => the referer3 auxiliary parameter of an advertising campaign

    [SESSION_TIME] => time difference between the first and last hits (sec.)
    [PHPSESSID] => the PHP session identifier
)

See Also

  • Session

Example

<?
// select all existing sessions of the visitor #1025
$arFilter = array(
    "GUEST_ID" => "1025"
    );

// obtain the list of records
$rs = CSession::GetList(
    ($by = "s_id"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CStatEvent

The CStatEvent class is used to add, delete and manage events.

Methods

Method | Description
Add | Adds an event of the specified type using information contained in the special parameter.
AddByEvents | Adds an event by the specified event type identifiers and a special parameter.
AddCurrent | Adds an event by the parameters of the current visitor.
DecodeGid | Decodes the specified special parameter.
Delete | Deletes the specified event.
GetGID | Returns the special parameter used for creating events.
GetHandlerList | Returns a list of CSV file handlers for displaying in the drop-down list
GetList | Returns a list of events.
GetListByGuest | Returns a list of event identifiers by the site visitor ID.

See Also

  • The Event list report


Add

CStatEvent::Add

int
CStatEvent::Add(
 int type_id,
 string event3,
 string date,
 string gid,
 mixed money = "",
 string currency = "",
 string chargeback = "N"
)

The method Add adds an event of the specified type using information contained in the special parameter.

Parameters

Parameter | Description
type_id | The event type ID.
event3 | The event auxiliary parameter event3.
date | Date in the current time.
gid | Special parameter containing all information (in the encoded form) required to add the event.
money | Amount of money.
currency | Three-character currency identifier. Currency identifiers are defined in the Currencies module.
chargeback Indicates a negative amount ("N"). Used in situations when a chargeback event occurs. Possible values:
  • Y - the amount is negative;
  • N - the amount is positive.

Return Values

Returns the ID of the added event on success, or 0 (null) otherwise.

See Also

  • CStatEvent::AddByEvents
  • CStatEvent::AddCurrent
  • Creating Events
  • Event
  • Auxiliary event parameter
  • Special event parameter

Example

<?
// add an event of the type #1
// the type must be created in advance

// special parameter in readable form
$gid = "BITRIX_SM.995.82.N0.25.N.ru";

// date in the format of the current site or language
$date = "23.12.2005 18:15:10";

CStatEvent::Add(1, "", $date, $gid, 99, "USD");
?>

<?
// add an event of the type #2
// the type must be created in advance

// special parameter in encoded form
$gid = "BITRIX_SM.OTk1LjgyLk4wLjI1Lk4ucnU%3D";

// date in the format of the current site or language
$date = "01.06.2005";

CStatEvent::Add(2, "", $date, $gid, "199", "EUR");
?>


AddByEvents

CStatEvent::AddByEvents

int
CStatEvent::AddByEvents(
 string event1,
 string event2,
 string event3,
 string date,
 string gid,
 mixed money = "",
 string currency = "",
 string chargeback = "N"
)

The method AddByEvents adds an event by the specified event type identifiers and a special parameter. If no event type with identifiers event1, event2 exists, it will be automatically created.

Parameters

Parameter | Description
event1 | The event1 event type identifier.
event2 | The event2 event type identifier.
event3 | The event auxiliary parameter event3.
date | Date in the current format.
gid | Special parameter containing all information (in the encoded form) required to add the event.
money | Amount of money.
currency | Three-character currency identifier. Currency identifiers are defined in the Currencies module.
chargeback Indicates a negative amount ("N"). Used in situations when a chargeback event occurs. Possible values:
  • Y - the amount is negative;
  • N - the amount is positive.

Return Values

Returns the ID of the added event on success, or 0 (null) otherwise.

See Also

  • CStatEvent::Add
  • CStatEvent::AddCurrent
  • Creating Events
  • Event
  • Auxiliary event parameter
  • Special event parameter

Example

<?
// add an event of the type softkey/buy
// if it does not exist, it will be created

// special parameter in readable form
$gid = "BITRIX_SM.995.82.N0.25.N.ru";

// date in the format of the current site or language
$date = "23.12.2005 18:15:10";

CStatEvent::AddByEvents("softkey", "buy", "", $date, $gid, "899", "USD");
?>

<?
// add an event of the type regnow/buy
// if it does not exist, it will be created

// special parameter in encoded form
$gid = "BITRIX_SM.OTk1LjgyLk4wLjI1Lk4ucnU%3D";

// date in the format of the current site or language
$date = "01.06.2005";

CStatEvent::AddByEvents("regnow", "buy", "", $date, $gid, "199", "EUR");
?>


AddCurrent

CStatEvent::AddCurrent

array
CStatEvent::AddCurrent(
 string event1,
 string event2 = "",
 string event3 = "",
 mixed money = "",
 string currency = "",
 string goto = "",
 string chargeback = "N",
 mixed site_id = false
)

The method AddCurrent adds an event by the parameters of the current visitor. If no event type with identifiers event1, event2 exists, it will be automatically created.

Parameters

Parameter | Description
event1 | event1 event type identifier.
event2 | event2 event type identifier.
event3 | The event auxiliary parameter event3.
money | Amount of money.
currency | Three-character currency identifier. Currency identifiers are defined in the Currencies module.
goto | Address of the page the visitor want to open. Commonly used in scripts like /bitrix/redirect.php, that redirect visitors to other pages and register the required event.
chargeback Indicates a negative amount ("N"). Used in situations when a chargeback event occurs. Possible values:
  • Y - the amount is negative;
  • N - the amount is positive.
site_id | The ID of the site with which the new event will be associated.

Return Values

Returns an array in the following format:

Array
(
    [TYPE_ID] => the event type ID
    [EID] => the ID of the new event
)

See Also

  • CStatEvent::Add
  • CStatEvent::AddByEvents
  • Event
  • Auxiliary event parameter

Example

<?
// register an event of the type
// "Special page views" (view/special_page)
CStatEvent::AddCurrent("softkey",
                       "out",
                       $GLOBALS["APPLICATION"]->GetCurPage());
?>

<?
// register an event of the type
// "Redirect to Softkey payment page" (softkey/out)
// if it does not exist, it will be created
// register the event using the current visitor parameters

// this variable can contain page to redirect to
$goto = "http://www.softkey.ru/catalog/basket.php?prodid=902&"
        "quantity=1&referer1=ritlabs_site&"
        "referer2=BITRIX_SM.OTk1LjgyLk4wLjI1Lk4ucnU%3D";

CStatEvent::AddCurrent("softkey", "out", "", "", "", $goto);
?>

<?
// register an event of the type
// "CHM file download" (download/manual)
// if it does not exist, it will be created
// register the event using the current visitor parameters

// check if the current visitor tried to download the file
// within the last hour

// get the event type ID
$rs = CStatEventType::GetByEvents($event1, $event2);
if ($ar = $rs->Fetch())
{
    // get all events of this type for the current visitor
    // for the last hour (3600 sec)
    $rs = CStatEvent::GetListByGuest($_SESSION["SESS_GUEST_ID"],
                                     $ar["TYPE_ID"], "",
                                     3600);

    // if no such event occurred
    if (!($ar=$rs->Fetch()))
    {
        // add the event!
        CStatEvent::AddCurrent("download", "manual");
    }
}
?>


DecodeGID

CStatEvent::DecodeGID

array
CStatEvent::DecodeGID(
 string gid
)

The method DecodeGID decodes the specified special parameter used with methods CStatEvent::Add, CStatEvent::AddByEvents.

Note
The method will successfully decode the parameters in both encoded and human-readable formats.

Parameters

Parameter | Description
gid | Special parameter.

Return Values

Returns an array in the following format:

Array
(
    [SESSION_ID] => the session ID
    [GUEST_ID] => the visitor ID
    [COUNTRY_ID] => the country ID
    [ADV_ID] => the advertising campaign ID
    [ADV_BACK] => Y - return under the advertising campaign;
                  N - direct hit
    [SITE_ID] => the site ID
)

See Also

  • CStatEvent::GetGID
  • Special event parameter

Example

<?
// decode the special parameter
$arr = CStatEvent::DecodeGID("BITRIX_SM.OTk1LjgyLk4wLjI1Lk4ucnU%3D");

// print the result
echo "<pre>"; print_r($arr); echo "</pre>";
?>


Delete

CStatEvent::Delete

bool
CStatEvent::Delete(
 int event_id
)

The method Delete deletes the specified event.

Parameters

Parameter | Description
event_id | The ID of the event to be deleted.

Return Values

Returns true on success, or false otherwise.

See Also

  • Event

Example

<?
$event_id = 1;
if (CStatEvent::Delete($event_id))
    echo "Event #".$event_id." successfully deleted.";
?>


GetGID

CStatEvent::GetGID

string
CStatEvent::GetGID(
 mixed site_id = false
)

The method GetGID returns the special parameter used for creating events with functions CStatEvent::Add, CStatEvent::AddByEvents.

The special parameter is created using the following parameters of the current visitor:

  • the portal short identifier (from the Statistics module settings);
  • the session ID;
  • the visitor ID;
  • the two-character country identifier;
  • the advertising campaign ID;
  • value of the flag: direct hit or return under the advertising campaign;
  • the two-character site ID.
Depending on the value of the parameter Encode additional parameter #EVENT_GID# for events of the Statistics module settings, the returned parameter may be either in the human-readable or encoded format.

Parameters

Parameter | Description
site_id | The site ID.

See Also

  • CStatEvent::DecodeGID
  • Special event parameter

Example

<?
// the page to which the visitor will be redirected
// after the event is registered.
// e.g. payment system or registration service provider
$goto = "http://www.softkey.ru/catalog/basket.php?prodid=902&"
        "quantity=1&referer1=ritlabs_site&referer2=#EVENT_GID#";

// register event
$goto = eregi_replace("#EVENT_GID#",
                      urlencode(CStatEvent::GetGID()),
                      $goto);
CStatEvent::AddCurrent("softkey", "out", "", "", "", $goto);

// redirect visitor
LocalRedirect($goto);
?>


GetHandlerList

CStatEvent::GetHandlerList

array
CStatEvent::GetHandlerList(
 array &handlers
)

The method GetHandlerList returns a list of CSV file handlers for displaying in the drop-down list using SelectBoxFromArray, or in the multiple selection list using SelectBoxMFromArray.

The CSV file handlers can be custom (their path is specified in the parameter Path to additional handlers for manual event loading in the Statistics module settings), as well as standard (shipped with the module distribution package, located in /bitrix/modules/statistic/loading/).

Parameters

Parameter Description
handlers When the method returns, this variable contains an array of paths (relative to the root) to the custom handlers.

Example of the array:
Array
(
    [0] => /bitrix/php_interface/include/statistic/regnow_alawar.php
    [1] => /bitrix/php_interface/include/statistic/regnow_editable.php
    [2] => /bitrix/php_interface/include/statistic/regsoft_editable.php
    [3] => /bitrix/php_interface/include/statistic/shareit_editable.php
    [4] => /bitrix/php_interface/include/statistic/softkey_editable.php
)

Return Values

The following is the example of the returned array:

Array
(
    [reference] => Array
        (
            [0] => regnow.php
            [1] => regsoft.php
            [2] => shareit_eur.php
            [3] => shareit_usd.php
            [4] => softkey.php
            [5] => [1] regnow_alawar.php
            [6] => [2] regnow_editable.php
            [7] => [3] regsoft_editable.php
            [8] => [4] shareit_editable.php
            [9] => [5] softkey_editable.php
        )

    [reference_id] => Array
        (
            [0] => /bitrix/modules/statistic/loading/regnow.php
            [1] => /bitrix/modules/statistic/loading/regsoft.php
            [2] => /bitrix/modules/statistic/loading/shareit_eur.php
            [3] => /bitrix/modules/statistic/loading/shareit_usd.php
            [4] => /bitrix/modules/statistic/loading/softkey.php
            [5] => /bitrix/php_interface/include/statistic/regnow_alawar.php
            [6] => /bitrix/php_interface/include/statistic/regnow_editable.php
            [7] => /bitrix/php_interface/include/statistic/regsoft_editable.php
            [8] => /bitrix/php_interface/include/statistic/shareit_editable.php
            [9] => /bitrix/php_interface/include/statistic/softkey_editable.php
        )

)

See Also

  • CStatEvent::Add
  • CStatEvent::AddByEvents
  • Creating Events
  • Event

Example

<?
// obtain the list of available handlers
$arrHandlers = CStatEvent::GetHandlerList($arUSER_HANDLERS);

// display the list in the combo box
echo SelectBoxFromArray("handler", $arrHandlers, $handler, " ");
?>


GetList

CStatEvent::GetList

CDBResult
CStatEvent::GetList(
 string &by = "s_id",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of events.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_id - the event ID;
  • s_site_id - the site ID;
  • s_type_id - the event type ID;
  • s_event3 - the event auxiliary parameter event3;
  • s_date_enter - date and time the event was created ;
  • s_adv_id - the advertising campaign ID;
  • s_adv_back - flag: direct hit or return under the advertising campaign;
  • s_session_id - the session ID;
  • s_guest_id - the visitor ID;
  • s_hit_id - the hit ID;
  • s_url - page on which the event was generated;
  • s_referer_url - referring page;
  • s_redirect_url - address of the page to which the visitor was redirected after the event had been registered;
  • s_country_id - the visitor country ID;
  • s_money - amount of money.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the event ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • EVENT_ID* - the event type ID;
  • EVENT_ID_EXACT_MATCH - if "N", entry in the EVENT_ID is sufficient (loose match);
  • EVENT_NAME* - the event type name;
  • EVENT_NAME_EXACT_MATCH - if "Y", the EVENT_NAME must match exactly (strict match);
  • EVENT1* - the event1 event type identifier;
  • EVENT1_EXACT_MATCH - if "Y", the EVENT1 must match exactly (strict match);
  • EVENT2* - the event2 event type identifier;
  • EVENT2_EXACT_MATCH - if "Y", the EVENT2 must match exactly (strict match);
  • EVENT3* - the event auxiliary parameter event3;
  • EVENT3_EXACT_MATCH - if "Y", the EVENT3 must match exactly (strict match);
  • DATE - date and time when the event occurred (exact match);
  • DATE1 - the earliest date of the required events;
  • DATE2 - the latest date of the required events;
  • MONEY - event value (amount of money; exact match);
  • MONEY1 - minimum value of amount of money of the required events;
  • MONEY2 - maximum value of amount of money of the required events;
  • CURRENCY - three-character identifier of the amount currency;
  • SESSION_ID* - the session ID;
  • SESSION_ID_EXACT_MATCH - if "N", entry in the SESSION_ID is sufficient (loose match);
  • GUEST_ID* - the visitor ID;
  • GUEST_ID_EXACT_MATCH - if "N", entry in the GUEST_ID is sufficient (loose match);
  • ADV_ID* - the advertising campaign ID;
  • ADV_ID_EXACT_MATCH - if "N", entry in the ADV_ID is sufficient (loose match);
  • ADV_BACK - flag: direct hit (N) or return (Y) under an advertising campaign;
  • HIT_ID* - the hit ID;
  • HIT_ID_EXACT_MATCH - if "N", entry in the HIT_ID is sufficient (loose match);
  • COUNTRY_ID* - the visitor country ID;
  • COUNTRY_ID_EXACT_MATCH - if "N", entry in the COUNTRY_ID is sufficient (loose match);
  • COUNTRY* - name of the visitor country;
  • COUNTRY_EXACT_MATCH - if "Y", the COUNTRY must match exactly (strict match);
  • REFERER_URL* - the referring page;
  • REFERER_URL_EXACT_MATCH - if "Y", the REFERER_URL must match exactly (strict match);
  • REFERER_SITE_ID - the referring page site ID;
  • URL* - the page on which the event occurred;
  • URL_EXACT_MATCH - if "Y", the URL must match exactly (strict match);
  • SITE_ID - the ID of the site on which the event occurred;
  • REDIRECT_URL* - address of the page to which the visitor was redirected after the event had been registered;
  • REDIRECT_URL_EXACT_MATCH - if "Y", the REDIRECT_URL must match exactly (strict match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => the event ID
    [EVENT3] => the event auxiliary parameter event3
    [TYPE_ID] => the event type ID
    [DATE_ENTER] => the time the event was created
    [EVENT1] => event1 event type identifier
    [EVENT2] => event2 event type identifier
    [NAME] => the event type name
    [EVENT] => event1 / event2, the event type name
               (if specified)
    [DESCRIPTION] => event type description

    [ADV_ID] => the adv. campaign ID
    [ADV_BACK] => flag: direct hit (N) or return (Y)
                        under an advertising campaign
    [COUNTRY_ID] => the visitor country ID
    [COUNTRY_NAME] => name of the visitor country
    [SESSION_ID] => the session ID
    [GUEST_ID] => the visitor ID
    [HIT_ID] => the hit ID

    [REFERER_URL] => the referring page
    [REFERER_SITE_ID] => the referring page site ID
    [URL] => the page on which the event occurred
    [SITE_ID] => the event site ID
    [REDIRECT_URL] => address of the redirect page
                      (after the event had been registered)

    [MONEY] => amount of money
    [CHARGEBACK] => Y - amount of money is negative;
                    N - amount of money is positive
    [CURRENCY] => three-character identifier of the amount currency
)

See Also

  • CStatEvent::GetListByGuest
  • Event

Example

<?
// select all existing events of user #1025
$arFilter = array(
    "GUEST_ID" => "1025"
    );

// obtain the list of records
$rs = CStatEvent::GetList(
    ($by = "s_id"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetListByGuest

CStatEvent::GetListByGuest

CDBResult
CStatEvent::GetListByGuest(
 int guest_id,
 mixed type_id = false,
 mixed event3 = false,
 mixed time = false
)

The method GetListByGuest returns a list of event identifiers by the site visitor ID.

Parameters

Parameter | Description
guest_id | The visitor ID.
type_id | The event type ID. If "false", the returned list is not filtered by the event type.
event3 | The event auxiliary parameter event3. If "false", the returned list is not filtered by event3.
time | Number of seconds elapsed since now. If "false", the returned list is not filtered by time.

Structure of the returned record

Array
(
    [ID] => the event ID
)

See Also

  • CStatEvent::GetList
  • Event
  • Auxiliary event parameter

Example

<?
// register an event of the type
// "CHM file download" (download/manual)
// if it does not exist, it will be created
// register the event using the current visitor parameters

// check if the current visitor tried to download the file
// within the last hour

// get the event type ID
$rs = CStatEventType::GetByEvents($event1, $event2);
if ($ar = $rs->Fetch())
{
    // get all events of this type for the current visitor
    // for the last hour (3600 sec)
    $rs = CStatEvent::GetListByGuest($_SESSION["SESS_GUEST_ID"],
                                     $ar["TYPE_ID"], "", 3600);

    // if no such event occurred
    if (!($ar=$rs->Fetch()))
    {
        // add the event!
        CStatEvent::AddCurrent("download", "manual");
    }
}
?>


CStatEventType

The CStatEventType is the class used with event types.

Methods

Method | Description
ConditionSet | Returns the event type by the specified identifiers, or creates a new one if no such event type exists.
Delete | Deletes the specified event type.
GetByEvents | Retrieves the event type by the specified identifiers.
GetByID | Returns information on the specified event type.
GetDropdownList | Returns a list of event types for use in drop-down lists (the SelectBox function), or in multiple selection lists (the SelectBoxM function).
GetDynamicList | Returns the number of events of the specified type, on daily basis.
GetList | Returns a list of event types.
GetSimpleList | Returns a brief list of event types.

See Also

  • The event types report


ConditionSet

CStatEventType::ConditionSet

int
CStatEventType::ConditionSet(
 string event1,
 string event2,
 array &type
)

The method ConditionSet returns the event type by the specified identifiers, or creates a new one if no such event type exists.

Parameters

Parameter | Description
event1 | The event1 event type identifier.
event2 | The event2 event type identifier.
type Reference to an array describing the event type. The array has the following format:
Array
(
    [TYPE_ID] => the event type ID
    [DYNAMIC_KEEP_DAYS] => days to keep statistical information
                           on this event type, on daily basis
    [KEEP_DAYS] => days to keep events of this type
    [DATE_ENTER_STR] => the date the event was created
)

Return Values

Returns the ID of the existing or new event.

See Also

  • CStatEventType::GetByEvents
  • CStatEventType::GetByID
  • Event type

Example

<?
// obtain the ID of the event type "softkey/order"
// or create a new one
$TYPE_ID =
    CStatEventType::ConditionSet("softkey",
                                 "order", $arEventType);
?>


Delete

CStatEventType::Delete

bool
CStatEventType::Delete(
 int type_id
)

The method Delete deletes the specified event type and all events of this type.

Parameters

Parameter | Description
type_id | The event type ID.

Return Values

Returns true on success, or false otherwise.

See Also

  • Event type

Example

<?
$type_id = 1;
if (CStatEventType::Delete($type_id))
    echo "Event type #".$type_id." has been deleted.";
?>


GetByEvents

CStatEventType::GetByEvents

CDBResult
CStatEventType::GetByEvents(
 string event1,
 string event2
)

The method GetByEvents retrieves the event type by the specified identifiers.

Parameters

Parameter | Description
event1 | The event1 event type identifier.
event2 | The event2 event type identifier.

Structure of the returned record

Array
(
    [TYPE_ID] => the event type ID
    [DYNAMIC_KEEP_DAYS] => days to keep statistical information
                           on this event type, on daily basis
    [KEEP_DAYS] => days to keep events of this type
    [DATE_ENTER_STR] => the date the event was created
)

See Also

  • CStatEventType::ConditionSet
  • Event type

Example

<?
// register an event of the type
// "CHM file download" (download/manual)
// if it does not exist, it will be created
// register the event using the current visitor parameters

// check if the current visitor tried to download the file
// within the last hour

// get the event type ID
$rs = CStatEventType::GetByEvents($event1, $event2);
if ($ar = $rs->Fetch())
{
    // get all events of this type for the current visitor
    // for the last hour (3600 sec)
    $rs = CStatEvent::GetListByGuest($_SESSION["SESS_GUEST_ID"],
                                     $ar["TYPE_ID"], "", 3600);

    // if no such event occurred
    if (!($ar = $rs->Fetch()))
    {
        // add the event!
        CStatEvent::AddCurrent("download", "manual");
    }
}
?>


GetByID

CStatEventType::GetByID

CDBResult
CStatEventType::GetByID(
 int type_id
)

The method GetByID returns information on the specified event type.

Parameters

Parameter | Description
type_id | The event type ID.

Structure of the returned record

Array
(
    [ID] => the event type ID
    [EVENT1] => the event1 identifier of the event type
    [EVENT2] => the event2 identifier of the event type
    [NAME] => the event type name
    [EVENT] => event1 / event2, or the type name if specified
    [DESCRIPTION] => the event type description
    [MONEY] => total amount of money for this event type
    [DATE_ENTER] => the date the event was created
    [DATE_CLEANUP] => the date the statistical information
                      on this event type was cleaned up, on daily basis
    [C_SORT] => sort order
    [COUNTER] => counter to keep the number of events of this type
    [ADV_VISIBLE] => [Y|N] flag: whether to include statistics on this
                                 event type in adv. campaign reports
    [KEEP_DAYS] => days to keep events of this type
    [DYNAMIC_KEEP_DAYS] => days to keep statistical information
                           on this event type, on daily basis
    [DIAGRAM_DEFAULT] => [Y|N] flag: whether to include this event type
                                     in charts and graphs by default
)

See Also

  • CStatEventType::GetByEvents
  • CStatEventType::ConditionSet
  • Event type

Example

<?
$type_id = 1;
if ($rs = CStatEventType::GetByID($type_id))
{
    $ar = $rs->Fetch();
    // print the event type parameters
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetDropdownList

CStatEventType::GetDropdownList

CDBResult
CStatEventType::GetDropdownList(
 string order = "ORDER BY EVENT1, EVENT2"
)

The method GetDropdownList returns a list of event types for use in drop-down lists (the SelectBox function), or in multiple selection lists (the SelectBoxM function).

Parameters

Parameter | Description
order | The SQL code that can be used to set arbitrary sorting of the event type list.

Structure of the returned record

Array
(
    [REFERENCE_ID] => the event type ID
    [REFERENCE] => "[ID] (event1 / event2) event type name"
)

See Also

  • CStatEventType::GetList
  • CStatEventType::GetSimpleList
  • Event type

Example

<?
// single selection list
echo SelectBox(
    "SEARCHER_ID",
    CStatEventType::GetDropdownList(),
    "",
    intval($SEARCHER_ID)
    );

// multiple selection list box with 20 visible items
echo SelectBoxM(
    "arSEARCHER_ID[]",
    CStatEventType::GetDropdownList(),
    $arSEARCHER_ID,
    "",
    false,
    20
    );
?>


GetDynamicList

CStatEventType::GetDynamicList

CDBResult
CStatEventType::GetDynamicList(
 int type_id,
 string &by = "s_date",
 string &order = "desc",
 array max_min,
 array filter
)

The method GetDynamicList returns the number of events of the specified type, on daily basis.

Parameters

Parameter | Description
type_id | The event type ID.
by Sorting field; possible values:
  • s_date - date.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
max_min Reference to an array containing minimum and maximum dates of the returned list. The array has the following structure:
Array
(
    [DATE_FIRST] => minimum date
    [MIN_DAY] => day of the minimum date (1-31)
    [MIN_MONTH] => month of the minimum date (1-12)
    [MIN_YEAR] => year of the minimum date

    [DATE_LAST] => maximum date
    [MAX_DAY] => day of the maximum date (1-31)
    [MAX_MONTH] => month of the maximum date (1-12)
    [MAX_YEAR] => year of the maximum date
)
filter Array used to filter the resulting list. The following keys can be used in the array:
  • DATE1 - earliest date and time of the time period for which the information is to be returned;
  • DATE2 - latest date and time of the time period.

Structure of the returned record

Array
(
    [DATE_STAT] => date
    [DAY] => day (1-31)
    [MONTH] => month (1-12)
    [YEAR] => year
    [COUNTER] => number of events of this type
                 for the specified date
)

See Also

  • CStatEventType::GetList
  • CStatEventType::GetSimpleList

Example

<?
$type_id = 1;

// set the filter for December 2005
$arFilter = array(
    "DATE1" => "01.12.2005",
    "DATE2" => "31.12.2005"
    );

// obtain the list of records
$rs = CStatEventType::GetDynamicList(
    $type_id,
    ($by="s_date"),
    ($order="desc"),
    $arMaxMin,
    $arFilter
    );

// print the date array
echo "<pre>"; print_r($arMaxMin); echo "</pre>";

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CStatEventType::GetList

CDBResult
CStatEventType::GetList(
 string &by = "s_today_counter",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered,
 mixed limit = false
)

The method GetList returns a list of event types.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_id - the event type ID;
  • s_date_last - the date of the last event of this type;
  • s_date_enter - the date of the first event of this type;
  • s_today_counter - number of events of this type for today;
  • s_yesterday_counter - number of events of this type for yesterday;
  • s_b_yesterday_counter - number of events of this type for day before yesterday;
  • s_total_counter - total number of events of this type;
  • s_period_counter - number of events of this type for the specified period (filter[DATE1_PERIOD], filter[DATE2_PERIOD]);
  • s_name - the event type name;
  • s_event1 - the event1 identifier of the event type;
  • s_event2 - the event2 identifier of the event type;
  • s_event12 - sort by "EVENT1, EVENT2";
  • s_chart - sort by "DIAGRAM_DEFAULT desc, TOTAL_COUNTER";
  • s_stat - sort by "TODAY_COUNTER desc, YESTERDAY_COUNTER desc, B_YESTERDAY_COUNTER desc, TOTAL_COUNTER desc, PERIOD_COUNTER".
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the event type ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • EVENT1* - the event1 event type identifier;
  • EVENT1_EXACT_MATCH - if "Y", the EVENT1 must match exactly (strict match);
  • EVENT2* - the event2 event type identifier;
  • EVENT2_EXACT_MATCH - if "Y", the EVENT2 must match exactly (strict match);
  • NAME* - the event type name;
  • NAME_EXACT_MATCH - if "Y", the NAME must match exactly (strict match);
  • DESCRIPTION* - the event type description;
  • DESCRIPTION_EXACT_MATCH - if "Y", the DESCRIPTION must match exactly (strict match);
  • DATE_ENTER_1 - the earliest date when the first event of the required type occurred;
  • DATE_ENTER_2 - the latest date when the first event of the required type occurred;
  • DATE_LAST_1 - the earliest date when the last event of the required type occurred;
  • DATE_LAST_2 - the latest date when the last event of the required type occurred;
  • DATE1_PERIOD - the earliest date of an arbitrary period;
  • DATE2_PERIOD - the latest date of an arbitrary period;
  • COUNTER1 - minimum value of the range to match against the field "total number of events of this type";
  • COUNTER2 - maximum value of the range to match against the field "total number of events of this type";
  • ADV_VISIBLE - flag: whether to include information on this event type in the advertising campaign report [Y/N];
  • DIAGRAM_DEFAULT - flag: whether to include this event type in charts and graphs by default [Y/N];
  • KEEP_DAYS1 - minimum value of the range to match against the field "days to keep events of this type";
  • KEEP_DAYS2 - maximum value of the range to match against the field "days to keep events of this type";
  • DYNAMIC_KEEP_DAYS1 - minimum value of the range to match against the field "days to keep information on events of this type on daily basis";
  • DYNAMIC_KEEP_DAYS2 - maximum value of the range to match against the field "days to keep information on events of this type on daily basis";
  • MONEY1 - minimum value of amount of money of the events of this type;
  • MONEY2 - maximum value of amount of money of the events of this type;
  • CURRENCY - three-character identifier of the amount currency;
  • GROUP - how to group the resulting list; possible values:
    • event1 - grouping by event1;
    • event2 - grouping by event2.
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.
limit | Maximum number of event types to return. If set to false, the number of event types will be limited to that specified in the parameter Maximum number of records displayed in tables in the Statistics module settings.

Structure of the returned record

Depending on how the list is grouped, the returned record structure may vary.

  • grouping by event1 (filter["GROUP"]="event1"):
    Array
(
    [EVENT1] => the event1 event type identifier
    [DATE_ENTER] => the date of the first event whose type
                    equals to the event1 identifier
    [DATE_LAST] => the date of the last event whose type
                   equals to the event1 identifier
    [TOTAL_COUNTER] => total number of events
    [TODAY_COUNTER] => total number of events for today
    [YESTERDAY_COUNTER] => total number of events for yesterday
    [B_YESTERDAY_COUNTER] => total number of events for the day before yesterday
    [PERIOD_COUNTER] => total number of events for the time period
                        (filter[DATE1_PERIOD], filter[DATE2_PERIOD])
    [TOTAL_MONEY] => total amount of money
    [TODAY_MONEY] => total amount of money for today
    [YESTERDAY_MONEY] => total amount of money for yesterday
    [B_YESTERDAY_MONEY] => total amount of money for the day before yesterday
    [PERIOD_MONEY] => total amount of money for the time period
                      (filter[DATE1_PERIOD], filter[DATE2_PERIOD])
    [CURRENCY] => three-character identifier of the amount currency
)
  • grouping by event2 (filter["GROUP"]="event2"):
    Array
(
    [EVENT2] => the event2 event type identifier;
    [DATE_ENTER] => the date of the first event whose type
                    equals to the event2 identifier
    [DATE_LAST] => the date of the last event whose type
                   equals to the event2 identifier
    [TOTAL_COUNTER] => total number of events
    [TODAY_COUNTER] => total number of events for today
    [YESTERDAY_COUNTER] => total number of events for yesterday
    [B_YESTERDAY_COUNTER] => total number of events for the day before yesterday
    [PERIOD_COUNTER] => total number of events for the time period
                        (filter[DATE1_PERIOD], filter[DATE2_PERIOD])
    [TOTAL_MONEY] => total amount of money
    [TODAY_MONEY] => total amount of money for today
    [YESTERDAY_MONEY] => total amount of money for yesterday
    [B_YESTERDAY_MONEY] => total amount of money for the day before yesterday
    [PERIOD_MONEY] => total amount of money for the time period
                      (filter[DATE1_PERIOD], filter[DATE2_PERIOD])
    [CURRENCY] => three-character identifier of the amount currency
)
  • without grouping:
    Array
(
    [ID] => the event type ID
    [EVENT1] => the event1 event type identifier
    [EVENT2] => the event2 event type identifier
    [DIAGRAM_DEFAULT] => flag: whether to include this event type
                         in charts and graphs by default [Y/N];
    [NAME] => the event type name
    [EVENT] => event1 / event2, the event type name
               (if specified)
    [DESCRIPTION] => the event type description
    [TOTAL_COUNTER] => total number of events of this type
    [TODAY_COUNTER] => total number of events of this type for today
    [YESTERDAY_COUNTER] => total number of events of this type for yesterday
    [B_YESTERDAY_COUNTER] => total number of events of this type
                             for the day before yesterday
    [PERIOD_COUNTER] => total number of events of this type for the time period
                        (filter[DATE1_PERIOD], filter[DATE2_PERIOD])
    [TOTAL_MONEY] => total amount of money for this type of event
    [TODAY_MONEY] => total amount of money for this type of event for today
    [YESTERDAY_MONEY] => total amount of money for this type of event for yesterday
    [B_YESTERDAY_MONEY] => total amount of money for this type of event
                           for the day yesterday
    [PERIOD_MONEY] => total amount of money for this type of event for the time period
                      (filter[DATE1_PERIOD], filter[DATE2_PERIOD])
    [CURRENCY] => three-character identifier of the amount currency
)

See Also

  • CStatEventType::GetDynamicList
  • CStatEventType::GetSimpleList
  • Event type

Example

<?
// obtain information only on those event types
// whose event1 = "download"
// also obtain extra data on December 2005
$arFilter = array(
    "DATE1_PERIOD" => "01.12.2005",
    "DATE2_PERIOD" => "31.12.2005",
    "EVENT1"       => "download"
    );

// obtain the list of records
$rs = CStatEventType::GetList(
    ($by = "s_today_counter"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetSimpleList

CStatEventType::GetSimpleList

CDBResult
CStatEventType::GetSimpleList(
 string &by = "s_event1",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetSimpleList returns a brief list of event types.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_id - the event type ID;
  • s_event1 - the event1 identifier of the event type;
  • s_event2 - the event2 identifier of the event type;
  • s_name - the event type name;
  • s_description - event type description.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the event type ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • EVENT1* - the event1 event type identifier;
  • EVENT1_EXACT_MATCH - if "Y", the EVENT1 must match exactly (strict match);
  • EVENT2* - the event2 event type identifier;
  • EVENT2_EXACT_MATCH - if "Y", the EVENT2 must match exactly (strict match);
  • NAME* - the event type name;
  • NAME_EXACT_MATCH - if "Y", the NAME must match exactly (strict match);
  • DESCRIPTION* - event type description;
  • DESCRIPTION_EXACT_MATCH - if "Y", the DESCRIPTION must match exactly (strict match);
  • KEYWORDS - event1, event2, name and description of the event type;
  • KEYWORDS_EXACT_MATCH - if "Y", the KEYWORDS must match exactly (strict match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [ID] => the event type ID
    [EVENT1] => the event1 identifier of the event type
    [EVENT2] => the event2 identifier of the event type
    [NAME] => the event type name
    [EVENT] => event1 / event2, the event type name if specified
    [DESCRIPTION] => event type description
)

See Also

  • CStatEventType::GetDynamicList
  • CStatEventType::GetList
  • Event type

Example

<?
// select only those event types whose event1 = "download"
$arFilter = array(
    "EVENT1" => "download"
    );

// obtain the list of records
$rs = CStatEventType::GetSimpleList(
    ($by="s_event2"),
    ($order="desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CStatistics

The CStatistics class contains basic methods used with the Statistic module.

Methods

Method | Description
CleanUp | Erases collected statistical data.
Keep | Enables collecting all the statistical data.

See Also

  • Overview of the Statistics module


CleanUp

CStatistics::CleanUp

bool
CStatistics::CleanUp(
 string date = "",
 array &errors
)

The method CleanUp erases collected statistical data.

Parameters

Parameter | Description
date | Date (in the format of the current site or language) up to which the statistics is to be erased. If an empty string is passed in this parameter all the collected data will be erased.
errors | If the date parameter is empty, this variable will contain all errors that may occur during the statistics clean-up.

Return Values

The method returns "true" on success, or "false" otherwise.

See Also

  • The Statistics module settings

Example

<?
// date (in the format of the current site or language)
// up to which the statistics is to be erased
$date = "31.12.2005";

// erase
CStatistics::CleanUp($date);
?>


Keep

CStatistics::Keep

CStatistics::Keep(
 bool handle_call = false
)

The method Keep enables collecting all the statistical data.

If the Statistics module is installed, this method is automatically called in the prologue. At the same time, you can disable automatic call of this method in the prologue by initialising the constant STOP_STATISTICS before the prologue is included. After that, this method can be called with handle_call set to true.

Parameters

Parameter | Description
handle_call | If the value of this parameter is true, the method will ignore the constant STOP_STATISTICS and continue execution.

See Also

  • STOP_STATISTICS constant
  • NO_KEEP_STATISTIC constant

Example

<?
// disable automatic collection of the statistics in the prologue
define("STOP_STATISTICS", true);
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

// start collecting the statistics manually
CStatistics::Keep(true);

...

?>


CStopList

The CStopList class is used with the stop list.

Methods

Method | Description
Check | Checks if the current visitor matches one of the stop list records.
GetByID | Returns information on the stop list records.
GetList | Returns a list of the stop list records.

See Also

  • The stop list form


Check

CStopList::Check

mixed
CStopList::Check(
 string test = "N",
 mixed params = false
)

The method Check checks if the current visitor matches one of the stop list records. This method is called automatically in the prologue on each hit.

Parameters

Parameter Description
test There can be situations when you may happen to add yourself to the stop list. To avoid this, the system first adds a test record to the stop list, then checks if the current visitor matches this test record. If the visitor does not match, the method deletes the test record.

If this method is called with test="Y", it will only check if the current visitor matches test records of the stop list. If this method is called with test="N" (the default value), it will check if the visitor matches all the records of the stop list except the test ones.
params Optional array of parameters that can be used to check if the visitor matches the stop list. The following keys are possible in this array:
  • IP - the IP address in the format XXX.XXX.XXX.XXX;
  • USER_AGENT - the UserAgent (full or partial string);
  • URL_FROM - the referring page;
  • URL_TO - the target page;
  • SITE_ID - the site ID.

Return Values

The method returns the ID of the matching stop list record, or false otherwise.

See Also

  • Stop list
  • Stop list subnet musk

Example

<?
// set the visitor parameters for checking in the stop list
$arParams = array(
    "IP" => "192.168.0.1",
    "USER_AGENT" => "Firefox"
    );

$record_id = CStopList::Check("N", $arParams);
if (intval($record_id)>0)
    echo "Matching record #".intval($record_id);
?>


GetByID

CStopList::GetByID

CDBResult
CStopList::GetByID(
 int record_id
)

The method GetByID returns information on the stop list records.

Parameters

Parameter | Description
record_id | The ID of the stop list record.

Structure of the returned record

Array
(
    [ID] => the record ID
    [TIMESTAMP_X] => modification time
    [DATE_START] => date and time of record activation
    [DATE_END] => date and time of record deactivation
    [ACTIVE] => "Y" - record is active; "N" - record is inactive
    [SAVE_STATISTIC] => "Y" - keep statistics of the visitor
                        added to the stop list;
                        "N" - don't keep
    [IP_1] => the octet 1 of the IP address
    [IP_2] => the octet 2 of the IP address
    [IP_3] => the octet 3 of the IP address
    [IP_4] => the octet 4 of the IP address
    [MASK_1] => the octet 1 mask of the IP address
    [MASK_2] => the octet 2 mask of the IP address
    [MASK_3] => the octet 3 mask of the IP address
    [MASK_4] => the octet 4 mask of the IP address
    [USER_AGENT] => the visitor UserAgent
    [USER_AGENT_IS_NULL] => "Y" - the visitor UserAgent is not specified (empty);
                            "N" - specified (default)
    [URL_TO] => the target page URL (or its part)
    [URL_FROM] => the referring page URL (or its part)
    [MESSAGE] => text of the message which will
                 be displayed to the site visitor
                 if they match this stop list record
    [MESSAGE_LID] => language of the message in the field [MESSAGE]
    [URL_REDIRECT] => the page to which the visitor is to be
                      redirected after it have been found in the stop list
    [COMMENTS] => administrator's comment;
                  commonly used to explain reasons for creating the record
    [TEST] => "Y" - this is a test record;
              "N" - this is not a test record
              (see also: CStopList::Check)
    [SITE_ID] => the ID of the site for which the record is effective;
                 if not specified, the record is effective for all sites
    [LAMP] => "green" - the record is active and effective;
              "red" - the record is inactive (expired or became inactive)
)

See Also

  • Stop list

Example

<?
$stop_id = 1;
if ($rs = CStopList::GetByID($stop_id))
{
    $ar = $rs->Fetch();
    // print the stop list record parameters
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


GetList

CStopList::GetList

CDBResult
CStopList::GetList(
 string &by = "s_id",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of the stop list records.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_id - the record ID;
  • s_date_start - date and time of record activation;
  • s_date_end - date and time of record deactivation;
  • s_site_id - the ID of the site for which the record is effective;
  • s_active - active state flag of the record;
  • s_save_statistic - flag: whether to keep statistics of the visitor added to the stop list [Y/N];
  • s_ip - the visitor IP address;
  • s_mask - the visitor IP address mask;
  • s_url_to - the target page URL;
  • s_url_from - the referring page URL.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the session ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • DATE_START_1 - the earliest date when the required records became active;
  • DATE_START_2 - the latest date when the required records became active;
  • DATE_END_1 - the earliest date when the required records became inactive;
  • DATE_END_2 - the latest date when the required records became inactive;
  • ACTIVE - active state flag of the record; possible values:
    • Y - record is active;
    • N - record is inactive.
  • SAVE_STATISTIC - flag: whether to keep statistics of the visitor added to the stop list [Y/N];
  • IP_1* - the octet 1 of the IP address;
  • IP_1_EXACT_MATCH - if "N", entry in the IP_1 is sufficient (loose match);
  • IP_2* - the octet 2 of the IP address;
  • IP_2_EXACT_MATCH - if "N", entry in the IP_2 is sufficient (loose match);
  • IP_3* - the octet 3 of the IP address;
  • IP_3_EXACT_MATCH - if "N", entry in the IP_3 is sufficient (loose match);
  • IP_4* - the octet 4 of the IP address;
  • IP_4_EXACT_MATCH - if "N", entry in the IP_4 is sufficient (loose match);
  • URL_FROM* - the referring page URL;
  • URL_FROM_EXACT_MATCH - if "Y", the URL_FROM must match exactly (strict match);
  • USER_AGENT* - the visitor UserAgent;
  • USER_AGENT_EXACT_MATCH - if "Y", the USER_AGENT must match exactly (strict match);
  • MESSAGE* - text of the message which will be displayed to the site visitor if they match this stop list record;
  • MESSAGE_EXACT_MATCH - if "Y", the MESSAGE must match exactly (strict match);
  • COMMENTS* - administrator's comment; commonly used to explain reasons for creating the record;
  • COMMENTS_EXACT_MATCH - if "Y", the COMMENTS must match exactly (strict match);
  • URL_TO* - the target page URL (or its part);
  • URL_TO_EXACT_MATCH - if "Y", the URL_TO must match exactly (strict match);
  • URL_REDIRECT* - the page to which the visitor is to be redirected after it have been found in the stop list;
  • URL_REDIRECT_EXACT_MATCH - if "Y", the URL_REDIRECT must match exactly (strict match);
  • SITE_ID* - the ID of the site for which the record is effective; if not specified, the record is effective for all sites;
  • SITE_ID_EXACT_MATCH - if "N", entry in the SITE_ID is sufficient (loose match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.

Structure of the returned record

Array
(
    [DATE_START] => date and time of record activation
    [DATE_END] => date and time of record deactivation
    [ACTIVE] => "Y" - record is active; "N" - record is inactive
    [SAVE_STATISTIC] => "Y" - keep statistics of the visitor
                        added to the stop list;
                        "N" - don't keep
    [IP_1] => the octet 1 of the IP address
    [IP_2] => the octet 2 of the IP address
    [IP_3] => the octet 3 of the IP address
    [IP_4] => the octet 4 of the IP address
    [MASK_1] => the octet 1 mask of the IP address
    [MASK_2] => the octet 2 mask of the IP address
    [MASK_3] => the octet 3 mask of the IP address
    [MASK_4] => the octet 4 mask of the IP address
    [USER_AGENT] => the visitor UserAgent
    [USER_AGENT_IS_NULL] => "Y" - the visitor UserAgent is not specified (empty);
                            "N" - specified (default)
    [URL_TO] => the target page URL (or its part)
    [URL_FROM] => the referring page URL (or its part)
    [MESSAGE] => text of the message which will
                 be displayed to the site visitor
                 if they match this stop list record
    [MESSAGE_LID] => language of the message in the field [MESSAGE]
    [URL_REDIRECT] => the page to which the visitor is to be
                      redirected after it have been found in the stop list
    [COMMENTS] => administrator's comment;
                  commonly used to explain reasons for creating the record
    [TEST] => "Y" - this is a test record;
              "N" - this is not a test record
              (see also: CStopList::Check)
    [SITE_ID] => the ID of the site for which the record is effective;
                 if not specified, the record is effective for all sites
    [LAMP] => "green" - the record is active and effective;
              "red" - the record is inactive (expired or became inactive)
)

See Also

  • Stop list

Example

<?
// select stop list records with IP addresses 192.168.0.xxx
$arFilter = array(
    "IP_1" => 192,
    "IP_2" => 168,
    "IP_3" => 0
    );

// obtain the list of records
$rs = CStopList::GetList(
    ($by = "s_id"),
    ($order = "desc"),
    $arFilter,
    $is_filtered
    );

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


CTraffic

The CTraffic class helps obtain information on the site attendance.

Methods

Method | Description
GetCommonValues | Returns the number of hits, hosts, sessions, visitors and events: for the whole time of keeping statistics, for the last 3 days, or for the specified period.
GetDailyList | Returns the number of hits, hosts, sessions, visitors, events; rates of visitors' attentiveness on daily basis.
GetPhraseList | Returns the number of search phrases: for the whole time of keeping statistics, for the last 3 days, or for the specified period.
GetRefererList | Returns the number of referring sites: for the whole time of keeping statistics, for the last 3 days, or for the specified period.
GetSumList | Returns the number of hits, hosts, sessions, visitors, events on hourly, daily or monthly basis.

See Also

  • The Statistics summary report
  • The Site traffic report


GetCommonValues

CTraffic::GetCommonValues

array
CTraffic::GetCommonValues(
 array filter = array()
)

The method GetCommonValues returns the number of hits, hosts, sessions, visitors, events: for the whole time of keeping statistics, for the last 3 days, or for the specified period.

Note
When filtering by site (filter[SITE_ID]), you can retrieve information only on hits, hosts, sessions, events. No information on visitors will be available since the current version of the module assumes a single visitor for the portal.

Parameters

Parameter Description
filter Array used to filter the resulting list. The following keys can be used in the array:
  • SITE_ID - the ID of the site whose statistics is to be obtained;
  • DATE1 - starting date;
  • DATE2 - ending date.

Return Values

If filtering by site, the format of a returned array is the following:

Array
(
    [TOTAL_HITS] => total number of hits (for the whole period of keeping statistics)
    [TOTAL_SESSIONS] => total number of sessions (-//-)
    [TOTAL_EVENTS] => total number of events (-//-)
    [TOTAL_HOSTS] => total number of hosts (-//-)
    [TOTAL_GUESTS] => total number of visitors (-//-)
    [TOTAL_FAVORITES] => total number of visitors who added to Favorites (-//-)

    [TODAY_HITS] => today's hits
    [TODAY_SESSIONS] => today's sessions
    [TODAY_EVENTS] => today's events
    [TODAY_HOSTS] => today's hosts
    [TODAY_GUESTS] => today's visitors
    [TODAY_NEW_GUESTS] => today's new visitors
    [TODAY_FAVORITES] => today's visitors who added to Favorites

    [YESTERDAY_HITS] => yesterday's hits
    [YESTERDAY_SESSIONS] => yesterday's sessions
    [YESTERDAY_EVENTS] => yesterday's events
    [YESTERDAY_HOSTS] => yesterday's hosts
    [YESTERDAY_GUESTS] => yesterday's visitors
    [YESTERDAY_NEW_GUESTS] => yesterday's new visitors
    [YESTERDAY_FAVORITES] => yesterday's visitors who added to Favorites

    [B_YESTERDAY_HITS] => number of hits for day before yesterday
    [B_YESTERDAY_SESSIONS] => number of sessions -//-
    [B_YESTERDAY_EVENTS] => number of events -//-
    [B_YESTERDAY_HOSTS] => number of hosts -//-
    [B_YESTERDAY_GUESTS] => number of visitors -//-
    [B_YESTERDAY_NEW_GUESTS] => number of new visitors -//-
    [B_YESTERDAY_FAVORITES] => number of visitors who added to Favorites -//-

    [PERIOD_HITS] => number of hits for the specified period
                     (filter[DATE1], filter[DATE2])
    [PERIOD_SESSIONS] => number of sessions -//-
    [PERIOD_EVENTS] => number of events -//-
    [PERIOD_NEW_GUESTS] => number of visitors -//-
    [PERIOD_FAVORITES] => number of visitors who added to Favorites -//-

    [ONLINE_GUESTS] => number of online visitors
)

See Also

  • CUserOnline::GetGuestCount
  • The Statistics Summary report

Example

<?
// obtain traffic information
$arr = CTraffic::GetCommonValues();

echo "total hits: ".$arr["TOTAL_HITS"];
echo "today's hits: ".$arr["TODAY_HITS"];

echo "total hosts: ".$arr["TOTAL_HOSTS"];
echo "today's hosts: ".$arr["TODAY_HOSTS"];

echo "total visitors: ".$arr["TOTAL_GUESTS"];
echo "today's visitors: ".$arr["TODAY_GUESTS"];
echo "on-line visitors: ".$arr["ONLINE_GUESTS"];
?>


GetDailyList

CTraffic::GetDailyList

CDBResult
CTraffic::GetDailyList(
 string &by = "s_date",
 string &order = "desc",
 array &max_min,
 array filter = array(),
 bool &is_filtered,
 string get_maxmin = "Y"
)

The method GetDailyList returns the number of hits, hosts, sessions, visitors, events; rates of visitors' attentiveness on daily basis.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_id - the record ID;
  • s_date - date;
  • s_hits - hit count;
  • s_hosts - host count;
  • s_sessions - session count;
  • s_events - event count;
  • s_guests - visitor count;
  • s_new_guests - number of new visitors ;
  • s_favorites - number of visitors who added to Favorites.
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
max_min Reference to an array containing minimum and maximum dates of the returned list. The array has the following structure:
Array
(
    [DATE_FIRST] => minimum date
    [MIN_DAY] => day of the minimum date (1-31)
    [MIN_MONTH] => month of the minimum date (1-12)
    [MIN_YEAR] => year of the minimum date

    [DATE_LAST] => maximum date
    [MAX_DAY] => day of the maximum date (1-31)
    [MAX_MONTH] => month of the maximum date (1-12)
    [MAX_YEAR] => year of the maximum date
)
filter Array used to filter the resulting list. The following keys can be used in the array:
  • ID* - the record ID;
  • ID_EXACT_MATCH - if "N", entry in the ID is sufficient (loose match);
  • DATE1 - the earliest date and time of the time period for which the information is to be returned;
  • DATE2 - the latest date and time of the time period;
  • HITS_1 - minimum value of the "hit count" field;
  • HITS_2 - maximum value -//-;
  • HOSTS_1 - minimum value of the "hosts count" field;
  • HOSTS_2 - maximum value -//-;
  • SESSIONS_1 - minimum value of the "session count" field;
  • SESSIONS_2 - maximum value -//-;
  • EVENTS_1 - minimum value of the "event count" field;
  • EVENTS_2 - maximum value -//-;
  • GUESTS_1 - minimum value of the "visitor count" field;
  • GUESTS_2 - maximum value -//-;
  • NEW_GUESTS_1 - minimum value of the "new visitor count" field;
  • NEW_GUESTS_2 - maximum value -//-;
  • FAVORITES_1 - minimum value of the "number of visitors who added to favorites" field;
  • FAVORITES_2 - maximum value -//-;
  • SITE_ID* - the site ID;
  • SITE_ID_EXACT_MATCH - if "N", entry in the SITE_ID is sufficient (loose match).
* - complex logic allowed.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.
get_maxmin | If set to "Y", on method return, the parameter max_min will contain an array of max and min dates of the returned list.

Structure of the returned record

Array
(
    [ID] => the record ID
    [DATE_STAT] => date
    [DAY] => day (1-31)
    [MONTH] => month (1-12)
    [YEAR] => year
    [WDAY] => day of week
              (0 - Monday,
               1 - Tuesday, ...
               6 - Sunday)
    [HITS] => hit count
    [C_HOSTS] => host count
    [SESSIONS] => session count
    [C_EVENTS] => event count
    [GUESTS] => visitor count
    [NEW_GUESTS] => new visitor count
    [FAVORITES] => number of visitors who added to Favorites.
    [TOTAL_HOSTS] => host count
    [AM_AVERAGE_TIME] => average duration of session
    [AM_1] => number of sessions with duration < 1 min.
    [AM_1_3] => number of sessions with duration from 1 to 3 min.
    [AM_3_6] => -//- from 3 to 6 min.
    [AM_6_9] => -//- from 6 to 9 min.
    [AM_9_12] => -//- from  to  min.
    [AM_12_15] => -//- from  to  min.
    [AM_15_18] => -//- from  to  min.
    [AM_18_21] => -//- from  to  min.
    [AM_21_24] => -//- from  to  min.
    [AM_24] => -//- over 24 min.
    [AH_AVERAGE_HITS] => average hits per session
    [AH_1] => number of sessions with only 1 hit
    [AH_2_5] => number of sessions with 2 to 5 hits
    [AH_6_9] => -//- 6 to 9 hits
    [AH_10_13] => -//- 10 to 13 hits
    [AH_14_17] => -//- 14 to 17 hits
    [AH_18_21] => -//- 18 to 21 hits
    [AH_22_25] => -//- 22 to 25 hits
    [AH_26_29] => -//- 26 to 29 hits
    [AH_30_33] => -//- 30 to 33 hits
    [AH_34] => -//-  over 34 hits
)

See Also

  • CTraffic::GetCommonValues
  • The Site Traffic report

Example

<?
// select data for December 2005
$arFilter = array(
    "DATE1" => "01.12.2005",
    "DATE2" => "31.12.2005"
    );

// get traffic statistics
$rsDays = CTraffic::GetDailyList(
    ($by="s_date"),
    ($order="desc"),
    $arMaxMin,
    $arFilter,
    $is_filtered
    );

while ($arDay = $rsDays->Fetch())
{
    echo "date: ".$arDay["DATE_STAT"]."<br>";
    echo "hits: ".$arDay["HITS"]."<br>";
    echo "hosts: ".$arDay["C_HOSTS"]."<br>";
    echo "sessions: ".$arDay["SESSIONS"]."<br>";
    echo "events: ".$arDay["C_EVENTS"]."<br>";
    echo "visitors: ".$arDay["GUESTS"]."<br>";
}
?>


GetPhraseList

CTraffic::GetPhraseList

CDBResult
CTraffic::GetPhraseList(
 string &by = "s_today",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered,
 mixed limit = 10,
)

The method GetPhraseList returns the number of search phrases: for the whole time of keeping statistics, for the last 3 days, or for the specified period.

Parameters

Parameter | Description
by Sorting field; possible values:
  • s_phrase - the search phrase;
  • s_today - number of today's search phrases;
  • s_yesterday - number of yesterday's search phrases;
  • s_bef_yesterday - number of search phrases for day before yesterday;
  • s_total - total number of search phrases;
  • s_period - number of search phrases for the specified period (filter[DATE1], filter[DATE2]).
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • SITE_ID - the ID of the site whose information is required;
  • DATE1 - starting date;
  • DATE2 - ending date.
is_filtered | If this flag contains "true" on return, the resulting list is filtered.
limit | Maximum number of records to return. If set to 0, the number of returned records is not limited.

Structure of the returned record

Array
(
    [PHRASE] => search phrase
    [TOTAL_PHRASES] => total visits with this search phrase
    [TODAY_PHRASES] => today's visits
    [YESTERDAY_PHRASES] => yesterday's visits
    [B_YESTERDAY_PHRASES] => visits for day before yesterday
    [PERIOD_PHRASES] => visits for the period:
                        (filter[DATE1],  filter[DATE2])
)

See Also

  • The CPhrase class
  • The Statistics Summary report

Example

<?
// get data for December 2005
$arFilter = array(
    "DATE1" => "01.12.2005",
    "DATE2" => "31.12.2005"
    );

// obtain the list of phrases and the statistics
$rs = CTraffic::GetPhraseList($by="s_today",
                              $order="desc",
                              $arFilter,
                              $is_filtered,
                              false);
while ($ar = $rs->Fetch())
{
    echo "search phrase: ".$ar["PHRASE"]."<br>";
    echo "total visits with this search phrase: ".
         $ar["TOTAL_PHRASES"].
         "<br>";
    echo "today: ".$ar["TODAY_PHRASES"]."<br>";
    echo "yesterday: ".$ar["YESTERDAY_PHRASES"]."<br>";
    echo "d. before yesterday: ".$ar["B_YESTERDAY_PHRASES"]."<br>";
    echo "during December 2005: ".
         $ar["PERIOD_PHRASES"]."<br>";
}
?>


GetRefererList

CTraffic::GetRefererList

CDBResult
CTraffic::GetRefererList(
 string &by = "ref_today",
 string &order = "desc",
 array filter = array(),
 bool &is_filtered,
 mixed limit = 10,
)

The method GetRefererList returns the number of referring sites: for the whole time of keeping statistics, for the last 3 days, or for the specified period.

Parameters

Parameter | Description
by Sorting field; possible values:
  • ref_server - the referring site;
  • ref_today - number of today's visits from the referring site;
  • ref_yesterday - number of yesterday's visits from the referring site;
  • ref_bef_yesterday - number of visits from the referring site for day before yesterday;
  • ref_total - total number of visits from the referring site;
  • ref_period - number of visits from the referring site for the period (filter[DATE1], filter[DATE2]).
order Sort order; the following values are possible:
  • asc - ascending;
  • desc - descending.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • SITE_ID - the ID of the site whose referring site statistics is to be obtained;;
  • DATE1 - starting date;
  • DATE2 - ending date.
is_filtered | If this variable contains "true" on return, the resulting list is filtered.
limit | Maximum number of records to return. If set to 0, the number of returned records is not limited.

Structure of the returned record

Array
(
    [SITE_NAME] => the referring site
    [TOTAL_REFERERS] => total number of visits from the referring site
    [TODAY_REFERERS] => number of today's visits from the referring site
    [YESTERDAY_REFERERS] => number of yesterday's visits from
                            the referring site
    [B_YESTERDAY_REFERERS] => number of visits from the referring site
                              for day before yesterday
    [PERIOD_REFERERS] => number of visits from the referring site
                         for the period
                         (filter[DATE1],  filter[DATE2])
)

See Also

  • The CReferer class
  • The Statistics Summary report

Example

<?
// get data for December 2005
$arFilter = array(
    "DATE1" => "01.12.2005",
    "DATE2" => "31.12.2005"
    );

// obtain the list of phrases and the statistics
$rs = CTraffic::GetRefererList(
    ($by="ref_today"),
    ($order="desc"),
    $arFilter,
    $is_filtered,
    false
    );

while ($ar = $rs->Fetch())
{
    echo "referring site: ".$ar["SITE_NAME"]."<br>";
    echo "total hits from this site: ".
         $ar["TOTAL_REFERERS"]."<br>";
    echo "today: ".$ar["TODAY_REFERERS"]."<br>";
    echo "yesterday: ".$ar["YESTERDAY_REFERERS"]."<br>";
    echo "day before yesterday: ".$ar["B_YESTERDAY_REFERERS"]."<br>";
    echo "during December 2005: ".
         $ar["PERIOD_REFERERS"]."<br>";
}
?>


GetSumList

CTraffic::GetSumList

CDBResult
CTraffic::GetSumList(
 string data_type,
 array filter = array(),
)

The method GetSumList returns the number of hits, hosts, sessions, visitors, events on hourly, daily or monthly basis.

Parameters

Parameter Description
data_type Data type. Possible values:
  • hour - return data on hourly basis;
  • weekday - on daily basis;
  • month - on monthly basis.
filter Array used to filter the resulting list. The following keys can be used in the array:
  • SITE_ID - the ID of the site whose statistics is to be obtained;
  • DATE1 - starting date;
  • DATE2 - ending date.

Structure of the returned record

The structure of the returned record varies depending on the data_type parameter value.

  • when (data_type is hour):
    Array
(
    [HOUR_HOST_0] => host count from 0:00 till 1:00
    ...
    [HOUR_HOST_23] => host count from 23:00 till 00:00

    [HOUR_SESSION_0] => session count from 00:00 till 01:00
    ...
    [HOUR_SESSION_23] => session count from 23:00 till 0:00

    [HOUR_HIT_0] => hit count from 0:00 till 1:00
    ...
    [HOUR_HIT_23] => hit count from 23:00 till 0:00

    [HOUR_EVENT_0] => event count from 0:00 till 1:00
    ...
    [HOUR_EVENT_23] => event count from 23:00 till 0:00

    [HOUR_GUEST_0] => visitor count from 0:00 till 1:00
    ...
    [HOUR_GUEST_23] => visitor count from 23:00 till 0:00

    [HOUR_NEW_GUEST_0] => new visitor count from 0:00 till 1:00
    ...
    [HOUR_NEW_GUEST_23] => new visitor count from 23:00 till 0:00

    [HOUR_FAVORITE_0] => number of new visitors who
                         added to Favorites, from 0:00 till 1:00
    ...
    [HOUR_FAVORITE_23] => number of new visitors who
                          added to Favorites, from 23:00 till 0:00
)
  • when data_type is weekday:
    Array
(
    [WEEKDAY_HOST_0] => number of Sunday's hosts
    [WEEKDAY_HOST_1] => number of Monday's hosts
    ...
    [WEEKDAY_HOST_6] => number of Saturday's hosts

    [WEEKDAY_SESSION_0] => number of Sunday's sessions
    [WEEKDAY_SESSION_1] => number of Monday's sessions
    ...
    [WEEKDAY_SESSION_6] => number of Saturday's sessions

    [WEEKDAY_HIT_0] => number of Sunday's hits
    [WEEKDAY_HIT_1] => number of Monday's hits
    ...
    [WEEKDAY_HIT_6] => number of Saturday's hits

    [WEEKDAY_EVENT_0] => number of Sunday's events
    [WEEKDAY_EVENT_1] => number of Monday's events
    ...
    [WEEKDAY_EVENT_6] => number of Saturday's events

    [WEEKDAY_GUEST_0] => number of Sunday's visitors
    [WEEKDAY_GUEST_1] => number of Monday's visitors
    ...
    [WEEKDAY_GUEST_6] => number of Saturday's visitors

    [WEEKDAY_NEW_GUEST_0] => number of Sunday's new visitors
    [WEEKDAY_NEW_GUEST_1] => number of Monday's new visitors
    ...
    [WEEKDAY_NEW_GUEST_6] => number of Saturday's new visitors

    [WEEKDAY_FAVORITE_0] => number of Sunday's visitors
                            who added the site to Favorites
    [WEEKDAY_FAVORITE_1] => Monday's visitors
    ...
    [WEEKDAY_FAVORITE_6] => Saturday's visitors
)
  • when data_type is month:
    Array
(
    [MONTH_HOST_1] => number of January's hosts
    ...
    [MONTH_HOST_12] => number of December's hosts

    [MONTH_SESSION_1] => number of January's sessions
    ...
    [MONTH_SESSION_12] => number of December's sessions

    [MONTH_HIT_1] => number of January's hits
    ...
    [MONTH_HIT_12] => number of December's hits

    [MONTH_EVENT_1] => number of January's events
    ...
    [MONTH_EVENT_12] => number of December's events

    [MONTH_GUEST_1] => number of January's visitors
    ...
    [MONTH_GUEST_12] => number of December's visitors

    [MONTH_NEW_GUEST_1] => number of January's new visitors
    ...
    [MONTH_NEW_GUEST_12] => number of December's new visitors

    [MONTH_FAVORITE_1] => number of January's visitors
                          who added to Favorites
    ...
    [MONTH_FAVORITE_12] => number of December's visitors
                           who added to Favorites
)

See Also

  • The Site Traffic page

Example

<?
// obtain information on daily traffic
$rs = CTraffic::GetSumList("weekday");
$ar = $rs->Fetch();
for ($i=0; $i<=6; $i++)
{
    switch($i)
    {
        case 0: echo "sun"; break;
        case 1: echo "mon"; break;
        case 2: echo "tue"; break;
        case 3: echo "wed"; break;
        case 4: echo "thu"; break;
        case 5: echo "fri"; break;
        case 6: echo "sat"; break;
    }
    echo "<br>";
    echo "hosts: ".$ar["WEEKDAY_HOST_".$i]."<br>";
    echo "sessions: ".$ar["WEEKDAY_SESSION_".$i]."<br>";
    echo "hits: ".$ar["WEEKDAY_HIT_".$i]."<br>";
    echo "visitors: ".$ar["WEEKDAY_GUEST_".$i]."<br>";
    echo "new visitors: ".$ar["WEEKDAY_NEW_GUEST_".$i]."<br>";
    echo "<br><br>";
}
?>


CUserOnline

The CUserOnline class is used to obtain information on recent visitors of the site and their sessions.

Methods

Method | Description
GetGuestCount | Returns the number of active visitors (those who made a hit) within a certain interval.
GetList | Returns a list of active visitors' sessions (those who made a hit) on the site within a certain time period.

See Also

  • The online visitors report


GetGuestCount

CUserOnline::GetGuestCount

int
CUserOnline::GetGuestCount()

The method GetGuestCount returns the number of active visitors (those who made a hit) within a certain interval. The interval is specified in the Statistics module settings in the On-line visitor interval parameter.

Parameters

No parameters.

See Also

  • CTraffic::GetCommonValues

Example

<?
echo "Users online: ".CUserOnline::GetGuestCount();
?>


GetList

CUserOnline::GetList

CDBResult
CUserOnline::GetList(
 int &guest_counter,
 int &session_counter
)

The method GetList returns a list of active visitors' sessions (those who made a hit) on the site within a certain time period.

Parameters

Parameter | Description
guest_counter | Reference to a variable which will contain the number of online visitors on return.
session_counter | Reference to a variable which will contain the number of visitor sessions on return.

Structure of the returned record

Array
(
    [ID] => the session ID
    [HITS] => number of session hits
    [LAST_USER_ID] => the ID of the user under which the visitor was last authorised
    [USER_AUTH] => flag: whether the user is authorised
                   in this session [Y/N]
    [STOP_LIST_ID] => the ID of the stop list record (if applicable)
    [GUEST_ID] => the visitor ID
    [NEW_GUEST] => new visitor (Y - new; N - returned)
    [FAVORITES] => flag: whether the visitor has added
                   the site to Favorites during this session
    [COUNTRY_ID] => the ID of the visitor country
    [COUNTRY_NAME] => name of the visitor country

    [ADV_ID] => the ID of the advertising campaign
    [ADV_BACK] => flag: direct hit (N) or return (Y) under an advertising campaign
    [REFERER1] => the referer1 identifier of the advertising campaign
    [REFERER2] => the referer2 identifier of the advertising campaign
    [REFERER3] => the additional parameter of the advertising campaign

    [FIRST_URL_FROM] => the referring page form which the visitor first entered the site
    [URL_FROM] => the referring page URL
    [FIRST_SITE_ID] => the first site ID
    [URL_LAST] => the page of the last session hit
    [URL_LAST_404] => [Y|N] indicates the error 404 occurred on the last page of the session
    [LAST_SITE_ID] => the ID of the last hit site
    [IP_LAST] => the visitor IP address during the last hit (in the form XXX.XXX.XXX.XXX)
    [DATE_LAST] => time of the last hit

    [SESSION_TIME] => time difference between the first and last hits (sec.)
)

See Also

  • The online visitors report

Example

<?
// obtain the list of records
$rs = CUserOnline::GetList($guest_counter, $session_counter);

echo "Online visitors : ".$guest_counter;
echo "Online sessions : ".$session_counter;

// print all records
while ($ar = $rs->Fetch())
{
    echo "<pre>"; print_r($ar); echo "</pre>";
}
?>


Classes

The following PHP classes are used in the Subscription module.

Classes

Class | Description
CPosting | Used with subscription issues.
CRubric | Used with mailing lists.
CSubscription | Used with subscriptions.
CPostingTemplate | Used with subscription issues templates.


CPosting

The CPosting class is used with subscription issues.

Methods

Method | Description
Add | The method adds a new issue (newsletter, message).
Delete | The method deletes an issue by its ID.
GetByID | The method returns an issue by its ID.
GetEmails | The method returns an array of e-mail addresses to which the message will be sent.
GetGroupList | The method returns a list of user groups to which the message will be sent.
GetList | The method returns a filtered list of issues.
GetRubricList | The method returns subscriptions to which the message will be sent.
SendMessage | The method sends the issue message to subscribed e-mail addresses.
Update | The method updates the issue properties by its ID.
Lock | Attempts to lock an issue. Used with automatic dispatch of the issue messages.
SaveFile | Adds an attachment to an issue. The attachment is stored and registered in the file table (b_file).
DeleteFile | Deletes one or all attachments of the issue.
GetFileList | Returns the issue attachments.
AutoSend | Schedules the issue sending via the cron or an agent function.
ChangeStatus | Changes the issue status and performs the required action.


CPosting fields

The CPosting class uses the following fields with the issue object.

Field | Description | Type | Required
ID | The issue ID. | int | Yes
TIMESTAMP_X | The date of the record modification. | datetime
STATUS The issue status. Can be one of the following:
  • "S" (sent successfully);
  • "E" (error);
  • "P" (partially sent);
  • "W" (suspended);
  • "D" (draft).
 char(1)
DATE_SENT | The date the message was sent. | datetime
SENT_BCC | List of e-mail addresses to which the message was sent; separated by commas. | text
FROM_FIELD | The message field "from". | string(255) | Yes
TO_FIELD | The message field "to". | string(255) | No
BCC_FIELD | List of e-mail addresses in the message field "BCC". | text
SUBJECT | The message field "Subject". | string(255) | Yes
BODY_TYPE | The type of the message body. Text or HTML. | string(4)
BODY | The message body. | text | Yes
DIRECT_SEND | Specifies to send message to each subscriber individually ("Y"/"N"). | char(1)
CHARSET | Charset used in the message header. | string(50)
EMAIL_FILTER | Filter used to select e-mail addresses. | string(255)
SUBSCR_FORMAT | Filter used to select the message body format. Format is specified in the subscriber preferences. | string(4)
ERROR_EMAIL | List of e-mail addresses to which the message failed to send; separated by commas. | text
AUTO_SEND_TIME | The time when the issue dispatch is to be started (using either an agent function or the cron). | datetime
BCC_TO_SEND | Comma-separated list of addresses to which to send issues. | text


Add

CPosting::Add

CPosting::Add(
   $arFields
);

The method Add is used to add a new issue (newsletter, message).

Parameters

Parameter Description
$arFields Associated array containing the keys and values of the Issue object fields. The following fields can also be used:
  • RUB_ID - array of the mailing list ID's;
  • GROUP_ID - array of the user group ID's.

Return Values

Returns the issue ID on success. In case of an error, it returns false and the class variable LAST_ERROR contains the error description.

Example

$posting = new CPosting;
$arFields = Array(
    "FROM_FIELD" => $FROM_FIELD,
    "TO_FIELD" => $TO_FIELD,
    "BCC_FIELD" => $BCC_FIELD,
    "EMAIL_FILTER" => $EMAIL_FILTER,
    "SUBJECT" => $SUBJECT,
    "BODY_TYPE" => ($BODY_TYPE <> "html"? "text":"html"),
    "BODY" => $BODY,
    "DIRECT_SEND" => ($DIRECT_SEND <> "Y"? "N":"Y"),
    "CHARSET" => $CHARSET,
    "SUBSCR_FORMAT" => ($SUBSCR_FORMAT<>"html" && $SUBSCR_FORMAT<>"text"?
        false:$SUBSCR_FORMAT),
    "RUB_ID" => $RUB_ID,
    "GROUP_ID" => $GROUP_ID
);
if($STATUS <> "")
{
    if($STATUS<>"S" && $STATUS<>"E" && $STATUS<>"P")
        $STATUS = "D";
    $arFields["STATUS"] = $STATUS;
    if($STATUS == "D")
    {
        $arFields["DATE_SENT"] = false;
        $arFields["SENT_BCC"] = "";
        $arFields["ERROR_EMAIL"] = "";
    }
}
$ID = $posting->Add($arFields);
if($ID == false)
    echo $posting->LAST_ERROR;


CPosting::AutoSend

CPosting::AutoSend(
    int ID = false,
    bool limit = false
);

The method AutoSend schedules the issue sending via the cron or an agent function.

Parameters

Parameter | Description
ID | The issue ID. If not specified or false, all issues are sent whose sending time is less or equal to the current.
limit | Specifies the maximum count of messages to be sent within a single function call. Used with agents. The default count maximum count of messages is specified in the module settings.

Return Values

No return value.

Example

The following is an example of sending messages via the cron.

#!/usr/bin/php
<?php

// Specify your DOCUMENT_ROOT here!
$_SERVER["DOCUMENT_ROOT"] = "/opt/www/html";

$DOCUMENT_ROOT = $_SERVER["DOCUMENT_ROOT"];
define("NO_KEEP_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
set_time_limit(0);
define("LANG", "en");
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("subscribe"))
{
    $cPosting = new CPosting;
    $cPosting->AutoSend();
}
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");
?>

Example

The following is an example of sending messages via an agent function.

<?
    CAgent::AddAgent("CPosting::AutoSend(".$ID.",true);",
                     "subscribe", "N", 0,
                     $post_arr["AUTO_SEND_TIME"], "Y",
                     $post_arr["AUTO_SEND_TIME"]);
?>
<p class="notetext">Created agent for the message sending.</p>


CPosting::ChangeStatus

CPosting::ChangeStatus(
    int ID,
    string status
);

The method ChangeStatus changes the issue status and performs action according to the rules summarized in the table below.

Current status | New status | Actions
Draft | Sending | Creates a list of addresses to which to send messages.
Sending | Suspended | No action.
Suspended | Sending | No action.
Sending | Errors occurred | No action.
Sending | Sent | No action.
Errors occurred | Sending | List of fault addresses is copied to the delivery list and the former clears.
Errors occurred, Sent, Suspended | Draft | The list of fault addresses, the delivery list and the successful list are all cleared.

Parameters

Parameter | Description
ID | The issue ID.
status The new status of the issue. Can be one of the following:
  • "S" (sent successfully);
  • "E" (error);
  • "P" (partially sent);
  • "W" (suspended);
  • "D" (draft).

Return Values

Returns true on successful status change, or false otherwise. On error, the class variable LAST_ERROR contains the error description.

Example

//******************************
// Stop sending the message
//******************************
if($action=="stop" && $ID>0 && $POST_RIGHT=="W")
{
    $cPosting->ChangeStatus($ID, "W");
}


Delete

CPosting::Delete

CPosting::Delete(
    $ID
);

The method Delete is used to delete an issue by its ID.

Parameters

Parameter | Description
$ID | The issue ID.

Return Values

Returns an instance of the CDBResult class on success, or false otherwise.

Example

if(($res = CPosting::Delete($ID)) && $res->AffectedRowsCount() < 1 || $res == false)
    echo "Cannot delete the issue.";
else
    echo "Deleted successfylly.";


CPosting::DeleteFile

CPosting::DeleteFile(
    int ID,
    int file_id = false
);

The method DeleteFile deletes one or all attachments of the issue.

Parameters

Parameter | Description
ID | The issue ID.
file_id | The attachment ID. If omitted or false, all attachments are deleted.

Return Values

No return value.

Example

    if(is_array($FILE_ID))
        foreach($FILE_ID as $file_id)
            CPosting::DeleteFile($ID, $file_id);


GetByID

CPosting::GetByID

CDBResult
CPosting::GetByID(
    $ID
);

The method GetByID returns an issue by its ID.

Parameters

Parameter | Description
$ID | The issue ID.

Return Values

Returns an instance of the CDBResult class. The fields of the Issue object become available after calling one of the CDBResult methods.

Example

if($ID>0)
{
    $post = CPosting::GetByID($ID);
    if(!($post_arr = $post->ExtractFields("str_")))
        $ID=0;
}


GetEmails

CPosting::GetEmails

CPosting::GetEmails(
    $post_arr
);

The method GetEmails returns an array of e-mail addresses to which the message will be sent.

Parameters

Parameter | Description
$post_arr | Array of all the Issue object fields in the form of "field value" => "value".

Return Values

The method returns an array of the unique e-mail addresses.

Example

$post = CPosting::GetByID($ID);
if(($post_arr = $post->Fetch()))
    $aEmail = CPosting::GetEmails($post_arr);


CPosting::GetFileList

CPosting::GetFileList(
    int ID,
    int file_id = false
);

The method GetFileList returns the issue attachments.

Parameters

Parameter | Description
ID | The issue ID.
file_id | The attachment ID. If omitted or false, all attachments are returned.

Return Values

Returns the CDBResult query result. The following File fields become available after the result is fetched: ID, FILE_SIZE, ORIGINAL_NAME, SUBDIR, FILE_NAME, CONTENT_TYPE.

Example

// size of all attachments
$attach_size = 0;
$rsFile = CPosting::GetFileList($ID);
while($arFile = $rsFile->Fetch())
    $attach_size += $arFile["FILE_SIZE"];


GetGroupList

CPosting::GetGroupList

CPosting::GetGroupList(
    $ID
);

The method GetGroupList returns a list of user groups to whom the message will be sent.

Parameters

Parameter | Description
$ID | The issue ID.

Return Values

Returns an instance of the CDBResult class. The ID and NAME fields of the object "Group" become available after calling one of the CDBResult methods.

Example

<?
//show user groups and check selected for the issue
$aPostGrp = array();
if($ID>0)
{
    $post_grp = CPosting::GetGroupList($ID);
    while($post_grp_arr = $post_grp->Fetch())
        $aPostGrp[] = $post_grp_arr["ID"];
}
$group = CGroup::GetList(($by="name"), ($order="asc"));
while($group->ExtractFields("g_")):
?>
<input
 type="checkbox"
 name="GROUP_ID[]"
 value="<?echo $g_ID?>"
 <?if(in_array($g_ID, $aPostGrp)) echo " checked"?>>
<?echo $g_NAME?><br>
<?
endwhile;
?>


GetList

CPosting::GetList

CPosting::GetList(
    $aSort=array(),
    $aFilter=array()
);

The method GetList returns a filtered list of issues.

Parameters

Parameter Description
aSort Array containing the sort criteria in the form "field name"=>"direction".

The field name can be the following:
  • ID - the issue ID;
  • TIMESTAMP - the modification date;
  • SUBJECT - the message subject;
  • BODY_TYPE - the body type;
  • STATUS - the issue status;
  • DATE_SENT - the date of the message sending;
  • AUTO_SEND_TIME - the time when the issue dispatch is to be started.
The direction can be one of the following:
  • ASC - ascending;
  • DESC - descending.
For example:
array("STATUS"=>"ASC", "DATE_SENT"=>"DESC")
aFilter Array containing the filter in the form of arrays "field name"=>"filter value".

The field name can be the following:
  • ID - the issue ID (complex logic allowed);
  • TIMESTAMP_1 - the earliest possible date of modification;
  • TIMESTAMP_2 - the latest possible date of modification;
  • DATE_SENT_1 - the earliest possible date of the message sending;
  • DATE_SENT_2 - the latest possible date of the message sending;
  • AUTO_SEND_TIME_1 - the date or the time when the dispatch is to be started (lower bound of the range);
  • AUTO_SEND_TIME_2 - the date or the time when the dispatch is to be started (upper bound of the range);
  • STATUS - string containing the issue status (complex logic allowed);
  • STATUS_ID - character indicating the issue status (complex logic allowed);
  • SUBJECT - the message subject (complex logic allowed);
  • FROM - the "from" field of the message (complex logic allowed);
  • TO - the "to" field of the message (complex logic allowed);
  • BODY_TYPE - the type of the message body;
  • BODY - message body (complex logic allowed).
For example:
array("SUBJECT"=>"test | test", "TO"=>"@bitrixsoft.com")

Return Values

Returns an instance of the CDBResult class. The Issue object fields except those of the text type become available after calling one of the CDBResult methods.

In case of an error, the class variable LAST_ERROR contains the error description.

Example

$cPosting = new CPosting;
$arFilter = Array(
    "ID" => $find_id,
    "TIMESTAMP_1" => $find_timestamp_1,
    "TIMESTAMP_2" => $find_timestamp_2,
    "DATE_SENT_1" => $find_date_sent_1,
    "DATE_SENT_2" => $find_date_sent_2,
    "STATUS" => $find_status,
    "STATUS_ID" => $find_status_id,
    "SUBJECT" => $find_subject,
    "FROM" => $find_from,
    "TO" => $find_to,
    "BODY" => $find_body,
    "BODY_TYPE" => $find_body_type
);
$rsPosting = $cPosting->GetList(array($by=>$order), $arFilter);
$strError .= $cPosting->LAST_ERROR;

$rsPosting->NavStart(50);
echo $rsPosting->NavPrint("Issues");
while($rsPosting->NavNext(true, "f_"))
{
    //...
}


GetRubricList

CPosting::GetRubricList

CDBResult
CPosting::GetRubricList(
    $ID
);

The method GetRubricList returns subscriptions to which the message will be sent.

Parameters

Parameter | Description
$ID | The issue ID.

Return Values

Returns an instance of the CDBResult class. The ID, NAME, SORT, LID and ACTIVE fields of the Issue object become available after calling one of the CDBResult methods.

Example

//obtain subscriptions to which the message is to be sent
$aPostRub = array();
$post_rub = CPosting::GetRubricList($post_arr["ID"]);
while($post_rub_arr = $post_rub->Fetch())
    $aPostRub[] = $post_rub_arr["ID"];


CPosting::Lock

CPosting::Lock(
    int ID
);

The method Lock attempts to lock an issue. Used with automatic dispatch of the issue messages.

Parameters

Parameter | Description
ID | The issue ID.

Return Values

Returns true on success, or false otherwise.

Example

if (CPosting::Lock($ID)===false)
    return "CONTINUE";


CPosting::SaveFile

CPosting::SaveFile(
    int ID,
    array file
);

The method SaveFile adds an attachment to an issue. The attachment is stored and registered in the file table (b_file).

Parameters

Parameter | Description
ID | The issue ID.
file Array of file data in the format:
Array(
    "name" => "file name",
    "size" => "size",
    "tmp_name" => "temporary path on the server",
    "type" => "file type");
You can obtain this array directly from $_FILES[field_name].

Return Values

Retuns the ID of the registered file on success, or false otherwise.

Example

if (strlen($save)>0 && $REQUEST_METHOD=="POST")
{
    $file_id = CPosting::SaveFile($ID, $_FILES["FILE_TO_ATTACH"]);
    if ($file_id===false)
        strError .= "Error storing the attachement."."<br>";
}


SendMessage

CPosting::SendMessage

mixed
CPosting::SendMessage(
 int ID,
 int timeout=0,
 int maxcount = 0
);

The method SendMessage is used to send the issue message to subscribed e-mail addresses.

Messages having the Sent successfully status cannot be sent again. If a message has the Partially sent status set, it is sent to the remaining e-mail addresses.

Parameters

Parameter | Description
ID | The issue ID.
timeout | Maximum sending period in seconds. In case of timeout, the method terminates and sets the Partially sent status of the message. The parameter is meaningful only for dispatch method Send a message personally. If $timeout=0, the sending operation is not fragmented.
maxcount | Maximum number of messages to be sent. If the number of messages sent exceeds this value, the method terminates and sets the issue status Partially sent. This parameter is only meaningful if used with the sending option Send personally to each recipient. If this value is 0, the sending is always performed within a single step.

Return Values

The method returns true on success, or false otherwise. If some of the messages could not be sent, the method returns "CONTINUE". In case of an error, the class variable LAST_ERROR contains the error description.

Example

<?
if ($action=="send" && $ID>0):
    if (($res = $cPosting->SendMessage($ID,
                COption::GetOptionString("subscribe",
                                         "posting_interval"))) !== false):
    if($res === "CONTINUE"):
?>
<script language="JavaScript" type="text/javascript">
<!--
function DoNext()
{
    window.location="<?echo $APPLICATION->GetCurPage().
                    "?ID=".$ID."&action=send&lang=".LANG.
                    "&rnd=".rand();?>";
}
setTimeout('DoNext()', 2500);
//-->
</script>
<?
        else:
            $strOk = "Sent successfully.";
        endif; //$res === "CONTINUE"
    endif; //$cPosting->SendMessage
    $strError .= $cPosting->LAST_ERROR;
endif; //$action=="send"


Update

CPosting::Update

CPosting::Update(
 $ID,
 $arFields
);

The method Update updates the issue properties by its ID.

Parameters

Parameter | Description
$ID | The issue ID.
$arFields Associated array containing the keys and values of the Issue object fields. The following fields can also be used:
  • RUB_ID - array of the mailing list ID's;
  • GROUP_ID - array of the user group ID's.

Return Values

Returns true on success. In case of an error, it returns false and the class variable LAST_ERROR contains the error description.

Example

$posting = new CPosting;
$arFields = Array(
    "FROM_FIELD" => $FROM_FIELD,
    "TO_FIELD" => $TO_FIELD,
    "BCC_FIELD" => $BCC_FIELD,
    "EMAIL_FILTER" => $EMAIL_FILTER,
    "SUBJECT" => $SUBJECT,
    "BODY_TYPE" => ($BODY_TYPE <> "html"? "text":"html"),
    "BODY" => $BODY,
    "DIRECT_SEND" => ($DIRECT_SEND <> "Y"? "N":"Y"),
    "CHARSET" => $CHARSET,
    "SUBSCR_FORMAT" => ($SUBSCR_FORMAT<>"html" &&
                        $SUBSCR_FORMAT<>"text"
                            ? false : $SUBSCR_FORMAT),
    "RUB_ID" => $RUB_ID,
    "GROUP_ID" => $GROUP_ID
);
if($STATUS <> "")
{
    if($STATUS<>"S" && $STATUS<>"E" && $STATUS<>"P")
        $STATUS = "D";
    $arFields["STATUS"] = $STATUS;
    if($STATUS == "D")
    {
        $arFields["DATE_SENT"] = false;
        $arFields["SENT_BCC"] = "";
        $arFields["ERROR_EMAIL"] = "";
    }
}
if(!$posting->Update($ID, $arFields))
    $strError = $posting->LAST_ERROR;


CPostingTemplate

The class CPostingTemplate is used with subscription issues templates.

Class methods

Method | Description
GetList | Returns a list of templates.
GetByID | Returns a template by its ID (which is the relative path).
IsExists | Checks whether the folder of the template physically exists.
Execute | Selects a scheduled template for the subscription issue generation.
AddPosting | Generates a subscription issue based on the template.


CPostingTemplate::AddPosting

CPostingTemplate::AddPosting(
    array arRubric
);

The method AddPosting generates a subscription issue based on the template.

Parameters

Parameter Description
arRubric Array of the Mailing list (rubric) fields. The following additional fields are also possible:
  • SITE_ID - the ID of the site from which the rubric originates;
  • START_TIME - time of the last template run in the "FULL" format of the current site;
  • END_TIME - time of the current template run in the "FULL" format of the current site.

Return Values

No return value.

Example

$rubrics = CRubric::GetList(array(), array("ID"=>$ID));
if($arRubric=$rubrics->Fetch())
{
    $arRubric["START_TIME"] = $START_TIME;
    $arRubric["END_TIME"] = $END_TIME;
    $arRubric["SITE_ID"] = $arRubric["LID"];
    CPostingTemplate::AddPosting($arRubric);
}


CPostingTemplate::Execute

CPostingTemplate::Execute();

The method Execute selects a scheduled template for the subscription issue generation.

First, the method selects all subscriptions marked as active and automatic. Then, each subscription is checked whether it needs to be posted. When the method encounters a subscription which satisfy all requirements, it calls CPostingTemplate::AddPosting on this subscription and terminates.

This method should be called from the cron script or an agent function.

Parameters

No parameters.

Return Values

If at least one active automatic subscription could be found, the method returns a string to be called from the agent. Otherwise, an empty string is returned.

Example

The following is an example of using the method in a PHP script for the cron.

#!/usr/bin/php
<?php

//Specify your DOCUMENT_ROOT here!
$_SERVER["DOCUMENT_ROOT"] = "/opt/www/html";

$DOCUMENT_ROOT = $_SERVER["DOCUMENT_ROOT"];
define("NO_KEEP_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
set_time_limit(0);
define("LANG", "en");
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("subscribe"))
    CPostingTemplate::Execute();
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");
?>


CPostingTemplate::GetByID

CPostingTemplate::GetByID(
    string path = ""
);

The method GetByID returns a template by its ID (which is the relative path).

Parameters

Parameter | Description
path | Relative path to the template folder.

Return Values

Returns an array from the file description.php. In addition, the array contains a key path set to the relative path to the template folder.

Example

The following is an example of description.php.

<?
$arTemplate =
    Array(
    "NAME"=>"News digest",
    "DESCRIPTION"=>"News digest template."
    );
?>


CPostingTemplate::GetList

CPostingTemplate::GetList();

The method GetList returns a list of templates.

Parameters

No parameters.

Return Values

Returns an array of relative paths to subfolders of the folder $_SERVER["DOCUMENT_ROOT"]."/"."bitrix/php_interface/subscribe/templates".

Example

<?
//get template directories
$arTemplates = CPostingTemplate::GetList();
foreach($arTemplates as $template_dir):
?>
    <p><?echo $template_dir?></p>
<?
endforeach;
?>


CPostingTemplate::IsExists

CPostingTemplate::IsExists(
    string path = ""
);

The method IsExists checks whether the folder of the template physically exists.

Parameters

Parameter | Description
path | Relative path to the template folder.

Return Values

Returns true if the specified folder exists, or false otherwise.

Example

<?
if (!CPostingTemplate::IsExists("bitrix/php_interface/subscribe/templates/news"))
    echo "The specified template does not exist.";
?>


CRubric

The CRubric class is used with mailing lists.

Methods

Method | Description
Add | The method adds a new mailing list.
Delete | The method deletes a mailing list.
GetByID | The method returns a mailing list by its ID.
GetList | The method returns a filtered list of mailing lists.
GetSubscriptionCount | The method returns the number of subscribers of the specified mailing list. Both confirmed and unconfirmed subscribers are counted.
Update | The method updates a mailing list.


CRubric fields

The CRubric class uses the following fields with the Mailing list object.

Field | Description | Type | Required
ID | The mailing list ID. | int | Yes
LID | The site ID. | char(2) | Yes
NAME | The name of mailing list. | string(100) | Yes
DESCRIPTION | The mailing list description displayed to subscribers. | text |
SORT | Sort weight. | int |
ACTIVE | The active state of mailing list (Y/N). | char(1) |
VISIBLE | Specifies whether the mailing list is public or not (Y/N). | char(1) |
AUTO | Specifies to generate issues automatically (Y/N). | char(1) |
LAST_EXECUTED | Time of the last issue. | datetime |
DAYS_OF_MONTH | List of days of the month when the issue is to be generated. | string(100) |
DAYS_OF_WEEK | List of days of week when the issue is to be generated. | string(15) |
TIMES_OF_DAY | List of hours when the issue is to be generated. | string(100) |
TEMPLATE | Relative path to the template folder. | string(100) |


Add

CRubric::Add

CRubric::Add(
    $arFields
);

The method Add is used to add a new mailing list.

Parameters

Parameter | Description
$arFields | Associated array containing the keys and values of the Mailing list object fields.

Return Values

Returns the mailing list ID on success. In case of an error, it returns false and the class variable LAST_ERROR contains the error description.

Example

$rubric = new CRubric;
$arFields = Array(
    "ACTIVE" => ($ACTIVE <> "Y"? "N":"Y"),
    "NAME" => $NAME,
    "SORT" => $SORT,
    "DESCRIPTION" => $DESCRIPTION,
    "LID" => $LID
);
$ID = $rubric->Add($arFields);
if($ID == false)
    echo $rubric->LAST_ERROR;


Delete

CRubric::Delete

CRubric::Delete(
    $ID
);

The method Delete is used to delete a mailing list.

Parameters

Parameter | Description
$ID | The mailing list ID.

Return Values

Returns an instance of the CDBResult class on success, or false otherwise.

Example

if(($res = CRubric::Delete($ID)) && $res->AffectedRowsCount() < 1 || $res == false)
    echo "Error";


GetByID

CRubric::GetByID

CRubric::GetByID(
    $ID
);

The method GetByID returns a mailing list by its ID.

Parameters

Parameter | Description
$ID | The mailing list ID.

Return Values

Returns an instance of the CDBResult class. The fields of the Mailing list object become available after calling one of the CDBResult methods.

Example

if($ID>0)
{
    $rubric = CRubric::GetByID($ID);
    if($rubric->ExtractFields("str_"))
        echo $str_NAME;
}


GetList

CRubric::GetList

CRubric::GetList(
    $aSort=array(),
    $aFilter=array()
);

The method GetList returns a filtered list of mailing lists.

Parameters

Parameter Description
$aSort Array containing the sort criteria entries in the form "field name"=>"direction".

The field name can be the following:
  • NAME - the mailing list name;
  • LID - the site ID;
  • ACT - the mailing list active state;
  • SORT - sort weight;
  • ID - the mailing list ID
  • AUTO - tells the subscription issues are to be generated;
  • VISIBLE - the mailing list is public;
  • LAST_EXECUTED - time of the last generation.
The direction can be one of the following:
  • ASC - ascending;
  • DESC - descending.
For example:
array("LID"=>"ASC", "NAME"=>"DESC")
$aFilter Array containing the filter entries in the form of "field name"=>"filter value".

The field name can be the following:
  • LID - the site ID;
  • ACTIVE - the mailing list active state;
  • AUTO - tells the subscription issues are to be generated;
  • VISIBLE - the mailing list is public;
  • ID - the mailing list ID.
For example:
array("LID"=>SITE_ID, "ACTIVE"=>"Y")

Return Values

Returns an instance of the CDBResult class. The Mailing list object fields become available after calling one of the CDBResult methods.

Example

<?
//get the site's newsletter categories
$rub = CRubric::GetList(array("SORT"=>"ASC", "NAME"=>"ASC"),
                        array("ACTIVE"=>"Y", "LID"=>LANG));
while($rub->ExtractFields("r_")):
?>
    <input
     type="checkbox"
     name="sf_RUB_ID[]" value="<?echo $r_ID?>"><?echo $r_NAME?><br>
<?
endwhile;
?>


GetSubscriptionCount

CRubric::GetSubscriptionCount

CRubric::GetSubscriptionCount(
    $ID
);

The method GetSubscriptionCount returns the number of subscribers of the specified mailing list. Both confirmed and unconfirmed subscribers are counted.

Parameters

Parameter | Description
$ID | The mailing list ID.

Return Values

The method returns an integer which is the number of subscribers.

Example

<?
//get site's newsletter categories
$rub = CRubric::GetList(array("SORT"=>"ASC", "NAME"=>"ASC"),
                        array("ACTIVE"=>"Y", "LID"=>LANG));
while($rub->ExtractFields("r_")):
?>
    <input
     type="checkbox"
     name="sf_RUB_ID[]" value="<?echo $r_ID?>">
    <?echo $r_NAME?> (<?echo CRubric::GetSubscriptionCount($r_ID);?>)<br>
<?
endwhile;
?>


Update

CRubric::Update

CRubric::Update(
    $ID,
    $arFields
);

The method Update updates the mailing list.

Parameters

Parameter | Description
$ID | The mailing list ID.
$arFields | Associated array containing keys and values of the Mailing list object fields.

Return Values

Returns true on success. In case of an error, it returns false and the class variable LAST_ERROR contains the error description.

Example

$rubric = new CRubric;
$arFields = Array(
    "ACTIVE" => ($ACTIVE <> "Y"? "N":"Y"),
    "NAME" => $NAME,
    "SORT" => $SORT,
    "DESCRIPTION" => $DESCRIPTION,
    "LID" => $LID
);
if($ID>0)
{
    if(!$rubric->Update($ID, $arFields))
        echo $rubric->LAST_ERROR;
}


CSubscription

The CSubscription class is used with subscriptions.

Methods

Method | Description
Add | The method adds a subscription and sends the message containing the subscription confirmation code to the subscriber unless he has chosen not to receive such messages.
Authorize | The method authorizes a visitor before he can start modifying his subscription. Successful authorization is stored in the PHP session.
ConfirmEvent | The method adds an event SUBSCRIBE_CONFIRM to send the message containing the subscription confirmation code to the subscriber. The message is created using the template SUBSCRIBE_CONFIRM (subscription confirmation).
Delete | The method deletes a subscription.
GetByEmail | The method returns a subscription by the unique e-mail address.
GetByID | The method returns a subscription by its ID.
GetList | The method returns a filtered list of subscriptions.
GetRubricArray | The method returns an array of the ID's of subscriptions to which this e-mail address is subscribed.
GetRubricList | The method returns the selection of subscriptions to which this e-mail address is subscribed.
GetUserSubscription | The method returns an array containing fields of the current user subscription. The subscription is identified by the e-mail stored in the visitor cookie or by the authorized user e-mail.
IsAuthorized | The method checks if the current user is authorized to access the subscription preferences.
Update | The method updates the subscription properties.


Add

CSubcription::Add

CSubcription::Add(
    $arFields,
    $SITE_ID=SITE_ID
);

The method Add adds a subscription and sends the message containing the subscription confirmation code to the subscriber unless he has chosen not to receive such messages.

Parameters

Parameter | Description
$arFields Associated array containing the keys and values of Subscription object fields. The following fields can also be used:
  • RUB_ID - array of ID's of the subscriptions to which a user subscribes;
  • SEND_CONFIRM - specifies to send the message containing the confirmation code to the subscriber (Y/N).
$SITE_ID | The ID of the site used to determine the template of the subscription confirmation message. The parameter has the default value of the current site ID.

Return Values

Returns the subscription ID on success. In case of an error, it returns false and the class variable LAST_ERROR contains the error description.

Example

//there must be at least one newsletter category
if(!is_array($RUB_ID) || count($RUB_ID) == 0)
    $strWarning .= "There must be at least one category."."<br>";

if($strWarning == "")
{
    $arFields = Array(
        "USER_ID" => ($USER->IsAuthorized()? $USER->GetID():false),
        "FORMAT" => ($FORMAT <> "html"? "text":"html"),
        "EMAIL" => $EMAIL,
        "ACTIVE" => "Y",
        "RUB_ID" => $RUB_ID
    );

    //can add without authorization
    $ID = $subscr->Add($arFields);
    if($ID>0)
        CSubscription::Authorize($ID);
    else
        $strWarning .= "Error adding subscription: ".$subscr->LAST_ERROR."<br>";
}


Authorize

CSubcription::Authorize

CSubcription::Authorize(
    $ID,
    $CONFIRM_CODE=false
);

The method Authorize is used to authorize a visitor before he can start modifying his subscription. Successful authorization is stored in the PHP session.

In case of anonymous subscription, authorization is checked by the subscription confirmation code. If the subscription belongs to a registered user, the access is only given to the authorized user who is the owner of this subscription.

Parameters

Parameter | Description
$ID | The subscription ID.
$CONFIRM_CODE | Access authorization password. Should be the same as the subscription confirmation code. If the parameter has the value false, authorization is always performed.

Return Values

Returns true on success, or false otherwise.

Example

//try to authorize subscription by CONFIRM_CODE or user password AUTH_PASS
if($ID > 0 && !CSubscription::IsAuthorized($ID))
{
    if($str_USER_ID > 0 && !empty($AUTH_PASS))
    {
        //trying to login user
        $usr = CUser::GetByID($str_USER_ID);
        if(($usr_arr = $usr->Fetch()))
        {
            $res = $USER->Login($usr_arr["LOGIN"], $AUTH_PASS);
            if($res["TYPE"] == "ERROR")
                $strWarning .= $res["MESSAGE"];
        }
    }
    CSubscription::Authorize($ID, (empty($AUTH_PASS)? $CONFIRM_CODE:$AUTH_PASS));
}


ConfirmEvent

CSubcription::ConfirmEvent

CSubcription::ConfirmEvent(
 $ID,
 $SITE_ID=SITE_ID
);

The method ConfirmEvent adds an event SUBSCRIBE_CONFIRM that will send the message containing the subscription confirmation code to the subscriber. The message is created using the template "SUBSCRIBE_CONFIRM" (subscription confirmation).

Parameters

Parameter | Description
$ID | The subscription ID.
$SITE_ID | The ID of the site used to determine the template of the subscription confirmation message. The parameter has the default value of the current site ID.

Return Values

Returns true on success, or false otherwise.

Example

if($ID > 0)
{
    //confirmation code request
    if($action == "sendcode")
    {
        if(CSubscription::ConfirmEvent($ID))
            echo "Subscription confirmation was sent successfully";
    }
}


CSubscription fields

The CSubscription class uses the following fields with the subscription object.

Field | Description | Type | Required.
ID | The subscription ID. | int | Yes
DATE_INSERT | The date the subscription was added. | datetime |
DATE_UPDATE | The date of the record modification. | datetime |
USER_ID | The ID of the subscribed user. If NULL, the subscription is anonymous. | int |
ACTIVE | Subscription active state (Y/N). If subscription is inactive, no messages are sent to this e-mail address. | char(1) |
EMAIL | The unique subscription e-mail. | string(255) | Yes
FORMAT | Format of the message specified in the subscriber preferences (text/html). | string(4) |
CONFIRM_CODE | Subscription confirmation code (password). | string(8) |
CONFIRMED | Subscription confirmation state (Y/N). | char(1) |
DATE_CONFIRM | The date of the subscription confirmation. | datetime |


Delete

CSubcription::Delete

CSubcription::Delete(
 $ID
);

The method Delete deletes a subscription.

Parameters

Parameter | Description
$ID | The subscription ID.

Return Values

Returns an instance of the CDBResult class on success, or false otherwise.

Example

if (($res = CSubscription::Delete($ID)) &&
    $res->AffectedRowsCount() < 1 ||
    $res == false)
    echo "Error deleting subscription.";
else
    echo "Subscription deleted.";


GetByEmail

CSubcription::GetByEmail

CSubcription::GetByEmail(
    $email
);

The method GetByEmail returns a subscription by the unique e-mail address.

Parameters

Parameter | Description
$email | The subscriber's unique e-mail address.

Return Values

Returns an instance of the CDBResult class. The fields of the Subscription object become available after calling one of the CDBResult methods.

Example

//new or existing subscription?
//ID==0 indicates new subscription
if(strlen($sf_EMAIL) > 0 || $ID > 0)
{
    if($ID > 0)
        $subscription = CSubscription::GetByID($ID);
    else
        $subscription = CSubscription::GetByEmail($sf_EMAIL);

    if($subscription->ExtractFields("str_"))
        $ID = (integer)$str_ID;
    else
        $ID=0;
}
else
    $ID = 0;


GetByID

CSubcription::GetByID

CSubcription::GetByID(
 $ID
);

The method GetByID returns a subscription by its ID..

Parameters

Parameter | Description
$ID | The subscription ID.

Return Values

Returns an instance of the CDBResult class. The fields of the Subscription object become available after calling one of the CDBResult methods.

Example

//new or existing subscription?
//ID==0 indicates new subscription
if(strlen($sf_EMAIL) > 0 || $ID > 0)
{
    if($ID > 0)
        $subscription = CSubscription::GetByID($ID);
    else
        $subscription = CSubscription::GetByEmail($sf_EMAIL);

    if($subscription->ExtractFields("str_"))
        $ID = (integer)$str_ID;
    else
        $ID=0;
}
else
    $ID = 0;


GetList

CSubcription::GetList

CSubcription::GetList(
    $aSort=array(),
    $aFilter=array()
);

The method GetList returns a filtered list of subscriptions.

Parameters

Parameter Description
$aSort Array containing the sort criteria entries in the form of "field name"=>"direction".

The field name can be the following:
  • ID - the subscription ID;
  • DATE_INSERT - the date the subscription was added;
  • ACT - active state flag;
  • CONF - confirmation state flag;
  • EMAIL - e-mail address of the subscription;
  • FMT - format of the subscription message;
  • USER - the used ID.
The direction can be one of the following:
  • ASC - ascending;
  • DESC - descending.
For example:
array("EMAIL"=>"ASC", "ACT"=>"DESC")
$aFilter Array containing the filter entries in the form "field name"=>"filter value".

The field name can be the following:
  • ID - the subscription ID (complex logic allowed);
  • EMAIL - e-mail address (complex logic allowed);
  • UPDATE_1 - the earliest possible date of modification;
  • UPDATE_2 - the latest possible date of modification;
  • INSERT_1 - the earliest possible date of subscription adding;
  • INSERT_2 - the latest possible date of subscription adding;
  • USER - the user (complex logic allowed in fields ID, LOGIN, NAME, LAST_NAME);
  • USER_ID - the user ID (complex logic allowed);
  • ANONYMOUS - flag indicating the subscription is anonymous;
  • CONFIRMED - flag indicating the subscription is confirmed;
  • ACTIVE - the subscription active state flag;
  • FORMAT - the subscription format;
  • RUBRIC - the subscription rubrics in the form of an array of ID's and a string built using the filter logic rules.
For example:
array("CONFIRMED"=>"Y", "ACTIVE"=>"Y")

Return Values

Returns an instance of the CDBResult class. The Subscription object fields become available after calling one of the CDBResult methods.

Example

//selects rubrics to which message is to be sent
$aPostRub = array();
$post_rub = CPostingGeneral::GetRubricList($post_arr["ID"]);
while($post_rub_arr = $post_rub->Fetch())
    $aPostRub[] = $post_rub_arr["ID"];

//active and confirmed e-mail addresses subscribed to rubrics
$subscr = CSubscription::GetList(
    array("ID"=>"ASC"),
    array("RUBRIC"=>$aPostRub, "CONFIRMED"=>"Y", "ACTIVE"=>"Y",
        "FORMAT"=>$post_arr["SUBSCR_FORMAT"], "EMAIL"=>$post_arr["EMAIL_FILTER"])
);
while(($subscr_arr = $subscr->Fetch()))
    $aEmail[] = $subscr_arr["EMAIL"];


GetRubricArray

CSubcription::GetRubricArray

CSubcription::GetRubricArray(
    $ID
);

The method GetRubricArray returns an array of the ID's of subscriptions to which this e-mail address is subscribed.

Parameters

Parameter | Description
$ID | The subscription ID.

Return Values

Array of integer subscription ID's.

Example

<?
//shows all subscription categories and checks subscribed one
$aSubscrRub = CSubscription::GetRubricArray($ID);
$rub = CRubric::GetList(
    array("LID"=>"ASC", "SORT"=>"ASC", "NAME"=>"ASC"),
    array("ACTIVE"=>"Y", "LID"=>LANG)
);
while($rub->ExtractFields("r_")):
    $bChecked = in_array($r_ID, $aSubscrRub);
?>
<input
 type="checkbox"
 name="RUB_ID[]"
 value="<?echo $r_ID?>"<?if($bChecked) echo " checked"?>>
<?echo $r_NAME?><br>
<?
endwhile;
?>


GetRubricList

CSubcription::GetRubricList

CSubcription::GetRubricList(
    $ID
);

The method GetRubricList returns the selection of subscriptions to which this e-mail address is subscribed.

Parameters

Parameter | Description
$ID | The subscription ID.

Return Values

Returns an instance of the CDBResult class. The fields of the Subscription object become available after calling one of the CDBResult methods.

Example

//array of subscribed categories
function GetRubricArray($ID)
{
    $aSubscrRub = array();
    if($ID>0)
    {
        $subscr_rub = CSubscription::GetRubricList($ID);
        while($subscr_rub_arr = $subscr_rub->Fetch())
            $aSubscrRub[] = $subscr_rub_arr["ID"];
    }
    return $aSubscrRub;
}


GetUserSubscription

CSubscription::GetUserSubscription

CSubscription::GetUserSubscription();

The method GetUserSubscription returns an array containing fields of the current user subscription. The subscription is identified by the e-mail stored in the visitor cookie or by the authorized user e-mail.

Parameters

No parameters.

Return Values

Returns an array containing the Subscription object fields. If the visitor's subscription could not be found, the array array("ID"=>0, "EMAIL"=>"") is returned.

Example

//get current user subscription from cookies
$aSubscr = CSubscription::GetUserSubscription();

//get user's newsletter categories
$aSubscrRub = CSubscription::GetRubricArray(intval($aSubscr["ID"]));

//show subscription form
//.....


IsAuthorized

CSubcription::IsAuthorized

CSubcription::IsAuthorized(
    $ID
);

The method IsAuthorized checks if the current user is authorized to access the subscription preferences.

Parameters

Parameter | Description
$ID | The subscription ID.

Return Values

Returns true if the visitor is authorized to access the subscription preferences, or false otherwise.

Example

//check if we are already authorized to show password field
$bShowPass = true;
$aSubscr = CSubscription::GetUserSubscription();
if($aSubscr["ID"] > 0)
{
    //try to authorize user account's subscription
    if ($aSubscr["USER_ID"]>0 &&
        !CSubscription::IsAuthorized($aSubscr["ID"]))
    {
        CSubscription::Authorize($aSubscr["ID"], "");
    }

    //check authorization
    if (CSubscription::IsAuthorized($aSubscr["ID"]))
        $bShowPass = false;
}


Update

CSubcription::Update

CSubcription::Update(
    $ID,
    $arFields,
    $SITE_ID=SITE_ID
);

The method Update updates the subscription properties. If the e-mail address becomes modified, the method unconfirmes the subscription and fires an event which tells to send a message containing the subscription confirmation code unless this is not explicitly forbidden. If the subscription is not confirmed and the array of fields includes the correct CONFIRM_CODE, the subscription becomes confirmed.

Parameters

Parameter | Description
$ID | The subscription ID.
$arFields Associated array containing the keys and values of Subscription object fields. The following fields can also be used:
  • RUB_ID - array containing the ID's of subscriptions to which the e-mail is subscribed;
  • SEND_CONFIRM - specifies to send the message containing the subscription confirmation code to the subscriber when the e-mail address becomes modified (Y/N).
$SITE_ID | The ID of the site used to determine the template of the subscription confirmation message. The parameter has the default value of the current site ID.

Return Values

Returns true on success. In case of an error, it returns false and the class variable LAST_ERROR contains the error description.

On success, the class variable LAST_MESSAGE contains a string with the message code. The following values are possible:

  • "CONF" - the subscription is confirmed;
  • "SENT" - an event which tells to send a message containing the subscription confirmation code is fired.

Example

//confirmation code from letter or confirmation form
if($CONFIRM_CODE <> "" && $ID > 0 && empty($action))
{
    if($str_CONFIRMED <> "Y")
    {
        //subscribtion confirmation
        if($subscr->Update($ID, array("CONFIRM_CODE"=>$CONFIRM_CODE)))
            $str_CONFIRMED = "Y";
        $strWarning .= $subscr->LAST_ERROR;
        $iMsg = $subscr->LAST_MESSAGE;
    }
}

//*************************
//form actions processing
//*************************
if($ID > 0)
{
    if($action == "unsubscribe" && CSubscription::IsAuthorized($ID))
    {
        //unsubscription
        if($subscr->Update($ID, array("ACTIVE"=>"N")))
        {
            $str_ACTIVE = "N";
            $iMsg = "UNSUBSCR";
        }
    }
    if($action == "activate" && CSubscription::IsAuthorized($ID))
    {
        //activation
        if($subscr->Update($ID, array("ACTIVE"=>"Y")))
        {
            $str_ACTIVE = "Y";
            $iMsg = "ACTIVE";
        }
    }
}


Installation

Perform the following operations to install the module.

  1. Make sure the Kernel version is no less than 3.0.5 (the Kernel version can be checked in the lower left corner of the administrative pages). The installer will not allow you to install the module if the kernel version does not correspond with the required one.
  2. Create a group of users responsible for tickets and a group of ticket administrators.
  3. Move to the page Modules and click Set beside the Techsupport module.
  4. Set the required values of the following module parameters:
    Parameter | Description
    Techsupport directory | Path to the techsupport scripts in the public section. If you have specified this parameter at the moment of installation, the specified folder will be created for each site, and all the required scripts will be copied there.
  5. Click Install.
  6. Set up a a menu in the public section of the site for the “ticket_list.php” script.
  7. Fill in the techsupport dictionary.

The installation stipulates creation of the following tables in the database:

  • b_ticket – the ticket table;
  • b_ticket_message – the message table (each ticket contains one or more messages);
  • b_ticket_dictionary – the ticket dictionary table;
  • b_ticket_online – table containing the information about users' access to a ticket;

After the required tables are created the default dictionary information is loaded.

When the tables are ready, all the required administrative scripts are copied from the directory \bitrix\modules\support\install\public\bitrix\admin\ to the directory \bitrix\admin\.

If required, the directory with the name is specified in the parameter Techsupport directory is created in each site.

After this, the following files are copied to these directories:

  • ticket_list.php – list of tickets;
  • ticket_edit.php – editing of a ticket;
  • ticket_message_edit.php – editing of a message.

All the above files are copied from the directory \bitrix\modules\support\install\public\.


Classes

CTicket

The CTicket class is used with trouble tickets.

Methods

Method | Description
Set | Creates a new ticket, or modifies the existing one.
GetList | Obtains a filtered list of techsupport tickets.
GetByID | Returns information about a ticket.
GetMessageList | Obtains a list of messages in one ticket.
GetMessageByID | Returns information about a message.

CTicketDictionary

The CTicketDictionary class is used with the ticket dictionary.

Methods

Method | Description
GetList | Obtains a filtered list of techsupport tickets.
GetByID | Obtains information about one record in the dictionary.


CTicket

The CTicket class is used with tickets.

Methods

Method | Description
Set | The method creates a new ticket, or modifies the existing one.
GetList | The method obtains a filtered list of techsupport tickets.
GetByID | The method returns information about a ticket.
GetMessageList | The method obtains a list of messages in one ticket.
GetMessageByID | The method returns information about a message.


Delete

CTicket::Delete

record set
CTicket::Delete(
 int TICKET_ID,
 char(1) CHECK_RIGHTS="Y"
);

The method Delete deletes a ticket.

Parameters

Parameter | Description
TICKET_ID | The ticket ID.
CHECK_RIGHTS | If set to "Y", the current user deletion permission is checked. If "N", the permission is not checked.


DeleteMessage

CTicket::DeleteMessage

record set
CTicket::DeleteMessage(
 int MESSAGE_ID,
 char(1) CHECK_RIGHTS="Y"
);

The method DeleteMessage is used to delete a message.

Parameters

Parameter | Description
MESSAGE_ID | The message ID.
CHECK_RIGHTS | If set to "Y", the current user deletion permission is checked. If "N", the permission is not checked.


GetByID

CTicket::GetByID

record set
CTicket::GetByID(
 int ID,
 char(2) lang=LANG,
 char(1) CHECK_RIGHTS="Y",
 char(1) get_user_name="Y",
 char(1) get_dictionary_name="Y"
);

The method GetByID returns information about a ticket.

Parameters

Parameter | Description
ID | The ticket ID.
lang | Two-character identifier of the language whose format is to be used to get the time parameters of a ticket (time of creation, modification, closing). The current site identifier is used by default.
CHECK_RIGHTS | If set to "Y", only the tickets the current user can view are selected (default). If "N", all tickets regardless of the current user permissions are selected.
get_user_name If set to "Y", the following fields describing the parameters of users related to this ticket are also returned when selecting tickets:
  • OWNER_LOGIN
  • OWNER_NAME
  • RESPONSIBLE_LOGIN
  • RESPONSIBLE_NAME
  • MODIFIED_LOGIN
  • MODIFIED_NAME
  • LAST_MESSAGE_LOGIN
  • LAST_MESSAGE_NAME
  • CREATED_LOGIN
  • CREATED_EMAIL
  • CREATED_NAME
If "N", all the above fields are not returned which speeds up the method execution.
get_dictionary_name If set to "Y", the following fields from the techsupport dictionary are also returned when selecting tickets:
  • CATEGORY_NAME
  • CATEGORY_SID
  • CRITICALITY_NAME
  • CRITICALITY_SID
  • STATUS_NAME
  • STATUS_SID
  • MARK_NAME
  • MARK_SID
  • SOURCE_NAME
  • SOURCE_SID
If "N", all the above fields are not returned which speeds up the method execution.

Example

The following is an example of a single row of selection returned by CTicket::GetByID.

Array
(
 [ID] => 647
 [LID] => ru
 [DATE_CREATE] => 17.03.2004 15:27:05
 [TIMESTAMP_X] => 19.04.2004 13:37:30
 [DATE_CLOSE] =>
 [AUTO_CLOSED] =>
 [AUTO_CLOSE_DAYS] =>
 [CATEGORY_ID] => 27
 [CRITICALITY_ID] => 8
 [STATUS_ID] => 14
 [MARK_ID] => 21
 [SOURCE_ID] =>
 [TITLE] => Commercial catalogue export and import
 [MESSAGES] => 30
 [OWNER_USER_ID] => 166
 [OWNER_GUEST_ID] => 14649
 [OWNER_SID] =>
 [CREATED_USER_ID] => 166
 [CREATED_GUEST_ID] => 14649
 [CREATED_MODULE_NAME] => support
 [RESPONSIBLE_USER_ID] => 12
 [MODIFIED_USER_ID] => 166
 [MODIFIED_GUEST_ID] => 16218
 [MODIFIED_MODULE_NAME] => support
 [LAST_MESSAGE_USER_ID] => 166
 [LAST_MESSAGE_GUEST_ID] => 16218
 [LAST_MESSAGE_SID] =>
 [SUPPORT_COMMENTS] =>
 [OWNER_LOGIN] => row
 [OWNER_EMAIL] => row@machaon.com
 [OWNER_NAME] => Rowan Atkinson
 [RESPONSIBLE_LOGIN] => bradpitt
 [RESPONSIBLE_EMAIL] => bradpitt@bitrix.com
 [RESPONSIBLE_NAME] => Brad Pitt
 [MODIFIED_LOGIN] => row
 [MODIFIED_EMAIL] => row@machaon.com
 [MODIFIED_NAME] => Rowan Atkinson
 [LAST_MESSAGE_LOGIN] => row
 [LAST_MESSAGE_EMAIL] => row@machaon.com
 [LAST_MESSAGE_NAME] => Rowan Atkinson
 [CREATED_LOGIN] => row
 [CREATED_EMAIL] => row@machaon.com
 [CREATED_NAME] => Rowan Atkinson
 [CATEGORY_NAME] => Installation
 [CATEGORY_DESC] =>
 [CATEGORY_SID] =>
 [CRITICALITY_NAME] => Medium
 [CRITICALITY_DESC] =>
 [CRITICALITY_SID] => middle
 [STATUS_NAME] => Being processed
 [STATUS_DESC] =>
 [STATUS_SID] =>
 [MARK_NAME] => Ok
 [MARK_DESC] =>
 [MARK_SID] =>
 [SOURCE_NAME] =>
 [SOURCE_DESC] =>
 [SOURCE_SID] =>
 [LAMP] => yellow
);


GetList

CTicket::GetList

record set
CTicket::GetList(
 varchar &by,
 varchar &order,
 array arFilter=array(),
 boolean &is_filtered,
 char(1) CHECK_RIGHTS="Y",
 char(1) get_user_name="Y",
 char(1) get_dictionary_name="Y",
 char(2) lang=LANG
);

The method GetList obtains a list of techsupport tickets.

Parameters

Parameter | Description
by Identifier specifying the name of the field by which sorting is to be performed. The following values are possible:
  • s_id - by the ID;
  • s_lid - by the site for which the ticket was created;
  • s_lamp - by indicator;
  • s_date_create - by the date of creation;
  • s_timestamp - by the modification date;
  • s_date_close - by the closing date;
  • s_owner - by creator;
  • s_modified_by - by the ID of the user who has modified the ticket;
  • s_title - by the title;
  • s_responsible - by the ID of the person in charge;
  • s_messages - by the number of messages;
  • s_category - by the category ID;
  • s_criticality - by the emergency level ID;
  • s_status - by the status ID;
  • s_mark - by the mark ID;
  • s_online - by the number of users.
order Sort order. One of the following values is possible:
  • desc - descending (default);
  • asc - ascending
arFilter An array used to filter values. The following keys are possible:
  • ID - the ticket ID (complex logic allowed);
  • ID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the ticket ID (default). If "N", the method performs loose searches (entry is sufficient);
  • LID - the site ID;
  • LID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the language ID (default). If "N", the method performs loose searches (entry is sufficient);
  • LAMP - array of indicator values: "red", "yellow", "green", "green_s", "grey";
  • DATE_CREATE_1 - lower bound of the date range when the ticket could be created;
  • DATE_CREATE_2 - upper bound of the date range when the ticket could be created;
  • DATE_TIMESTAMP_1 - lower bound of the date range when the ticket could be modified;
  • DATE_TIMESTAMP_2 - upper bound of the date range when the ticket could be modified;
  • DATE_CLOSE_1 - lower bound of the date range when the ticket could be closed;
  • DATE_CLOSE_2 - upper bound of the date range when the ticket could be closed;
  • AUTO_CLOSE_DAYS1 - lower bound of the day range on expiry of which the ticket will be automatically closed in case the author does not respond;
  • AUTO_CLOSE_DAYS2 - upper bound of the day range on expiry of which the ticket will be automatically closed in case the author does not respond;
  • TICKET_TIME_1 - lower bound of the day range from the ticket opening till closing;
  • TICKET_TIME_2 - upper bound of the day range from the ticket opening till closing;
  • TITLE - the ticket title (complex logic allowed);
  • TITLE_EXACT_MATCH - set to "Y" for exact match searches when filtering by the ticket title (default). If "N", the method performs loose searches (entry is sufficient);
  • MESSAGES1 - lower bound of the range of messages in the ticket;
  • MESSAGES1 - upper bound of the range of messages in the ticket;
  • OWNER - the ticket owner. The search is performed by the user ID, login, first and last names and the symbolic code (complex logic allowed);
  • OWNER_EXACT_MATCH - set to "Y" for exact match searches when filtering by the ticket owner (default). If "N", the method performs loose searches;
  • CREATED_BY - the ticket creator. The search is performed by the user ID, login, first and last names and the name of the module from which the ticket originates (complex logic allowed);
  • CREATED_BY_EXACT_MATCH - set to "Y" for exact match searches when filtering by the ticket creator (default). If "N", the method performs loose searches;
  • MODIFIED_BY - the person who modified the ticket. The search is performed by the user ID, login, first and last names and the name of the module from which the ticket was modified (complex logic allowed);
  • MODIFIED_BY_EXACT_MATCH - set to "Y" for exact match searches when filtering by the status symbolic code (default). If "N", the method performs loose searches;
  • RESPONSIBLE - the person in charge of the ticket. The search is performed by the user ID, login, first and last names (complex logic allowed);
  • RESPONSIBLE_EXACT_MATCH - set to "Y" for exact match searches when filtering by the person in charge of the ticket (default). If "N", the method performs loose searches;
  • RESPONSIBLE_ID - the ID of the user responsible for the ticket. If set to "0", only the tickets without a responsible person are selected;
  • CATEGORY - the ticket category ID (0 - no category);
  • CATEGORY_SID - the symbolic code of the ticket category (complex logic allowed);
  • CATEGORY_SID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the category symbolic code (default). If "N", the method performs loose searches;
  • CRITICALITY - the ID of ticket emergency level (0 - no emergency level);
  • CRITICALITY_SID - the emergency level symbolic code (complex logic allowed);
  • CRITICALITY_SID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the emergency level symbolic code (default). If "N", the method performs loose searches;
  • STATUS - the ID of the ticket status (0 - no status);
  • STATUS_SID - the ticket status symbolic code (complex logic allowed);
  • STATUS_SID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the status symbolic code (default). If "N", the method performs loose searches;
  • MARK - the ID of the reply mark (0 - no mark);
  • MARK_SID - the reply mark symbolic code (complex logic allowed);
  • SOURCE - the source ID (0 - from the web);
  • SOURCE_SID - the source symbolic code (complex logic allowed);
  • SOURCE_SID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the source symbolic code (default). If "N", the method performs loose searches;
  • MESSAGE - the message body text (complex logic allowed);
  • MESSAGE_EXACT_MATCH - set to "Y" for exact match searches when filtering by the message body text (default). If "N", the method performs loose searches;
  • LAST_MESSAGE_USER_ID - the ID of a user who has created the last message in the ticket (complex logic allowed);
  • LAST_MESSAGE_USER_ID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the ID of a user who has created the last message in the ticket (default). If "N", the method performs loose searches;
  • LAST_MESSAGE_SID - the symbolic code of a user who has created the last message in the ticket (if the source is an e-mail, this can be the e-mail address; if the source is a phone call, this can be the phone number) (complex logic allowed);
  • LAST_MESSAGE_SID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the symbolic code of a user who has created the last message in the ticket (default). If "N", the method performs loose searches;
  • SUPPORT_COMMENTS - techsupport comments which can be viewed by users who are members of the techsupport user group;
  • SUPPORT_COMMENTS_EXACT_MATCH - set to "Y" for exact match searches when filtering by the techsupport comments (default). If "N", the method performs loose searches;
is_filtered | On return, this variable contains true if the returned list of contracts is filtered by any above criteria, or false otherwise.
CHECK_RIGHTS | If set to "Y", only the tickets the current user can view are selected (default). If "N", all tickets regardless of the current user permissions are selected.
get_user_name If set to "Y", the following fields describing the parameters of users related to this ticket are also returned when selecting tickets:
  • OWNER_LOGIN
  • OWNER_NAME
  • RESPONSIBLE_LOGIN
  • RESPONSIBLE_NAME
  • MODIFIED_LOGIN
  • MODIFIED_NAME
  • LAST_MESSAGE_LOGIN
  • LAST_MESSAGE_NAME
  • CREATED_LOGIN
  • CREATED_EMAIL
  • CREATED_NAME
If "N", all the above fields are not returned which speeds up the method execution.
get_dictionary_name If set to "Y", the following fields from the techsupport dictionary are also returned when selecting tickets:
  • CATEGORY_NAME
  • CATEGORY_SID
  • CRITICALITY_NAME
  • CRITICALITY_SID
  • STATUS_NAME
  • STATUS_SID
  • MARK_NAME
  • MARK_SID
  • SOURCE_NAME
  • SOURCE_SID
If "N", all the above fields are not returned which speeds up the method execution.
lang | Two-character identifier of the language whose format is to be used to get the time parameters of a ticket (time of creation, modification, closing). The current site identifier is used by default.

Example

<?
$FilterArr = Array(
 "find_id",
 "find_lid",
 "find_lamp",
 "find_date_create1",
 "find_date_create2",
 "find_date_timestamp1",
 "find_date_timestamp2",
 "find_date_close1",
 "find_date_close2",
 "find_close",
 "find_ticket_time_1",
 "find_ticket_time_2",
 "find_title",
 "find_messages1",
 "find_messages2",
 "find_owner",
 "find_created_by",
 "find_responsible",
 "find_responsible_id",
 "find_category_id",
 "find_criticality_id",
 "find_status_id",
 "find_mark_id",
 "find_source_id",
 "find_modified_by",
 "find_message"
 );

if (strlen($set_filter)>0)
    InitFilterEx($FilterArr,"TICKET_LIST","set",true);
else
    InitFilterEx($FilterArr,"TICKET_LIST","get",true);

if (strlen($del_filter) > 0)
    DelFilterEx($FilterArr,"TICKET_LIST",true);

if (CheckFilter())
{
 $arFilter = Array(
 "ID" => $find_id,
 "LID" => $find_lid,
 "LAMP" => $find_lamp,
 "DATE_CREATE_1" => $find_date_create1,
 "DATE_CREATE_2" => $find_date_create2,
 "DATE_TIMESTAMP_1" => $find_date_timestamp1,
 "DATE_TIMESTAMP_2" => $find_date_timestamp2,
 "DATE_CLOSE_1" => $find_date_close1,
 "DATE_CLOSE_2" => $find_date_close2,
 "CLOSE" => $find_close,
 "TICKET_TIME_1" => $find_ticket_time_1,
 "TICKET_TIME_2" => $find_ticket_time_2,
 "TITLE" => $find_title,
 "MESSAGES1" => $find_messages1,
 "MESSAGES2" => $find_messages2,
 "OWNER" => $find_owner,
 "CREATED_BY" => $find_created_by,
 "RESPONSIBLE" => $find_responsible,
 "RESPONSIBLE_ID" => $find_responsible_id,
 "CATEGORY" => $find_category_id,
 "CRITICALITY" => $find_criticality_id,
 "STATUS" => $find_status_id,
 "MARK" => $find_mark_id,
 "SOURCE" => $find_source_id,
 "MODIFIED_BY" => $find_modified_by,
 "MESSAGE" => $find_message
 );
}
$tickets = CTicket::GetList($by,
                            $order,
                            $arFilter,
                            $is_filtered);
?>


GetMessageByID

CTicket::GetMessageByID

record set
CTicket::GetMessageByID(
 int ID,
 char(1) CHECK_RIGHTS="Y",
 char(1) get_user_name="Y"
);

The method GetMessageByID returns information about a message.

Parameters

Parameter | Description
ID | The message ID.
CHECK_RIGHTS | If set to "Y", this ticket is returned only if the user has any permission for this ticket. If "N", ticket is selected regardless of the current user permissions.
get_user_name If set to "Y", the following fields describing the parameters of users related to this message are also returned when selecting messages:
  • OWNER_EMAIL
  • OWNER_LOGIN
  • OWNER_NAME
  • CREATED_EMAIL
  • CREATED_LOGIN
  • CREATED_NAME
  • MODIFIED_EMAIL
  • MODIFIED_LOGIN
  • MODIFIED_NAME.
If "N", all the above fields are not returned which speeds up the method execution.

Example

The following is an example of a single row of selection returned by CTicket::GetMessageByID.

Array
(
 [ID] => 3585
 [TIMESTAMP_X] => 27.04.2004 12:46:02
 [DATE_CREATE] => 13.04.2004 11:57:04
 [C_NUMBER] => 22
 [TICKET_ID] => 647
 [MESSAGE] => "OK, then what about activating a group"
              "specified in the uploaded file? You can"
              "desctivate a rubric on upload, but cannot activate it."
 [MESSAGE_SEARCH] => "OK, THEN WHAT ABOUT ACTIVATING A GROUP"
                     "SPECIFIED IN THE UPLOADED FILE? YOU CAN"
                     "DESCTIVATE A RUBRIC ON UPLOAD"
                     "BUT CANNOT ACTIVATE IT."
 [IMAGE] => 996
 [OWNER_USER_ID] => 166
 [OWNER_GUEST_ID] => 16218
 [OWNER_SID] =>
 [SOURCE_ID] => 0
 [CREATED_USER_ID] => 166
 [CREATED_GUEST_ID] => 16218
 [CREATED_MODULE_NAME] => support
 [MODIFIED_USER_ID] => 2
 [MODIFIED_GUEST_ID] => 6221
 [OWNER_EMAIL] => row@machaon.com
 [OWNER_LOGIN] => row
 [OWNER_NAME] => Rowan Atkinson
 [CREATED_EMAIL] => row@machaon.com
 [CREATED_LOGIN] => row
 [CREATED_NAME] => Rowan Atkinson
 [MODIFIED_EMAIL] => nessy@bitrix.com
 [MODIFIED_LOGIN] => nessy
 [MODIFIED_NAME] => Vitaly Kaplich
)


GetMessageList

CTicket::GetMessageList

record set
CTicket::GetMessageList(
 varchar &by,
 varchar &order,
 array arFilter=array(),
 boolean &is_filtered,
 char(1) CHECK_RIGHTS="Y",
 char(1) get_user_name="Y"
);

The method GetMessageList obtains a list of messages in one ticket.

Parameters

Parameter | Description
by Identifier specifying the name of the field by which sorting is to be performed. The following values are possible:
  • s_id - by the ID;
  • s_number - by the ordinal.
order Sort order. One of the following values is possible:
  • desc - descending (default);
  • asc - ascending.
arFilter An array used to filter values. The following keys are possible:
  • ID - the message ID (complex logic allowed);
  • ID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the message ID (default). If "N", the method performs loose searches (entry is sufficient) when filtering by the message ID;
  • TICKET_ID - the ticket ID (complex logic allowed);
  • TICKET_ID_EXACT_MATCH - set to "Y" for exact match searches when filtering by the ticket ID (default). If "N", the method performs loose searches (entry is sufficient) when filtering by the ticket ID;
  • IS_HIDDEN - if set to "Y", only the hidden tickets are selected. If "N", all the non-hidden tickets are selected;
  • IS_LOG - if set to "Y", only the log history records are selected; if "N", only the existing records are selected;
is_filtered | On return, this variable contains true if the returned list of contracts is filtered by any above criteria, or false otherwise.
CHECK_RIGHTS Flag specifies that the current user permissions should be checked:
  • Y - only the messages the current user can view are returned (default);
  • N - all messages regardless of the current user permissions are returned.
get_user_name If set to "Y", the following fields describing the parameters of users related to this message are also returned when selecting messages:
  • OWNER_EMAIL
  • OWNER_LOGIN
  • OWNER_NAME
  • CREATED_EMAIL
  • CREATED_LOGIN
  • CREATED_NAME
  • MODIFIED_EMAIL
  • MODIFIED_LOGIN
  • MODIFIED_NAME
If "N", all the above fields are not returned which speeds up the method execution.

Example

<?
$mess = CTicket::GetMessageList($a, $b, array("TICKET_ID" => $ID, "TICKET_ID_EXACT_MATCH" => "Y"), $c, $CHECK_RIGHTS);
$mess->NavStart(50);
$messages = $mess->SelectedRowsCount();
?>


Set

CTicket::Set

int
CTicket::Set(
 array arFields,
 int &MESSAGE_ID,
 int TICKET_ID="",
 char(1) CHECK_RIGHTS="Y"
);

The method Set creates a new ticket or modifies the existing one if a ticket ID is passed in the second parameter. Returns the created ticket ID, or the modified ticket ID.

Parameters

Parameter | Description
arFields An array of the ticket parameters. The following keys are possible in this array:
  • *TITLE - the ticket title (required when creating a new ticket);
  • MESSAGE - message body (required when creating a new ticket);
  • IMAGE - array describing the image to be uploaded. The following keys are possible in this array:
    • name - the original name of an uploaded file;
    • type - type of the uploaded file (for example: "image/gif");
    • tmp_name - name of the temporary file on the server;
    • error - the error code ("0" - no errors);
    • size - size of the uploaded file;
    • MODULE_ID - the module ID ("support");
  • *OWNER_SID - the ticket owner symbolic code. Any value identifying the owner can be specified: e-mail, phone number, address etc.
  • *OWNER_USER_ID - the ticket owner ID (the current user ID by default);
  • *SOURCE_SID - the ticket source symbolic code ((from) "web" by default);
  • *CREATED_MODULE_NAME - the ID of the module from which the ticket originates ("support" by default);
  • **MESSAGE_AUTHOR_SID - the message author symbolic code. Any value identifying the message author can be specified: e-mail, phone number, address etc.;
  • **MESSAGE_AUTHOR_USER_ID - the ID of the user who is the message author (the current user ID by default);
  • **MESSAGE_SOURCE_SID - the message source symbolic code (from web by default);
  • **MODIFIED_MODULE_NAME - the ID of the module from which the ticket was modified ("support" by default);
  • **HIDDEN - if set to "Y", the message is added as hidden and can be viewed only by members of the techsupport user group. If "N", the message is added as visible and can be viewed both by the ticket owner and by members of the techsupport user group (by default);
  • CATEGORY_SID - the category symbolic code;
  • CRITICALITY_SID - the emergency level symbolic code;
  • STATUS_SID - the ticket status symbolic code;
  • MARK_SID - the reply mark symbolic code;
  • RESPONSIBLE_USER_ID - the ID of the user responsible for the ticket.;
  • SUPPORT_COMMENTS - comments which can be viewed only by users who are members of the techsupport user group;
  • CLOSE - "Y" specifies the ticket to be closed; "N" specifies the ticket to remain open;
  • AUTO_CLOSE_DAYS - number of days expire before the ticket is automatically closed in case the author did not respond;
* - the field can be used to create new tickets;
** - the field can be used to modify the existing tickets only.
MESSAGE_ID | The ID of the added message.
TICKET_ID | The ID of the modified ticket.
CHECK_RIGHTS Flag indicating that the current user permissions should be checked:
  • if "Y", the permissions of the current user who is creating or modifying a ticket should be checked;
  • if "N", a ticket can be created and modified disregarding the current user permissions.

Example

// Example of the code adding a new e-mail ticket to the techsupport,
// or adding a new message to the ticket if $TICKET_ID is valid:

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
CModule::IncludeModule("support");
$arFields = array(
 "CREATED_MODULE_NAME" => "mail",
 "MODIFIED_MODULE_NAME" => "mail",
 "OWNER_SID" => "user@mail.com",
 "SOURCE_SID" => "email",
 "MESSAGE_AUTHOR_SID" => "user@mail.com",
 "MESSAGE_SOURCE_SID" => "email",
 "TITLE" => "title",
 "MESSAGE" => "message"
 );

//$TICKET_ID = 866;
$NEW_TICKET_ID = CTicket::Set($arFields, $MESSAGE_ID, $TICKET_ID, "N");
echo "MESSAGE_ID = ".$MESSAGE_ID;
?>


CTicketDictionary

The CTicketDictionary class is used with the ticket dictionary.

Methods

Method | Description
GetList | The method obtains a filtered list of techsupport tickets.
GetByID | The method obtains information about one record in the dictionary.


GetByID

CTicketDictionary::GetByID

record set
CTicketDictionary::GetByID(
 int ID
);

The method GetByID obtains information about a dictionary record.

Parameters

Parameter | Description
ID | The record ID.

Example

The following is an example of a single row of selection returned by CTicketDictionary::GetByID.

Array
(
 [ID] => 3
 [LID] => en
 [C_TYPE] => C
 [SID] =>
 [SET_AS_DEFAULT] => N
 [C_SORT] => 500
 [NAME] => Providing updates
 [DESCR] =>
 [RESPONSIBLE_USER_ID] => 2
 [ EVENT1] => ticket
 [ EVENT2] =>
 [ EVENT3] =>
)


GetList

CTicketDictionary::GetList

record set
CTicketDictionary::GetList(
 varchar &by,
 varchar &order,
 array arFilter=array(),
 boolean &is_filtered
);

The method GetList obtains a list of techsupport tickets.

Parameters

Parameter | Description
by Identifier specifying the name of the field by which sorting is to be performed. The following values are possible:
  • s_id - by the ID;
  • s_c_sort - by the specified sort order;
  • s_sid - by the symbolic code;
  • s_lis - by the language;
  • s_name - by the name;
  • s_responsible - by the ID of the person in charge;
  • s_dropdown - by the specified sort order and name.
order Sort order. One of the following values is possible:
  • desc - descending (default);
  • asc - ascending.
arFilter An array used to filter values. The following keys are possible:
  • ID - by the record ID (complex logic allowed);
  • SID - the symbolic code (complex logic allowed);
  • LID - the site ID;
  • TYPE - type of the record: "C" - category, "K" - emergency level, "S" - status, "M" - reply mark, "F" - frequently used answers, "SR" - source;
  • NAME - name (complex logic allowed);
  • RESPONSIBLE_ID - the ID of the person in charge;
  • RESPONSIBLE - the person in charge. The search is performed by the user ID, login, first and last names (complex logic allowed);
  • DEFAULT - the "Select as default" flag; "Y" - yes, "N" - no.
is_filtered | On return, this variable contains true if the returned list of contracts is filtered by any above criteria, or false otherwise.

Example

<?
$FilterArr = Array(
 "find_id",
 "find_lid",
 "find_type",
 "find_name",
 "find_sid",
 "find_responsible",
 "find_responsible_id",
 "find_default"
 );

if (strlen($set_filter)>0)
    InitFilterEx($FilterArr,
                 "TICKET_DICTIONARY_LIST","set");
else
    InitFilterEx($FilterArr,
                 "TICKET_DICTIONARY_LIST","get");

if (strlen($del_filter) > 0)
    DelFilterEx($FilterArr,
                "TICKET_DICTIONARY_LIST");

$arFilter = Array(
 "ID" => $find_id,
 "LID" => $find_lid,
 "TYPE" => $find_type,
 "NAME" => $find_name,
 "SID" => $find_sid,
 "RESPONSIBLE_ID" => $find_responsible_id,
 "RESPONSIBLE" => $find_responsible,
 "DEFAULT" => $find_default
 );
$tdic = CTicketDictionary::GetList($by,
                                   $order,
                                   $arFilter,
                                   $is_filtered);
?>


Introduction

This section is for use by developers who use the Web Forms module to implement solutions beyond the functions of the module components.

The Web Forms module features:

  • Visual interface for creating web forms, including:
    • building a list of questions and answers;
    • building a list of additional fields;
    • building a list of the web form result statuses;
    • assigning access permissions to a web form and each status individually.
  • Displaying a web form to be filled in.
  • Saving answers to the web form questions in the form of results .
  • Perform additional actions when saving a result:
    • check the input data for correctness;
    • send results via the e-mail;
    • create an event in the Statistics module.
  • Displaying results in a list, as well as the following:
    • edit and update the result;
    • change the result status;
    • delete result;
    • filter results by the customizable set of questions and fields.


Names of HTML web form field names

Names of HTML web form fields

Questions

When displaying a web-form, all answers to questions are represented as HTML fields. Users fill in these fields to answer questions. The table below describes relation between the names of HTML fields and the answer type.

Answer type | Description | Field name | Value
text | Single line text. | form_text_answer_id | Typed text.
textarea | Multiple line text. | form_textarea_answer_id | Typed text.
password | Single line password input text. | form_password_answer_id | Typed text.
date | Single line date input text. | form_date_answer_id | Typed text.
radio | Radio button. | form_radio_question_sid | The selected answer ID.
dropdown | Drop-down list. | form_dropdown_question_sid | The selected answer ID.
checkbox | Check button. | form_checkbox_question_sid[] | The selected answer ID's array.
multiselect | Multiple selection list. | form_multiselect_question_sid[] | The selected answer ID's array.
file | File upload field. | form_file_answer_id | Array describing the uploaded file.
image | Image field. | form_image_answer_id | Array describing the uploaded file.
Legend
  • answer_id - the answer ID;
  • question_sid - the question symbolic ID.

Fields

Besides answers to a web form questions, it is essential to display and edit web form field values. The table below describes relation between the names of HTML fields and the field types.

Field type | Description | Field name | Value
text | Text. | form_textarea_ADDITIONAL_field_id | Typed text.
integer | Number. | form_text_ADDITIONAL_field_id | Typed text.
date | Date. | form_date_ADDITIONAL_field_id | Typed text.
Legend
  • field_id - the web form field ID.

See Also

  • CFormResult::GetDataByIDForHTML


Status handlers

In this topic

  • Introduction
  • File handlers
  • Available variables

Introduction

A result must have a definite status assigned to it. When creating a result, it must be assigned a default status that has an option "Assign this status to all new documents" set (only one status can have this option set). During its lifetime, the status of a result may change.

To intercept and process such changes of status, the Web Form module enables a developer to provide the status handler file. A handler can call any system function to perform the desired action; for example:

  • create mail events to send e-mail messages;
  • move a user who changed the status to a different user group (e.g. to grant access to other sections of the site);
  • other actions.

File handlers

File handlers are PHP scripts included when a status changes. They can be located in any directory from the site root; for example in /bitrix/php_interface/include/form/handlers/.

To specify a file handler, go to the Status parameters page. This page has the following two fields that are required to install file handlers:

  • File handler to be called when changing this status to another... - this parameter can be set to the file handler path relative to the root. This handler will be called when a result status is changed to some other one. It will also be included when a result in this status is deleted.
  • File handler to be called when changing a status to this... - this handler will be called when a result status is changed to this one. It will also be included when a new result is created.

Available variables

The handler specified in the field "File handler to be called when changing this status to another..." can use the following variables.

Variable | Description
$CURRENT_STATUS_ID | The ID of the current status (before it is changed).
$NEW_STATUS_ID | The ID of the new status.
$RESULT_ID | The ID of the result that is changing its status.
$arResult | Array describing the result fields.
$ACTION The symbolic code of the action which is to be performed:
  • UPDATE - the result is modified;
  • SET_STATUS - the result status has been changed directly (e.g. using the status list);
  • DELETE - the result is deleted.

The handler specified in the field "File handler to be called when changing a status to this..." can use the following variables.

Variable | Description
$CURRENT_STATUS_ID | The ID of the current status.
$PREV_STATUS_ID | The ID of the previous status.
$RESULT_ID | The ID of the result that is changing its status.
$arResult | Array describing the result fields.
$ACTION The symbolic code of the action which is to be performed:
  • UPDATE - the result is modified;
  • SET_STATUS - the result status has been changed directly (e.g. using the status list);
  • ADD - the result has just been created.


The Web Form module permissions

In this topic

  • Module permissions
  • Web form permissions
  • Result (status) permissions

Module permissions

Permissions to access the Web Forms module are assigned to a user group. Permissions restrict access to the administrative section of the module. The following permissions are provided (in the access level ascending order):

  • [D] access denied - any access to the administrative section of the module is closed;
  • [R] read access - access is granted;
  • [W] full access - full access to the administrative section of the module and all web forms.
Each user can have only one of the listed access level.

Web form permissions

Web form permissions restrict access to a specific web from and its results. The following permissions are provided (in the access level ascending order):

Different access permissions can be applied to a web form:

  • 1 - access denied (form and its results are totally inaccessible);
  • 10 - form fill (visitor can only fill in and save the form);
  • 15 - edit own result (visitor can view, filter and sort a list of results; view, edit or delete a result);
  • 20 - view all results (visitor can view all active results);
  • 25 - edit all results and view form settings (visitor can view and edit all results depending on their status; if he can access the administrative section, he can view the form settings);
  • 30 - full access (includes all the above rights plus editing the form settings).
A single user can be granted only one permission.

Result (status) permissions

A result can be assigned a specific status. A status defines the permissions to access a result. Thus, permissions are specified in the status settings; the following permissions apply:

  • VIEW - view results in this status;
  • MOVE - move results to this status;
  • EDIT - edit results in this status;
  • DELETE - delete results in this status.
A single user can have one or more permission.


Terms

Hierarchical diagram of the module entities

Module entities

  • Web forms
  • Field
  • Question
  • Answer
  • Result
  • Status
  • Validator
Term | Description
Web form Synonyms (implementations) of this notion are, for example, "survey" and "questionnaire". A web form is an aggregate of:
  • list of questions;
  • list of answers to questions;
  • list of additional fields of a web form;
  • list of possible statuses for a web form results.

A web form can be displayed, filled and saved as the result.

Different access permissions can be applied to a web form:

  • 1 - access denied (form and its results are totally inaccessible);
  • 10 - form fill (visitor can only fill in and save the form);
  • 15 - edit own result (visitor can view, filter and sort a list of results; view, edit or delete a result);
  • 20 - view all results (visitor can view all active results);
  • 25 - edit all results and view form settings (visitor can view and edit all results depending on their status; if he can access the administrative section, he can view the form settings);
  • 30 - full access (includes all the above rights plus editing the form settings).
A single user can be granted only one permission.

A web form can be assigned mail templates that are used to create mail events upon filling and saving a form.
Field | When filling in the form, a user views only questions and answers. When a user clicks Save, the answer values are saved as the result. Very often there is a need to calculate and store some value on the basis of the user supplied answers. To store these values, developers can use the web form fields.
Question A question is an aggregate of:
  • question text;
  • question text type [text|html];
  • question image;
  • list of answers;
  • settings used to display a question in the list of results;
  • settings used to display fields used to filter results by the question answer values.
Answer A web form question implies a set of HTML fields intended to receive the user answer to a question. Each HTML field is an answer. Hence, an answer (in terms of this module) is an aggregate of the following notions:
  • the ANSWER_TEXT parameter (displayed beside the field as a legend);
  • the ANSWER_VALUE parameter (used internally, for example, to calculate the web form values);
  • type, can have the following values:
    • text - single line text;
    • textarea - multiple line text;
    • radio - radio button;
    • checkbox - check button;
    • dropdown - drop-down list;
    • multiselect - multiple selection list;
    • date - date input field;
    • image - image upload field;
    • file - file upload field;
    • password - password input field.
  • width;
  • height;
  • additional parameters.
Result After a user fills in a form and clicks Save, all the answer values are stored in the database as the result. If a handler requires some fields, the calculated field values can also be stored as the result. Each result must have a status regulating the result access permission. A result is an aggregate of:
  • values of answers to a web form questions;
  • web form field values;
  • status value.
Status The major task of status is to delimit the access permission to the web form result for each user group.

The status access permission can be the following:
  • VIEW - view results in this status;
  • MOVE - move results to this status;
  • EDIT - edit results in this status;
  • DELETE - delete results in this status.
A single user can have one or more permission.

Hence, each result must have a status assigned to it. When creating a result, it must be assigned a default status that has an option "Assign this status to all new documents" set.
Validator Validator is a set of functions that are used to verify that the values of the form fields satisfy additional criteria.

A set of types of questions to which the validator is applicable is assigned to each validator. Validators cannot be used with questions that can have answers of different types.

You can create custom validators for any field types. For more details, see Creating Validators.


Classes

The following classes are used with the Web Forms module.

Classes

Class | Description
CForm | Class used to handle web forms.
CFormAnswer | Used to handle answers.
CFormField | Class used with questions and fields.
CFormStatus | This class handles statuses.
CFormResult | This class facilitates handling the web form results.


CForm

The CForm class is used to handle web forms.

Methods

Method | Description
Check | Checks the form required fields, date and time format and the file type for validity.
Mail | This method is used to send the result via the e-mail using the mail template.
SetEvent | Registers a new event in the Statistics module.
GetByID | Returns the selection from the database containing the form parameters.
GetBySID | Returns the selection from the database containing the form parameters.
GetDataByID | Returns arrays describing the form.
GetFieldList | Used to retrieve a list of the form questions and/or fields.
GetPermission | Returns the form access permission.
GetResultAnswerArray | Returns arrays containing information on the form questions, fields and answers.
GetStatusList | Returns a list of the forms states.
ShowResult | Emits the HTML code displaying the result using either display or print template.
EditResult | Displays the HTML code of a result editing page using the template "Result editing".
GetClosedFields | Returns the HTML code consisting of the fields with ID's equal to ID's of questions and fields passed as the second parameter. The fields have the hidden attribute set.


Check

CForm::Check

varchar
CForm::Check(
 int WEB_FORM_ID,
 array arrVALUES=false,
 int RESULT_ID=0
);

The method checks the form required fields, date and time format and the file type for validity.

Parameters

Parameter | Description
WEB_FORM_ID | Form ID.
arVALUES | Array of input values. In this parameter is false or not specified, it is taken from the array stored in $HTTP_POST_VARS. If $HTTP_POST_VARS is empty, it is taken from the array $HTTP_GET_VARS.
RESULT_ID | If the method is called for the result editing, specify the result ID here.

Return Value

The function returns a string containing the error description. If no error occurs, the string returned is empty.

Example

The following is an example of array $HTTP_POST_VARS passed to arrVALUES.

Array
(
    [form_text_586] => John Smith
    [form_date_587] => 10.03.1992
    [form_textarea_588] => London
    [form_radio_VS_MARRIED] => 589
    [form_checkbox_VS_INTEREST] => Array
        (
            [0] => 592
            [1] => 593
            [2] => 594
        )

    [form_dropdown_VS_AGE] => 597
    [form_multiselect_VS_EDUCATION] => Array
        (
            [0] => 603
            [1] => 604
        )

    [form_text_606] => 2345
    [form_image_607] => 1045
)

The below example shows the sample file "form_edit.php" allowing to edit the result.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
include(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/admin/lang/",
                        "/form_result_edit.php"));
$RESULT_ID = intval($RESULT_ID);
$z = CFormResult::GetByID($RESULT_ID);
if (!($arrResult=$z->Fetch()))
{
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
    echo ShowError("Survey form not found");
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
    die();
}
$WEB_FORM_ID = intval($arrResult["FORM_ID"]);
$F_RIGHT = intval(CForm::GetPermission($WEB_FORM_ID));

/*
Y - allow to edit the form fields
N - do not allow to edit the form fields
*/
$EDIT_ADDITIONAL = "N";

if ($F_RIGHT>=25 || ($F_RIGHT>=15 && $USER->GetID()==$arrResult["USER_ID"])) :

    // "Save results" clicked
    if ($REQUEST_METHOD=="POST" &&
             intval($WEB_FORM_ID)>0 &&
             (strlen($web_form_submit)>0 || strlen($apply)>0))
    {
        // obtain the form data array
        $arrVALUES = $HTTP_POST_VARS;
        $error = CForm::Check($WEB_FORM_ID, $arrVALUES, $RESULT_ID);
        if (strlen($error)<=0)
        {
            CFormResult::Update($RESULT_ID, $arrVALUES, $EDIT_ADDITIONAL);
            $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
            $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
            CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
            if (strlen($web_form_submit)>0)
                LocalRedirect("index.php?WEB_FORM_NAME=".$arrResult["VARNAME"]);
        }
        else $strError .= $error;
    }
    else
    // obtain the data array from the database
        $arrVALUES = CFormResult::GetDataByIDForWeb($RESULT_ID,$EDIT_ADDITIONAL);
endif;

$title = str_replace("#RESULT_ID#","$RESULT_ID","Editing form # #RESULT_ID#");
$APPLICATION->SetTitle($title);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
<a href="index.php?WEB_FORM_NAME=<?=$arrResult["VARNAME"]?>" class="navchain">Forms</a>
<br><br>
<table cellspacing="0" cellpadding="2">
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b>ID:</b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["ID"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_FORM_NAME")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?
        echo "[<a class='tablebodylink' href='form_edit.php?lang=".LANG."&ID=".$WEB_FORM_ID."'>". $WEB_FORM_ID."</a>] (".$arrResult["VARNAME"].") ".$arrResult["NAME"];
        ?></font></td>
    </tr>
    <?endif;?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_DATE_CREATE")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["DATE_CREATE"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_TIMESTAMP")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["TIMESTAMP_X"]?></font></td>
    </tr>
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_USER")?></b></font></td>
        <td valign="top" nowrap><font class="tablebodytext"><?
            if (intval($arrResult["USER_ID"])>0) :
                echo "<font class='tablebodytext'>[</font><a class='tablebodylink' title='".GetMessage("FORM_EDIT_USER")."' href='user_edit.php?lang=".LANG."&ID=".$arrResult["USER_ID"]."'>".$arrResult["USER_ID"]."</a><font class='tablebodytext'>] (".htmlspecialchars($arrResult["LOGIN"]).") ".htmlspecialchars($arrResult["USER_NAME"])."</font>";
                echo ($arrResult["USER_AUTH"]=="N") ? " <font class='filteroff'>".GetMessage("FORM_NOT_AUTH")."</font>" : "";
            else :
                echo "<font class='tablebodytext'>".GetMessage("FORM_NOT_REGISTERED")."</font>";
            endif;
            ?></font></td>
    </tr>
    <?if (CModule::IncludeModule("statistic")):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_GUEST")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_GUEST_ALT")?>" class="tablebodylink" href="/bitrix/admin/guest_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_GUEST_ID"]?>&set_filter=Y"><?=$arrResult["STAT_GUEST_ID"]?></a>]</font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_SESSION")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_SESSION_ALT")?>" class="tablebodylink" href="/bitrix/admin/session_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_SESSION_ID"]?>&set_filter=Y"><?=$arrResult["STAT_SESSION_ID"]?></a>]</font></td>
    </tr>
    <?endif;?>
    <?endif;?>
</table>
<br>
<?
CForm::EditResult($RESULT_ID, $arrVALUES, $EDIT_RESULT_TEMPLATE, $EDIT_ADDITIONAL);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


EditResult

CForm::EditResult

CForm::EditResult(
 int RESULT_ID,
 array arrVALUES,
 varchar TEMPLATE="",
 char(1) EDIT_ADDITIONAL="N",
 char(1) EDIT_STATUS="N"
);

The method displays the HTML code of a result editing page using the template "Result editing".

Parameters

Parameter | Description
RESULT_ID | Result ID.
arVALUES | Array of the field values for the result editing form. This can be the result of a call to CFormResult::GetDataByIDForWeb, or can be set to array stored in $HTTP_POST_VARS.
TEMPLATE | Name of the result editing template file. If omitted, the default template file of this is used.
EDIT_ADDITIONAL | If set to "Y", all form fields are available for editing. If set to "N" (default), only the form questions are displayed and can be edited.
EDIT_STATUS | If set to "Y", a result status can be changed in templates like "default.php".

Example

The following is an example of the arVALUES parameter:

Array
(
    [form_text_586] => James Brown
    [form_date_587] => 10.03.1992
    [form_textarea_588] => LA
    [form_radio_VS_MARRIED] => 589
    [form_checkbox_VS_INTEREST] => Array
        (
            [0] => 592
            [1] => 593
            [2] => 594
        )

    [form_dropdown_VS_AGE] => 597
    [form_multiselect_VS_EDUCATION] => Array
        (
            [0] => 603
            [1] => 604
        )

    [form_text_606] => 2345
    [form_image_607] => 1045
)

The below example shows the sample file "form_edit.php" allowing to edit the result.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
include(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/admin/lang/",
                        "/form_result_edit.php"));
$RESULT_ID = intval($RESULT_ID);
$z = CFormResult::GetByID($RESULT_ID);
if (!($arrResult=$z->Fetch()))
{
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
    echo ShowError("Survey form not found");
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
    die();
}
$WEB_FORM_ID = intval($arrResult["FORM_ID"]);
$F_RIGHT = intval(CForm::GetPermission($WEB_FORM_ID));

/*
Y - allow to edit the form fields
N - do not allow to edit the form fields
*/
$EDIT_ADDITIONAL = "N";

if ($F_RIGHT>=25 || ($F_RIGHT>=15 && $USER->GetID()==$arrResult["USER_ID"])) :

    // "Save results" clicked
    if ($REQUEST_METHOD=="POST" &&
             intval($WEB_FORM_ID)>0 &&
             (strlen($web_form_submit)>0 || strlen($apply)>0))
    {
        // obtain the form data array
        $arrVALUES = $HTTP_POST_VARS;
        $error = CForm::Check($WEB_FORM_ID, $arrVALUES, $RESULT_ID);
        if (strlen($error)<=0)
        {
            CFormResult::Update($RESULT_ID, $arrVALUES, $EDIT_ADDITIONAL);
            $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
            $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
            CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
            if (strlen($web_form_submit)>0)
                LocalRedirect("index.php?WEB_FORM_NAME=".$arrResult["VARNAME"]);
        }
        else $strError .= $error;
    }
    else
    // obtain the data array from the database
        $arrVALUES = CFormResult::GetDataByIDForWeb($RESULT_ID,$EDIT_ADDITIONAL);
endif;

$title = str_replace("#RESULT_ID#","$RESULT_ID","Editing form # #RESULT_ID#");
$APPLICATION->SetTitle($title);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
<a href="index.php?WEB_FORM_NAME=<?=$arrResult["VARNAME"]?>" class="navchain">Forms</a>
<br><br>
<table cellspacing="0" cellpadding="2">
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b>ID:</b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["ID"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_FORM_NAME")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?
        echo "[<a class='tablebodylink' href='form_edit.php?lang=".LANG."&ID=".$WEB_FORM_ID."'>". $WEB_FORM_ID."</a>] (".$arrResult["VARNAME"].") ".$arrResult["NAME"];
        ?></font></td>
    </tr>
    <?endif;?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_DATE_CREATE")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["DATE_CREATE"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_TIMESTAMP")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["TIMESTAMP_X"]?></font></td>
    </tr>
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_USER")?></b></font></td>
        <td valign="top" nowrap><font class="tablebodytext"><?
            if (intval($arrResult["USER_ID"])>0) :
                echo "<font class='tablebodytext'>[</font><a class='tablebodylink' title='".GetMessage("FORM_EDIT_USER")."' href='user_edit.php?lang=".LANG."&ID=".$arrResult["USER_ID"]."'>".$arrResult["USER_ID"]."</a><font class='tablebodytext'>] (".htmlspecialchars($arrResult["LOGIN"]).") ".htmlspecialchars($arrResult["USER_NAME"])."</font>";
                echo ($arrResult["USER_AUTH"]=="N") ? " <font class='filteroff'>".GetMessage("FORM_NOT_AUTH")."</font>" : "";
            else :
                echo "<font class='tablebodytext'>".GetMessage("FORM_NOT_REGISTERED")."</font>";
            endif;
            ?></font></td>
    </tr>
    <?if (CModule::IncludeModule("statistic")):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_GUEST")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_GUEST_ALT")?>" class="tablebodylink" href="/bitrix/admin/guest_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_GUEST_ID"]?>&set_filter=Y"><?=$arrResult["STAT_GUEST_ID"]?></a>]</font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_SESSION")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_SESSION_ALT")?>" class="tablebodylink" href="/bitrix/admin/session_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_SESSION_ID"]?>&set_filter=Y"><?=$arrResult["STAT_SESSION_ID"]?></a>]</font></td>
    </tr>
    <?endif;?>
    <?endif;?>
</table>
<br>
<?
CForm::EditResult($RESULT_ID, $arrVALUES, $EDIT_RESULT_TEMPLATE, $EDIT_ADDITIONAL);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetByID

CForm::GetByID

record set
CForm::GetByID(
 int ID
);

The function returns the selection from the database containing the form parameters.

Parameters

Parameter | Description
ID | Form ID for which the parameters are to be returned.

Return Values

Returns a database record containing the form parameters. See Example for details on handling the result.

Example

The following is an example of one row of the selection returned by CForm::GetByID.

Array
(
    [ID] => 1 (ID)
    [TIMESTAMP_X] => 22.09.2003 16:52:48 (modification date)
    [NAME] => College application form
    [VARNAME] => COLLEGE (identifier)
    [BUTTON] => Save (button title for the template default.php)
    [C_SORT] => 100 (sort weight)
    [LID] => en (site)
    [IMAGE_ID] => (ID of the image)
    [DESCRIPTION] => (description)
    [DESCRIPTION_TYPE] => html (type of description)
    [SHOW_TEMPLATE] => osago.php (form display template)
    [MAIL_EVENT_TYPE] => FORM_FILLING_COLL (mail event type)
    [MAIL_TEMPLATE] => 270 (ID of the mail template)
    [SHOW_RESULT_TEMPLATE] => default.php (result display template)
    [PRINT_RESULT_TEMPLATE] => cprint.php (result print template)
    [EDIT_RESULT_TEMPLATE] => default.php (result editing temlate)
    [FILTER_RESULT_TEMPLATE] => name of the file containing
                                the code used for filter display
    [TABLE_RESULT_TEMPLATE] => name of the file containing
                               the code used to display results
    [STAT_EVENT1] => (event type identifier - event1)
    [STAT_EVENT2] => (event type identifier - event2)
    [STAT_EVENT3] => (auxiliary event type identifier - event3)
    [C_FIELDS] => 2 (number of form fields)
    [QUESTIONS] => 59 (number of questions in the form)
)

The below example shows the sample file "form_fill.php" displaying the form.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("form"))
{
    if (intval($WEB_FORM_ID)>0)
        $z = <b>CForm::GetByID</b>($WEB_FORM_ID);
    else
        $z = CForm::GetBySID($WEB_FORM_NAME);

    if (!($zr=$z->Fetch()))
    {
        $FORM_EXIST = "N";
        $strError .= "Invalid form ID.<br>";
    }
    else
    {
        $FORM_EXIST = "Y";
        $WEB_FORM_ID = $zr["ID"];
        $WEB_FORM_NAME = $zr["VARNAME"];
        if ($REQUEST_METHOD=="POST" &&
            intval($WEB_FORM_ID)>0 &&
            strlen($web_form_submit)>0)
        {
            $arrVALUES = $HTTP_POST_VARS;
            $error = CForm::Check($WEB_FORM_ID);
            if (strlen($error)<=0)
            {
                if ($RESULT_ID = CFormResult::Add($WEB_FORM_ID))
                {
                    $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
                    $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
                    CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
                    CForm::SetEvent($RESULT_ID);
                    CForm::Mail($RESULT_ID);
                    LocalRedirect("index.php?WEB_FORM_NAME=".$WEB_FORM_NAME. "&strNote=".urlencode("Information saved"));
                }
            }
            else
                $strError .= $error;
        }
    }
}

if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle("Visitor survey");

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
echo ShowNote($strNote);
echo ShowError($strError);
?><?
if (CModule::IncludeModule("form"))
    CForm::Show($WEB_FORM_NAME, $arrVALUES);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetBySID

CForm::GetBySID

record set
CForm::GetBySID(
 varchar(255) SID
);

The function returns the selection from the database containing the form parameters.

Parameters

Parameter | Description
SID | Symbolic ID of a form.

Return Values

Returns a database record containing the form parameters. See Example for details on handling the result.

Example

The following is an example of one row of the selection returned by CForm::GetBySID.

Array
(
    [ID] => 1 (ID)
    [TIMESTAMP_X] => 22.09.2003 16:52:48 (modification date)
    [NAME] => College application form
    [VARNAME] => COLLEGE (identifier)
    [BUTTON] => Save (button title for the template default.php)
    [C_SORT] => 100 (sort weight)
    [LID] => en (site)
    [IMAGE_ID] => (ID of the image)
    [DESCRIPTION] => (description)
    [DESCRIPTION_TYPE] => html (type of description)
    [SHOW_TEMPLATE] => osago.php (form display template)
    [MAIL_EVENT_TYPE] => FORM_FILLING_COLL (mail event type)
    [MAIL_TEMPLATE] => 270 (ID of the mail template)
    [SHOW_RESULT_TEMPLATE] => default.php (result display template)
    [PRINT_RESULT_TEMPLATE] => cprint.php (result print template)
    [EDIT_RESULT_TEMPLATE] => default.php (result editing temlate)
    [FILTER_RESULT_TEMPLATE] => name of the file containing
                                the code used for filter display
    [TABLE_RESULT_TEMPLATE] => name of the file containing
                               the code used to display results
    [STAT_EVENT1] => (event type identifier - event1)
    [STAT_EVENT2] => (event type identifier - event2)
    [STAT_EVENT3] => (auxiliary event type identifier - event3)
    [C_FIELDS] => 2 (number of form fields)
    [QUESTIONS] => 59 (number of questions in the form)
)

The below example shows the sample file "form_fill.php" displaying the form.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("form"))
{
    if (intval($WEB_FORM_ID)>0)
        $z = <b>CForm::GetByID</b>($WEB_FORM_ID);
    else
        $z = CForm::GetBySID($WEB_FORM_NAME);

    if (!($zr=$z->Fetch()))
    {
        $FORM_EXIST = "N";
        $strError .= "Invalid form ID.<br>";
    }
    else
    {
        $FORM_EXIST = "Y";
        $WEB_FORM_ID = $zr["ID"];
        $WEB_FORM_NAME = $zr["VARNAME"];
        if ($REQUEST_METHOD=="POST" &&
            intval($WEB_FORM_ID)>0 &&
            strlen($web_form_submit)>0)
        {
            $arrVALUES = $HTTP_POST_VARS;
            $error = CForm::Check($WEB_FORM_ID);
            if (strlen($error)<=0)
            {
                if ($RESULT_ID = CFormResult::Add($WEB_FORM_ID))
                {
                    $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
                    $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
                    CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
                    CForm::SetEvent($RESULT_ID);
                    CForm::Mail($RESULT_ID);
                    LocalRedirect("index.php?WEB_FORM_NAME=".$WEB_FORM_NAME. "&strNote=".urlencode("information saved"));
                }
            }
            else
                $strError .= $error;
        }
    }
}

if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle("Visitor survey");

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
echo ShowNote($strNote);
echo ShowError($strError);
?><?
if (CModule::IncludeModule("form"))
    CForm::Show($WEB_FORM_NAME, $arrVALUES);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetClosedFields

CForm::GetClosedFields

text
CForm::GetClosedFields(
 int FORM_ID,
 array arFields
);

The method returns the HTML code consisting of the fields with ID's equal to ID's of questions and fields passed as the second parameter. The fields have the hidden attribute set.

The method is used in result editing templates to limit the set of questions and fields to those passed to this method. If a result editing template provides only a subset of all form fields, values of the absent fields will be deleted from the database upon save. This method allow to prevent this side-effect.

Parameters

Parameter | Description
FORM_ID | Form ID.
arFields | Array of the symbolic ID's of the emitted fields.

Example

The following code is used in the real result editing template.

<form name="<?=$arForm["VARNAME"]?>"
      action="<?=$APPLICATION->GetCurPage()?>?
              lang=<?=LANG?>&WEB_FORM_ID=<?echo $WEB_FORM_ID?>&
              RESULT_ID=<?echo $RESULT_ID?>"
      method="POST" enctype="multipart/form-data">
<input type="hidden" name="WEB_FORM_ID" value="<?=intval($WEB_FORM_ID)?>">
<input type="hidden" name="lang" value="<?=LANG?>">
<input type="hidden" name="VIEW_TEMPLATE" value="<?=htmlspecialchars($VIEW_TEMPLATE)?>">
<?
// emit the hidden fields of questions which are not to be edited
echo CForm::GetClosedFields($WEB_FORM_ID,
    array(
        "CL_POLICY_SERIES",
        "CL_POLICY_NUMBER",
        "CL_SYMBOL_SERIES",
        "CL_SYMBOL_NUMBER",
        "CL_TICKET_SERIES",
        "CL_TICKET_NUMBER",
        "CL_AGENT_TECH",
        "CL_AGENT_GENERAL",
        "CL_CENTER",
        "CL_COMMENTS"));
?>


GetDataByID

CForm::GetDataByID

CForm::GetDataByID(
 int FORM_ID,
 array &arForm,
 array &arQuestions,
 array &arAnswers,
 array &arDropDown,
 array &arMultiSelect,
 char(1) additional="Y"
);

The function returns arrays describing the form.

Parameters

FORM_ID | Form ID.
arForm Array containing the form parameters with keys:
  • ID - Form ID
  • TIMESTAMP_X - modification date
  • NAME - form name
  • VARNAME - form identifier
  • BUTTON - button title for use with default.php
  • C_SORT - sort order
  • LID - ID of the site in which the form is used
  • IMAGE_ID - ID of the image in description
  • DESCRIPTION - form description
  • DESCRIPTION_TYPE - form description type (text|html)
  • SHOW_TEMPLATE - default template for the form display
  • MAIL_EVENT_TYPE - mail event type
  • MAIL_TEMPLATE - ID of the mail template
  • SHOW_RESULT_TEMPLATE - result display template
  • PRINT_RESULT_TEMPLATE - result print template
  • EDIT_RESULT_TEMPLATE - result editing template
  • STAT_EVENT1 - identifier event1 for the Statistics module.
  • STAT_EVENT2 - identifier event2 for the Statistics module.
  • STAT_EVENT3 - auxiliary identifier event3 for the Statistics module.
  • C_FIELDS - number of fields
  • QUESTIONS - number of questions
Sample
Array
(
    [ID] => 4
    [TIMESTAMP_X] => 17.09.2003 12:43:46
    [NAME] => Visitor review
    [VARNAME] => ANKETA
    [BUTTON] => Save
    [C_SORT] => 300
    [LID] => ru
    [IMAGE_ID] => 717
    [DESCRIPTION] => Used to collect info on visitors.
    [DESCRIPTION_TYPE] => text
    [SHOW_TEMPLATE] => default.php
    [MAIL_EVENT_TYPE] => FORM_FILLING_ANKETA
    [MAIL_TEMPLATE] => 262
    [SHOW_RESULT_TEMPLATE] => default.php
    [PRINT_RESULT_TEMPLATE] => default.php
    [EDIT_RESULT_TEMPLATE] => default.php
    [STAT_EVENT1] => form
    [STAT_EVENT2] => anketa
    [STAT_EVENT3] =>
    [C_FIELDS] => 1
    [QUESTIONS] => 9
)
arQuestions Array with questions and fields of the form. Each key in the array is a question or field identifier. Each value is an array describing a single question or field. Such array have the following keys.
  • ID - ID of a question or field
  • FORM_ID - form ID
  • TIMESTAMP_X - modification date of a question or field
  • ACTIVE - active state flag [Y|N]
  • TITLE - text of a question or a field title
  • TITLE_TYPE - type of text
  • VARNAME - identifier of a question or field
  • C_SORT - sort weight
  • ADDITIONAL - Y for questions, N for fields
  • REQUIRED - flag indicating the field is required [Y|N]
  • IN_FILTER - flag indicating the field or question is listed in the filter of the results form [Y|N]
  • IN_RESULTS_TABLE - flag indicating the field or question is listed in the table of results [Y|N]
  • FIELD_TYPE - field type
  • IMAGE_ID - ID of the image in the question description
  • COMMENTS - auxiliary comment
Sample
Array
(
    [VS_NAME] => Array
        (
            [ID] => 140
            [FORM_ID] => 4
            [TIMESTAMP_X] => 28.08.2003 11:45:57
            [ACTIVE] => Y
            [TITLE] => First and last name
            [TITLE_TYPE] => html
            [VARNAME] => VS_NAME
            [C_SORT] => 100
            [ADDITIONAL] => N
            [REQUIRED] => Y
            [IN_FILTER] => Y
            [IN_RESULTS_TABLE] => Y
            [FIELD_TYPE] =>
            [IMAGE_ID] =>
            [COMMENTS] =>
        )

    [VS_BIRTHDAY] => Array
        (
            [ID] => 141
            [FORM_ID] => 4
            [TIMESTAMP_X] => 16.09.2003 17:27:16
            [ACTIVE] => Y
            [TITLE] => Date of birth
            [TITLE_TYPE] => text
            [VARNAME] => VS_BIRTHDAY
            [C_SORT] => 200
            [ADDITIONAL] => N
            [REQUIRED] => Y
            [IN_FILTER] => Y
            [IN_RESULTS_TABLE] => Y
            [FIELD_TYPE] =>
            [IMAGE_ID] =>
            [COMMENTS] =>
        )
...
)
arAnswers Array with answers to questions of the form. Each key in the array is a question identifier. Each value is an array describing answers for a single question . Such array have the following keys.
  • ID - ID of the answer field
  • FIELD_ID - ID of the question
  • TIMESTAMP_X - modification date
  • MESSAGE - text [ANSWER_TEXT]
  • C_SORT - sort weight
  • ACTIVE - active state flag [Y|N]
  • VALUE - the value [ANSWER_VALUE]
  • FIELD_TYPE - type of the field
  • FIELD_WIDTH - field width
  • FIELD_HEIGHT - field height
  • FIELD_PARAM - additional user prameter
Sample
Array
(
    [VS_NAME] => Array
        (
            [0] => Array
                (
                    [ID] => 586
                    [FIELD_ID] => 140
                    [TIMESTAMP_X] => 2003-08-28 11:45:57
                    [MESSAGE] =>
                    [C_SORT] => 100
                    [ACTIVE] => Y
                    [VALUE] =>
                    [FIELD_TYPE] => text
                    [FIELD_WIDTH] => 50
                    [FIELD_HEIGHT] => 0
                    [FIELD_PARAM] =>
                )

        )

    [VS_MARRIED] => Array
        (
            [0] => Array
                (
                    [ID] => 589
                    [FIELD_ID] => 143
                    [TIMESTAMP_X] => 2003-08-28 14:51:29
                    [MESSAGE] => yes
                    [C_SORT] => 100
                    [ACTIVE] => Y
                    [VALUE] =>
                    [FIELD_TYPE] => radio
                    [FIELD_WIDTH] => 0
                    [FIELD_HEIGHT] => 0
                    [FIELD_PARAM] =>
                )

            [1] => Array
                (
                    [ID] => 590
                    [FIELD_ID] => 143
                    [TIMESTAMP_X] => 2003-08-28 14:51:29
                    [MESSAGE] => no
                    [C_SORT] => 200
                    [ACTIVE] => Y
                    [VALUE] =>
                    [FIELD_TYPE] => radio
                    [FIELD_WIDTH] => 0
                    [FIELD_HEIGHT] => 0
                    [FIELD_PARAM] =>
                )

        )
...
)
arDropDown Array containing the suggested answers for fields of the type dropdown.
Sample
Array
(
    [VS_AGE] => Array
        (
            [reference] => Array
                (
                    [0] => -
                    [1] => 10-19
                    [2] => 20-29
                    [3] => 30-39
                    [4] => 40-49
                    [5] => 50-59
                    [6] => over 60
                )

            [reference_id] => Array
                (
                    [0] => 608
                    [1] => 596
                    [2] => 597
                    [3] => 598
                    [4] => 599
                    [5] => 600
                    [6] => 601
                )

            [param] => Array
                (
                    [0] => NOT_ANSWER
                    [1] =>
                    [2] => SELECTED
                    [3] =>
                    [4] =>
                    [5] =>
                    [6] =>
                )

        )

)
arMultiSelect Array containing the suggested answers for fields of the type multiselect.
Ïðèìåð
Array
(
    [VS_EDUCATION] => Array
        (
            [reference] => Array
                (
                    [0] => school
                    [1] => college
                    [2] => post-graduate course
                )

            [reference_id] => Array
                (
                    [0] => 602
                    [1] => 603
                    [2] => 604
                )

            [param] => Array
                (
                    [0] =>
                    [1] => SELECTED
                    [2] =>
                )

        )

)
additional | If set to "Y", the method returns form fields as well as questions in the array arQuestions. If "N" (default), questions only are returned.

Example

<?

    /*
        Returns the HTML code of the form with respect to the user permissions
        WEB_FORM_VARNAME - form identifier
        VARS - array of values for the form fields
        SHOW_TEMPLATE - form template
        PREVIEW - set to "Y" to disable the button "Save"
    */

    function Show($WEB_FORM_VARNAME, $arrVALUES=false, $SHOW_TEMPLATE=false, $PREVIEW="N")
    {
        $err_mess = (CAllForm::err_mess())."<".br>Function: Show<".br>Line: ";
        global $DB, $MESS, $APPLICATION, $USER, $HTTP_POST_VARS, $HTTP_GET_VARS;
        $z = CForm::GetBySID($WEB_FORM_VARNAME);
        $zr = $z->Fetch();
        $WEB_FORM_ID = intval($zr["ID"]);
        $WEB_FORM_ID = CForm::GetDataByID($WEB_FORM_ID, $arForm,
                                          $arQuestions, $arAnswers,
                                          $arDropDown, $arMultiSelect);
        if (intval($WEB_FORM_ID)>0)
        {
            $F_RIGHT = CAllForm::GetPermission($WEB_FORM_ID);
            if (intval($F_RIGHT)>=10)
            {
                if ($SHOW_TEMPLATE!==false) $template = $SHOW_TEMPLATE;
                else
                {
                    if (strlen($arForm["SHOW_TEMPLATE"])<=0) $template = "default.php";
                    else $template = $arForm["SHOW_TEMPLATE"];
                }
                require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
                $path = COption::GetOptionString("form","SHOW_TEMPLATE_PATH");
                include (GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/lang/", "/include.php"));
                include(GetLangFileName($_SERVER["DOCUMENT_ROOT"].$path."lang/", "/".$template));
                include($_SERVER["DOCUMENT_ROOT"].$path.$template);
            }
        }
    }
?>


GetFieldList

CForm::GetFieldList

record set
CForm::GetFieldList(
 int FORM_ID,
 varchar additional,
 varchar &by,
 varchar &order,
 array arFilter=array(),
 boolean &is_filtered
);

The method is used to retrieve a list of the form questions and/or fields.

Parameters

Parameter | Description
FORM_ID | Form ID.
additional Denotes which information to return.
  • "" or "ALL" - return both questions and fields
  • "Y" - return fields;
  • "N" - return questions.
by Allows to specify the name of the field by which the sorting is to be performed. The following values allowed:
  • s_id - by the result ID
  • s_active - by the active state flag
  • s_varname - by the symbolic identifier
  • s_c_sort - by sort weight
  • s_title - by title
  • s_comments - by comments
  • s_required - by the required state of a question or field
  • s_in_results_table - by inclusion in the results table
order Sort order. The following values apply:
  • desc - descending (default)
  • asc - ascending
arFilter Array used as the values filter. The following key names apply:
  • ID - ID of a question or field (complex logics allowed)
  • TITLE - text of a question or field (complex logics allowed)
  • VARNAME - symbolic identifier (complex logics allowed)
  • COMMENTS - comment (complex logics allowed)
  • ACTIVE - active state flag: "Y" - active; "N" - inactive;
  • IN_RESULTS_TABLE - flag indicating the inclusion in the results table: "Y" - included; "N" - not included;
  • IN_FILTER - flag indicating the inclusion in the filter: "Y" - included; "N" - not included;
  • REQUIRED - flag indicating the field is required: "Y" - required; "N" - not not required;
is_filtered | Contains true on return if the results has been filtered, or false otherwise.

Return Values

Returns a database record containing the form parameters.

Example

$arFilter = Array(
    "ID"                => $find_id,
    "TITLE"             => $find_title,
    "VARNAME"           => $find_varname,
    "ACTIVE"            => $find_active,
    "IN_RESULTS_TABLE"  => $find_in_table,
    "IN_FILTER"         => $find_in_filter,
    "REQUIRED"          => $find_required,
    "COMMENTS"          => $find_comments
    );
$rsFields = CForm::GetFieldList($WEB_FORM_ID,
                                $additional,
                                $by,
                                $order,
                                $arFilter,
                                $is_filtered);


GetPermission

CForm::GetPermission

int
CForm::GetPermission(
 int FORM_ID,
 array arGroups=false,
 char(1) get_from_database=""
);

The function returns the form access permission.

Parameters

Parameter | Description
FORM_ID | Form ID.
arGroups | Array of the ID's of user groups for which access permission is to be checked. If not specified, information pertaining to the current user is returned.
get_from_database | Set this parameter to "Y" to return the access permission information from the database rather than the default value.

Return Value

A permission code is returned which can be one of the following.

  • 1 - deny - form and its results cannot be accessed
  • 10 - form fill - visitor is only allowed to fill and save a form
  • 15 - edit own results - visitor is allowed to view, sort, filter a list of his or her results; view, print, edit and delete his or her result. Visitor can also change the visibility state of the result.
  • 20 - view all results - visitor can view all active results
  • 25 - edit all results and view form settings - visitor can view and edit all results; view the form settings (this requires the access to the administrative section);
  • 30 - full access - includes the above permissions and allows to edit settings of the form.

Example

The example below shows the file "form_edit.php" used to edit the form result.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
include(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/admin/lang/", "/form_result_edit.php"));
$RESULT_ID = intval($RESULT_ID);
$z = CFormResult::GetByID($RESULT_ID);
if (!($arrResult=$z->Fetch()))
{
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
    echo ShowError("Survey not found");
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
    die();
}
$WEB_FORM_ID = intval($arrResult["FORM_ID"]);
$F_RIGHT = intval(CForm::GetPermission($WEB_FORM_ID));

/*
Y - edit form fields
N - disallow form fields editing
*/
$EDIT_ADDITIONAL = "N";

if ($F_RIGHT>=25 || ($F_RIGHT>=15 && $USER->GetID()==$arrResult["USER_ID"])) :

    // "Save" clicked
    if ($REQUEST_METHOD=="POST" &&
        intval($WEB_FORM_ID)>0 &&
        (strlen($web_form_submit)>0 || strlen($apply)>0))
    {
        $arrVALUES = $HTTP_POST_VARS; // get the form data array
        $error = CForm::Check($WEB_FORM_ID, $arrVALUES, $RESULT_ID);
        if (strlen($error)<=0)
        {
            CFormResult::Update($RESULT_ID, $arrVALUES, $EDIT_ADDITIONAL);
            $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
            $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
            CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
            if (strlen($web_form_submit)>0)
                LocalRedirect("index.php?WEB_FORM_NAME=".$arrResult["VARNAME"]);
        }
        else
            $strError .= $error;
    }
    else
        // get the array of values from the database
        $arrVALUES = CFormResult::GetDataByIDForWeb($RESULT_ID,$EDIT_ADDITIONAL);
endif;
$title = str_replace("#RESULT_ID#","$RESULT_ID","Edit form # #RESULT_ID#");
$APPLICATION->SetTitle($title);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
<a href="index.php?WEB_FORM_NAME=<?=$arrResult["VARNAME"]?>" class="navchain">Forms</a>
<br><br>
<table cellspacing="0" cellpadding="2">
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b>ID:</b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["ID"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_FORM_NAME")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?
        echo "[<a class='tablebodylink' href='form_edit.php?lang=".LANG."&ID=".$WEB_FORM_ID."'>". $WEB_FORM_ID."</a>] (".$arrResult["VARNAME"].") ".$arrResult["NAME"];
        ?></font></td>
    </tr>
    <?endif;?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_DATE_CREATE")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["DATE_CREATE"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_TIMESTAMP")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["TIMESTAMP_X"]?></font></td>
    </tr>
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_USER")?></b></font></td>
        <td valign="top" nowrap><font class="tablebodytext"><?
            if (intval($arrResult["USER_ID"])>0) :
                echo "<font class='tablebodytext'>[</font><a class='tablebodylink' title='".GetMessage("FORM_EDIT_USER")."' href='user_edit.php?lang=".LANG."&ID=".$arrResult["USER_ID"]."'>".$arrResult["USER_ID"]."</a><font class='tablebodytext'>] (".htmlspecialchars($arrResult["LOGIN"]).") ".htmlspecialchars($arrResult["USER_NAME"])."</font>";
                echo ($arrResult["USER_AUTH"]=="N") ? " <font class='filteroff'>".GetMessage("FORM_NOT_AUTH")."</font>" : "";
            else :
                echo "<font class='tablebodytext'>".GetMessage("FORM_NOT_REGISTERED")."</font>";
            endif;
            ?></font></td>
    </tr>
    <?if (CModule::IncludeModule("statistic")):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_GUEST")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_GUEST_ALT")?>" class="tablebodylink" href="/bitrix/admin/guest_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_GUEST_ID"]?>&set_filter=Y"><?=$arrResult["STAT_GUEST_ID"]?></a>]</font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_SESSION")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_SESSION_ALT")?>" class="tablebodylink" href="/bitrix/admin/session_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_SESSION_ID"]?>&set_filter=Y"><?=$arrResult["STAT_SESSION_ID"]?></a>]</font></td>
    </tr>
    <?endif;?>
    <?endif;?>
</table>
<br>
<?
CForm::EditResult($RESULT_ID, $arrVALUES, $EDIT_RESULT_TEMPLATE, $EDIT_ADDITIONAL);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetResultAnswerArray

CForm::GetResultAnswerArray

CForm::GetResultAnswerArray(
 int FORM_ID,
 array &arrColumns,
 array &arrAnswers,
 array &arrAnswersVarname=array(),
 array arFilter=array(),
);

The function returns arrays containing information on the form questions, fields and answers.

Parameters

Parameter | Description
FORM_ID | Form ID.
arrColumns | Array describing questions and fields of the form. This array contains only active questions and fields included in the results table. To get a full list of questions and fields, use the function CForm::GetFieldList.
arrAnswers | Array containing answers to the questions and values of the fields of the form.
arrAnswersVarname | Same as arrAnswers, but contains information in other form (see below).
arFilter Optional filter with the following possible keys:
  • RESULT_ID - result ID (complex logics allowed)

Remarks

Sample array arrColumns:

Array
(
    [1] => Array
        (
            [ID] => 1
            [FORM_ID] => 2
            [TIMESTAMP_X] => 07.10.2003 14:34:14
            [ACTIVE] => Y
            [TITLE] => (T) - calculated insurance premium
            [TITLE_TYPE] => text
            [VARNAME] => CL_SUMMA
            [C_SORT] => 50
            [ADDITIONAL] => Y
            [REQUIRED] => N
            [IN_FILTER] => Y
            [IN_RESULTS_TABLE] => Y
            [FIELD_TYPE] => integer
            [IMAGE_ID] =>
            [COMMENTS] =>
            [FILTER_TITLE] => Cost:
            [RESULTS_TABLE_TITLE] => Cost
        )

    [9] => Array
        (
            [ID] => 9
            [FORM_ID] => 2
            [TIMESTAMP_X] => 13.10.2003 14:08:25
            [ACTIVE] => Y
            [TITLE] => Preferred area of application
            [TITLE_TYPE] => text
            [VARNAME] => CL_CITY
            [C_SORT] => 200
            [ADDITIONAL] => N
            [REQUIRED] => Y
            [IN_FILTER] => Y
            [IN_RESULTS_TABLE] => Y
            [FIELD_TYPE] =>
            [IMAGE_ID] =>
            [COMMENTS] =>
            [FILTER_TITLE] => City:
            [RESULTS_TABLE_TITLE] => City
        )
    ...
)

Sample array arrAnswers:

Array
(
    [307] => Array
        (
            [1] => Array
                (
                    [0] => Array
                        (
                            [RESULT_ID] => 307
                            [FIELD_ID] => 1
                            [ANSWER_ID] =>
                            [ANSWER_TEXT] =>
                            [ANSWER_VALUE] =>
                            [USER_TEXT] => 8910
                            [USER_FILE_ID] =>
                            [USER_FILE_NAME] =>
                            [USER_DATE] =>
                            [VARNAME] => CL_SUMMA
                            [TITLE] => (T) - calculated insurance premium
                            [TITLE_TYPE] => text
                            [FILTER_TITLE] => cost:
                            [RESULTS_TABLE_TITLE] => cost
                            [MESSAGE] =>
                            [VALUE] =>
                            [FIELD_TYPE] =>
                            [FIELD_WIDTH] =>
                            [FIELD_HEIGHT] =>
                            [FIELD_PARAM] =>
                        )

                )

            [9] => Array
                (
                    [1] => Array
                        (
                            [RESULT_ID] => 307
                            [FIELD_ID] => 9
                            [ANSWER_ID] => 1
                            [ANSWER_TEXT] => London
                            [ANSWER_VALUE] => 2/1.2
                            [USER_TEXT] =>
                            [USER_FILE_ID] =>
                            [USER_FILE_NAME] =>
                            [USER_DATE] =>
                            [VARNAME] => CL_CITY
                            [TITLE] => Preferred area of application
                            [TITLE_TYPE] => text
                            [FILTER_TITLE] => City:
                            [RESULTS_TABLE_TITLE] => City
                            [MESSAGE] => London
                            [VALUE] => 2/1.2
                            [FIELD_TYPE] => dropdown
                            [FIELD_WIDTH] => 0
                            [FIELD_HEIGHT] => 0
                            [FIELD_PARAM] =>
                        )

                )
)

Sample array arrAnswersVarname:

Array
(
    [307] => Array
        (
            [CL_SUMMA] => Array
                (
                    [0] => Array
                        (
                            [RESULT_ID] => 307
                            [FIELD_ID] => 1
                            [ANSWER_ID] =>
                            [ANSWER_TEXT] =>
                            [ANSWER_VALUE] =>
                            [USER_TEXT] => 8910
                            [USER_FILE_ID] =>
                            [USER_FILE_NAME] =>
                            [USER_DATE] =>
                            [VARNAME] => CL_SUMMA
                            [TITLE] => (T) - calculated insurance premium
                            [TITLE_TYPE] => text
                            [FILTER_TITLE] => Cost:
                            [RESULTS_TABLE_TITLE] => Cost
                            [MESSAGE] =>
                            [VALUE] =>
                            [FIELD_TYPE] =>
                            [FIELD_WIDTH] =>
                            [FIELD_HEIGHT] =>
                            [FIELD_PARAM] =>
                        )

                )

            [CL_CITY] => Array
                (
                    [0] => Array
                        (
                            [RESULT_ID] => 307
                            [FIELD_ID] => 9
                            [ANSWER_ID] => 1
                            [ANSWER_TEXT] => London
                            [ANSWER_VALUE] => 2/1.2
                            [USER_TEXT] =>
                            [USER_FILE_ID] =>
                            [USER_FILE_NAME] =>
                            [USER_DATE] =>
                            [VARNAME] => CL_CITY
                            [TITLE] => Preferred area of application
                            [TITLE_TYPE] => text
                            [FILTER_TITLE] => City:
                            [RESULTS_TABLE_TITLE] => City
                            [MESSAGE] => London
                            [VALUE] => 2/1.2
                            [FIELD_TYPE] => dropdown
                            [FIELD_WIDTH] => 0
                            [FIELD_HEIGHT] => 0
                            [FIELD_PARAM] =>
                        )

                )
        )
)

Example

CForm::GetResultAnswerArray($WEB_FORM_ID, $arrColumns, $arrAnswers, $arrAnswersVarname, array("IN_RESULTS_TABLE" => "Y"));
print_r($arrAnswers);
$colspan = 4;
reset($arrColumns);
while (list($key, $arrCol) = each($arrColumns)) :

    if (!is_array($arrNOT_SHOW_TABLE) || !in_array($arrCol["VARNAME"],$arrNOT_SHOW_TABLE)):

    if (($arrCol["ADDITIONAL"]=="Y" && $SHOW_ADDITIONAL=="Y") || $arrCol["ADDITIONAL"]!="Y") :
        $colspan++;
        if (strlen($arrCol["RESULTS_TABLE_TITLE"])<=0)
        {
            $title = ($arrCol["TITLE_TYPE"]=="html") ? strip_tags($arrCol["TITLE"]) : htmlspecialchars($arrCol["TITLE"]);
            $title = TruncateText($title,100);
        }
        else $title = htmlspecialchars($arrCol["RESULTS_TABLE_TITLE"]);
        ?>
        <td valign="top" class="tablehead"><font class="tableheadtext"><?
        if ($F_RIGHT>=25) :
        ?>[<a title="<?=GetMessage("FORM_FIELD_PARAMS")?>" class="tablebodylink" href="/bitrix/admin/form_field_edit.php?lang=<?=LANG?>&ID=<?=$arrCol["ID"]?>&WEB_FORM_ID=<?=$WEB_FORM_ID?>&additional=<?=$arrCol["ADDITIONAL"]?>"><?=$arrCol["ID"]?></a>]<br><?
        endif;
        echo $title;
        ?></td><?
    endif;
    endif;
endwhile;


GetStatusList

CForm::GetStatusList

record set
CForm::GetStatusList(
 int FORM_ID,
 varchar &by,
 varchar &order,
 array arFilter=array(),
 boolean &is_filtered
);

The method returns a list of the forms states.

Parameters

Parameter | Description
FORM_ID | Form ID.
by Specifies the name of the field used to sort the output. The following values are possible:
  • s_id - by ID
  • s_timestamp - by the modification date
  • s_active - by the active state flag
  • s_c_sort - by sort weight
  • s_title - by title text
  • s_description - by description text
  • s_results - by number of results in this state
order Sort order. The following values apply:
  • desc - descending (default)
  • asc - ascending
arFilter Array used as the values filter. The following key names apply:
  • ID - status ID (complex logics allowed);
  • ACTIVE - active state of the status(Y/N);
  • TITLE - status title (complex logics allowed);
  • DESCRIPTION - status description (complex logics allowed);
  • RESULTS_1 - minimum number of results in this status;
  • RESULTS_2 - maximum number of results in this status.
is_filtered | Contains true on return if the results has been filtered, or false otherwise.

Return Values

Returns a database record containing the form parameters. See Example for details on handling the result.

Example

$rsStatus = CForm::GetStatusList($WEB_FORM_ID, $by, $order, array(), $is_filtered);
while ($arS = $rsStatus->Fetch())
     $arStatus[$arS["TITLE"]] = $arS["ID"];


Mail

CForm::Mail

CForm::Mail(
 int RESULT_ID,
 int TEMPLATE_ID=""
);

This method is used to send the result via the e-mail using the mail template .

Parameters

Parameter | Description
RESULT_ID | Result ID.
TEMPLATE_ID | Mail template ID. If omitted, the default template specified for this form is used.

Example

The below example shows the sample file "form_fill.php" displaying the form.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("form"))
{
    if (intval($WEB_FORM_ID)>0)
        $z = <b>CForm::GetByID</b>($WEB_FORM_ID);
    else
        $z = CForm::GetBySID($WEB_FORM_NAME);

    if (!($zr=$z->Fetch()))
    {
        $FORM_EXIST = "N";
        $strError .= "Invalid form ID.<br>";
    }
    else
    {
        $FORM_EXIST = "Y";
        $WEB_FORM_ID = $zr["ID"];
        $WEB_FORM_NAME = $zr["VARNAME"];
        if ($REQUEST_METHOD=="POST" &&
            intval($WEB_FORM_ID)>0 &&
            strlen($web_form_submit)>0)
        {
            $arrVALUES = $HTTP_POST_VARS;
            $error = CForm::Check($WEB_FORM_ID);
            if (strlen($error)<=0)
            {
                if ($RESULT_ID = CFormResult::Add($WEB_FORM_ID))
                {
                    $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
                    $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
                    CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
                    CForm::SetEvent($RESULT_ID);
                    CForm::Mail($RESULT_ID);
                    LocalRedirect("index.php?WEB_FORM_NAME=".$WEB_FORM_NAME. "&strNote=".urlencode("Information saved"));
                }
            }
            else
                $strError .= $error;
        }
    }
}

if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle("Visitor survey");

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
echo ShowNote($strNote);
echo ShowError($strError);
?><?
if (CModule::IncludeModule("form"))
    CForm::Show($WEB_FORM_NAME, $arrVALUES);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


SetEvent

CForm::SetEvent

CForm::SetEvent(
 int RESULT_ID,
 varchar(255) EVENT1=false,
 varchar(255) EVENT2=false,
 varchar(255) EVENT3=false
);

Registers a new event in the Statistics module.

Parameters

Parameter | Description
RESULT_ID | Result ID.
EVENT1 | Event type identifier event1. If this parameter is not specified, the default value assigned to the form is used. If the form has no default event1 identifier, the "form" value is used.
EVENT2 | Event type identifier event2. If this parameter is not specified, the default value assigned to the form is used. If the form has no default event2 identifier, the form identifier value is used.
EVENT3 | Event type identifier event3. If this parameter is not specified, the default value assigned to the form is used. If the form has no default event3 identifier, the link to the result view page is used.

Example

The below example shows the sample file "form_fill.php" displaying the form.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("form"))
{
    if (intval($WEB_FORM_ID)>0)
        $z = <b>CForm::GetByID</b>($WEB_FORM_ID);
    else
        $z = CForm::GetBySID($WEB_FORM_NAME);

    if (!($zr=$z->Fetch()))
    {
        $FORM_EXIST = "N";
        $strError .= "Invalid form ID.<br>";
    }
    else
    {
        $FORM_EXIST = "Y";
        $WEB_FORM_ID = $zr["ID"];
        $WEB_FORM_NAME = $zr["VARNAME"];
        if ($REQUEST_METHOD=="POST" &&
            intval($WEB_FORM_ID)>0 &&
            strlen($web_form_submit)>0)
        {
            $arrVALUES = $HTTP_POST_VARS;
            $error = CForm::Check($WEB_FORM_ID);
            if (strlen($error)<=0)
            {
                if ($RESULT_ID = CFormResult::Add($WEB_FORM_ID))
                {
                    $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
                    $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
                    CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
                    CForm::SetEvent($RESULT_ID);
                    CForm::Mail($RESULT_ID);
                    LocalRedirect("index.php?WEB_FORM_NAME=".$WEB_FORM_NAME. "&strNote=".urlencode("information saved"));
                }
            }
            else
                $strError .= $error;
        }
    }
}

if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle("Visitor survey");

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
echo ShowNote($strNote);
echo ShowError($strError);
?><?
if (CModule::IncludeModule("form"))
    CForm::Show($WEB_FORM_NAME, $arrVALUES);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


ShowResult

CForm::ShowResult

CForm::ShowResult(
 int RESULT_ID,
 varchar(255) TEMPLATE="",
 varchar TEMPLATE_TYPE="show",
 char(1) SHOW_ADDITIONAL="N",
 char(1) SHOW_ANSWER_VALUE="Y",
 char(1) SHOW_STATUS="N"
);

The method emits the HTML code displaying the result using either display or print template.

Parameters

Parameter | Description
RESULT_ID | Result ID.
TEMPLATE | Name of the template file.
TEMPLATE_TYPE | Template type: "show" - result view template, "print" - result print template.
SHOW_ADDITIONAL | If set to "Y", values of the form fields are included in output. Otherwise, only answers to the form questions are displayed.
SHOW_ANSWER_VALUE | If set to "Y", templates like default.php will display values ANSWER_VALUE øò round brackets.
SHOW_STATUS | If set to "Y", templates like default.php will include result status in the results table.

Example

The below example shows the sample file "form_view.php" used to display the result.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
include(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/admin/lang/", "/form_result_view.php"));
$APPLICATION->SetTitle(str_replace("#RESULT_ID#","$RESULT_ID","View form # #RESULT_ID#"));
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
<?
$z = CFormResult::GetByID($RESULT_ID);
if ($arrResult = $z->Fetch()) :

    ?><a href="index.php?WEB_FORM_NAME=<?=$zr["VARNAME"]?>" class="navchain">Forms
<?
    echo ShowError($strError);
    echo ShowNote($strNote);

    $F_RIGHT = CAllForm::GetPermission($arrResult["FORM_ID"]);

?>
<br>
<table cellspacing="0" cellpadding="2">
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b>ID:</b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["ID"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_FORM_NAME")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?
        echo "[<a class='tablebodylink' href='form_edit.php?lang=".LANG."&ID=".$arrResult["FORM_ID"]."'>". $arrResult["FORM_ID"]."</a>] (".$arrResult["VARNAME"].") ".$arrResult["NAME"];
        ?></font></td>
    </tr>
    <?endif;?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_DATE_CREATE")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["DATE_CREATE"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_TIMESTAMP")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["TIMESTAMP_X"]?></font></td>
    </tr>
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_USER")?></b></font></td>
        <td valign="top" nowrap><font class="tablebodytext"><?
            if (intval($arrResult["USER_ID"])>0) :
                echo "<font class='tablebodytext'>[</font><a class='tablebodylink' title='".GetMessage("FORM_EDIT_USER")."' href='user_edit.php?lang=".LANG."&ID=".$arrResult["USER_ID"]."'>".$arrResult["USER_ID"]."</a><font class='tablebodytext'>] (".htmlspecialchars($arrResult["LOGIN"]).") ".htmlspecialchars($arrResult["USER_NAME"])."</font>";
                echo ($arrResult["USER_AUTH"]=="N") ? " <font class='filteroff'>".GetMessage("FORM_NOT_AUTH")."</font>" : "";
            else :
                echo "<font class='tablebodytext'>".GetMessage("FORM_NOT_REGISTERED")."</font>";
            endif;
            ?></font></td>
    </tr>
    <?if (CModule::IncludeModule("statistic")):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_GUEST")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_GUEST_ALT")?>" class="tablebodylink" href="/bitrix/admin/guest_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_GUEST_ID"]?>&set_filter=Y"><?=$arrResult["STAT_GUEST_ID"]?></a>]</font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_SESSION")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_SESSION_ALT")?>" class="tablebodylink" href="/bitrix/admin/session_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_SESSION_ID"]?>&set_filter=Y"><?=$arrResult["STAT_SESSION_ID"]?></a>]</font></td>
    </tr>
    <?endif;?>
    <?endif;?>
</table>
<br>
<?
    /*
    Y - show the required form fields in both filter and table;
    N - hide form fields
    */
    $SHOW_ADDITIONAL = "N";

    /*
    Y - show values of ANSWER_VALUE in round brackets
    N - do not show values of ANSWER_VALUE
    */
    $SHOW_ANSWER_VALUE = "N";

    CForm::ShowResult($RESULT_ID, $VIEW_TEMPLATE, "show", $SHOW_ADDITIONAL, $SHOW_ANSWER_VALUE);

else :
    echo ShowError("Form not found");
endif;
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


CFormAnswer

The CFormAnswer class is used to handle answers.

Fields

Field | Type | Description
ID | int | The answer Id.
FIELD_ID | int | The question ID (alias is QUESTION_ID).
TIMESTAMP_X | datetime | The time the answer parameters were last modified.
MESSAGE | varchar(2000) | The value of the answer parameter ANSWER_TEXT.
VALUE | varchar(255) | The value of the answer parameter ANSWER_VALUE.
FIELD_TYPE varchar(255) The answer field type. The following values are possible:
  • text - single line text input field;
  • textarea - multiline text input field;
  • radio - mutually exclusive button (radio button);
  • checkbox - multiple selection flags (checkbox);
  • dropdown - drop-down list;
  • multiselect - multiple selection list;
  • date - date input field;
  • image - image upload field;
  • file - file upload field;
  • password - password input field;
FIELD_WIDTH | int | Answer field width.
FIELD_HEIGHT | int | Answer field height.
FIELD_PARAM | varchar(2000) | Answer field parameters.
C_SORT | int | Sort index.
ACTIVE | char | Active state flag (Y|N).

Methods

Method | Description
Set | Adds a new answer or modifies the existing one.
GetList | Returns a list of answers by the question ID.
GetByID | Returns the answer parameters.
Copy | Copies an answer.
Delete | Deletes an answer and all result values bound to it.


Copy

CFormAnswer::Copy

mixed
CFormAnswer::Copy(
 int answer_id,
 mixed question_id = false
)

The method Copy is used to copy an answer. Returns the ID of the new answer on success, or false otherwise.

Parameters

Parameter | Description
answer_id | The ID of the answer which is to be copied.
question_id | The ID of the question to which the answer is to be copied. Optional. False by default which means current question.

See Also

  • CForm::Copy
  • CFormField::Copy
  • CFormStatus::Copy

Example

<?
// The ID of the answer "yes" to the question "Are you married"?
$answer_id = 589;

// copy the answer
if ($NEW_ANSWER_ID = CFormAnswer::Copy($answer_id))
{
    echo "The answer #589 has been successfully copied to the new answer #".$NEW_ANSWER_ID
}
else
{
    // display the error description
    global $strError;
    echo $strError;
}
?>


Delete

CFormAnswer::Delete

bool
CFormAnswer::Delete(
 int answer_id,
 int question_id = false,
)

The method Delete deletes an answer and all result values bound to it. Returns true on success, or false otherwise.

Parameters

Parameter | Description
answer_id | The ID of the answer to be deleted.
question_id | The ID of the question to which the deleted answer is bound. If specified, the parameter will speed up the method execution. Optional. False by default.

See Also

  • CForm::Delete
  • CFormField::Delete
  • CFormStatus::Delete
  • CFormResult::Delete

Example

<?
$answer_id = 589; // The answer ID
// delete the answer
if (CFormAnswer::Delete($answer_id))
{
    echo "The answer #589 is deleted.";
}
else
{
    // display the error description
    global $strError;
    echo $strError;
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CFormAnswer::GetByID

CDBResult
CFormAnswer::GetByID(
 int answer_id
)

The method GetByID returns the answer parameters as the CDBResult instanse.

Parameters

Parameter | Description
answer_id | The answer ID.

See Also

  • CFormAnswer fields
  • CFormAnswer::GetList

Example

<?
$answer_id = 589; // The answer ID
$rsAnswer = CFormAnswer::GetByID($answer_id);
$arAnswer = $rsAnswer->Fetch();
echo "<pre>"; print_r($arAnswer); echo "</pre";
?>


GetList

CFormAnswer::GetList

CDBResult
CFormAnswer::GetList(
 int question_id,
 string &by = "s_sort",
 string &order = "asc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of answers as a CDBResult instanse.

Parameters

Parameter | Description
question_id | The question ID.
by Reference to the variable containing the field used to sort the result. The following values are possible:
  • s_id - the answer ID;
  • s_sort - sort index.
order Reference to the variable containing the sort order. The following values are possible:
  • asc - ascending;
  • desc - descending.
filter An array used to filter values. The following keys are possible:
  • ID* - the answer ID (by default the method accepts only the exact matches);
  • ID_EXACT_MATCH - if "N", the method performs loose searches (entry is sufficient) when filtering by the ID;
  • ACTIVE - active state flag. The following values are possible:
    • Y - the answer is active;
    • N - the answer is inactive.
  • MESSAGE* - the value of the ANSWER_TEXT parameter (the method performs loose searches by default);
  • MESSAGE_EXACT_MATCH - set to "Y" for exact match searches when filtering by MESSAGE;
  • VALUE* - the value of the ANSWER_VALUE parameter (the method performs loose searches by default);
  • VALUE_EXACT_MATCH - set to "Y" for exact match searches when filtering by VALUE;
  • FIELD_TYPE* - answer field type (the method performs loose searches by default);
  • FIELD_TYPE_EXACT_MATCH - set to "Y" for exact match searches when filtering by FIELD_TYPE;
  • FIELD_PARAM* - the value of the answer field parameter (the method performs loose searches by default);
  • FIELD_PARAM_EXACT_MATCH - set to "Y" for exact match searches when filtering by FIELD_PARAM.
* - complex logic allowed
is_filtered | Reference to the variable containing true if the returned list is filtered, or false if the returned list is not filtered.

See Also

  • CFormAnswer fields
  • CFormAnswer::GetByID

Example

<?
$QUESTION_ID = 143; // the question ID

// form the filter array
$arFilter = Array(
    // the answer ID is 589 or 590
    "ID"                      => "589 | 590",
    // we need the ID to match exactly
    "ID_EXACT_MATCH"          => "Y",
    // active state flag
    "ACTIVE"                  => "Y",
    // the value of the ANSWER_TEXT parameter is "yes" or "no"
    "MESSAGE"                 => "yes | no",
    // we need the MESSAGE to match exactly
    "MESSAGE_EXACT_MATCH"     => "Y",
    // type of the answer field is radio-button
    "FIELD_TYPE"              => "radio",
    // we need the FIELD_TYPE to match exactly
    "FIELD_TYPE_EXACT_MATCH"  => "Y",
    // parameter includes the string "checked"
    "FIELD_PARAM"             => "checked",
    // we need just an entry in FIELD_PARAM
    "FIELD_PARAM_EXACT_MATCH" => "N"
);

// obtain the list of all answers to the question #143
$rsAnswers = CFormAnswer::GetList(
    $QUESTION_ID,
    $by="s_id",
    $order="desc",
    $arFilter,
    $is_filtered
    );
while ($arAnswer = $rsAnswers->Fetch())
{
    echo "<pre>"; print_r($arAnswer); echo "</pre>";
}
?>


Set

CFormAnswer::Set

mixed
CFormAnswer::Set(
 array fields,
 mixed answer_id = false,
 mixed current_question_id = false
)

The method Set adds a new answer or modifies the existing one. Returns the ID of the modified or added answer on success, or false otherwise.

Parameters

fields Array of value which accept the following keys:
  • QUESTION_ID* - the question ID;
  • MESSAGE* - the value of the answer parameter ANSWER_TEXT;
  • VALUE - the value of the answer parameter ANSWER_VALUE;
  • C_SORT - sort order;
  • ACTIVE - active state flag. One of the following values is possible:
    • Y - the answer is active;
    • N - the answer is inactive (default).
  • FIELD_TYPE - answer field type. The following values are possible:
    • text - single line text input field;
    • textarea - multiline text input field;
    • radio - mutually exclusive button (radio button);
    • checkbox - multiple selection flags (checkbox);
    • dropdown - drop-down list;
    • multiselect - multiple selection list;
    • date - date input field;
    • image - image upload field;
    • file - file upload field;
    • password - password input field;
  • FIELD_WIDTH - answer field width;
  • FIELD_HEIGHT - answer field height;
  • FIELD_PARAM - answer field parameters.
* - required fields.
answer_id The ID of the modified answer.
Optional. False by default which means a new answer is to be added.
current_question_id The ID of the question to which the modified answer is bound. If specified, this parameter will speed up the method execution.
Optional. False by default.

See Also

  • CFormAnswer fields

Example

<?
$QUESTION_ID = 140; // The ID of the question "First and last names"

$arFields = array(
    "QUESTION_ID"   => $QUESTION_ID,
    "MESSAGE"       => " ",
    "C_SORT"        => 100,
    "ACTIVE"        => "Y",
    "FIELD_TYPE"    => "text",
    "FIELD_WIDTH"   => "40"
    );

$NEW_ID = CFormAnswer::Set($arFields);
if ($NEW_ID>0)
    echo "The ID=".$NEW_ID." has been successfully added";
else // error
{
    // display the error description
    global $strError;
    echo $strError;
}
?>

<?
$QUESTION_ID = 143; // The ID of the question "Are you married?"

$arFields = array(
    "QUESTION_ID"      => $QUESTION_ID,
    "MESSAGE"       => "yes",
    "C_SORT"        => 100,
    "ACTIVE"        => "Y",
    "FIELD_TYPE"    => "radio",
    "FIELD_PARAM"   => "checked"
    );
CFormAnswer::Set($arFields);

$arFields = array(
    "QUESTION_ID"      => $QUESTION_ID,
    "MESSAGE"       => "no",
    "C_SORT"        => 200,
    "ACTIVE"        => "Y",
    "FIELD_TYPE"    => "radio"
    );
CFormAnswer::Set($arFields);
?>


CFormField

The CFormField is the class used with questions and fields.

Fields

Field | Type | Description
ID | int | The ID of the question or the field.
SID | varchar(50) | The symbolic identifier of the question or the field.
FORM_ID | int | The ID of the web form to which the question or field is bound.
TIMESTAMP_X | datetime | The time the parameters of the question or field were last modified.
ACTIVE | char | Active state flag (Y|N).
ADDITIONAL | char | If "Y", this record is a field. If "N", the record is a web form question.
FIELD_TYPE varchar(50) Type of the field. The following values are possible:
  • text - text;
  • integer - number;
  • date - date.
TITLE | varchar(2000) | Text of the question or the field title.
TITLE_TYPE | varchar(4) | Type of the question ("text" or "html")
IMAGE_ID | int | The question image.
C_SORT | int | Sort index.
REQUIRED | char | Flag specifying the question must be answered when creating a new result or modifying the existing one (Y|N).
IN_FILTER | char | Specifies the question or field is included in the result filter.
FILTER_TITLE | varchar(2000) | Filter field title.
IN_RESULTS_TABLE | char | If "Y", the value of the question or field is included in the HTML table of results.
IN_EXCEL_TABLE | char | If "Y", the value of the question or field is included in the Excel table of results.
RESULTS_TABLE_TITLE | varchar(2000) | Title of the result table column.
COMMENTS | varchar(2000) | Administrative comments for the question or field.

Methods

Method | Description
Set | Adds a new question or a field or modifies the existing one.
GetList | Returns a list of questions or fields.
GetByID | Returns the parameters of a question or a field by their ID.
GetBySID | Returns the parameters of a question or a field by the symbolic identifier.
Copy | Copies a question or a field.
Reset | Deletes all answers of the specified question or field results.
Delete | Deletes a question or a field and all its answers.


Copy

CFormField::Copy

mixed
CFormField::Copy(
 int field_id,
 string check_rights = "Y",
 mixed form_id = false
)

The method Copy copies a question or a field of a web form. Returns the ID the new question or field on success, or false otherwise.

Parameters

Parameter | Description
field_id | The ID of the question or the field which is to be copied.
check_rights Flag specifying the current user permissions should be checked. One of the following values is possible:
  • Y - permissions should be checked;
  • N - no checks need to be performed.
A user must have the following permissions to copy a question or a field:
  1. [25] view web form parameters for the source web form;
  2. [30] full access for the destination web form.
Optional. "Y" by default which means the permissions should be checked.
form_id The ID of the destination web form to which a question or a field should be copied.
Optional. False by default which means that the current web form is used.

See Also

  • CForm::Copy
  • CFormAnswer::Copy
  • CFormStatus::Copy

Example

<?
$FIELD_ID = 140; // The question ID
// copy the question
if ($NEW_FIELD_ID=CFormField::Copy($FIELD_ID))
{
    echo "The question #140 has been successfully copied to the new question #".$NEW_FIELD_ID;
}
else
{
    // display the error description
    global $strError;
    echo $strError;
}
?>


Delete

CFormField::Delete

bool
CFormField::Delete(
 int field_id,
 string check_rights = "Y"
)

The method Delete deletes a question or a field and all its answers. Returns true on success, or false otherwise.

Parameters

Parameter | Description
field_id | The ID of the question or the field.
check_rights Flag specifying the current user permissions should be checked. One of the following values is possible:
  • Y - permissions should be checked;
  • N - no checks need to be performed.
For this method to succeed, you should have the permission [30] full access for the destination web form containing the field field_id.
Optional. "Y" by default which means the permissions should be checked.

See Also

  • CForm::Delete
  • CFormAnswer::Delete
  • CFormStatus::Delete
  • CFormResult::Delete

Example

<?
$FIELD_ID = 140;
// delete the question #140
if (CFormField::Delete($FIELD_ID))
{
    echo "The question #140 has been deleted.";
}
else
{
    // display the error description
    global $strError;
    echo $strError;
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CFormField::GetByID

CDBResult
CFormField::GetByID(
 int field_id
)

The method GetByID returns the parameters of a question or a field as a CDBResult instance.

Parameters

Parameter | Description
field_id | The ID of the question or the field.

See Also

  • CFormField fields
  • CFormField::GetBySID
  • CFormField::GetList

Example

<?
$FIELD_ID = 140; // The ID of the question or the field of a web form
$rsField = CFormField::GetByID($FIELD_ID);
$arField = $rsField->Fetch();
echo "<pre>"; print_r($arField); echo "</pre";
?>


GetBySID

CFormField::GetBySID

CDBResult
CFormField::GetBySID(
 int field_sid
)

The method GetBySID returns the parameters of a question or a field as a CDBResult instance.

Parameters

Parameter | Description
field_sid | The symbolic identifier of the question or the field.

See Also

  • CFormField fields
  • CFormField::GetByID
  • CFormField::GetList

Example

<?
$FIELD_SID = "VS_INTEREST"; // symbolic identifier of the question or the field of a web form
$rsField = CFormField::GetBySID($FIELD_SID);
$arField = $rsField->Fetch();
echo "<pre>"; print_r($arField); echo "</pre";
?>


GetList

CFormField::GetList

CDBResult
CFormField::GetList(
 int form_id,
 string get_only_fields,
 string &by = "s_sort",
 string &order = "asc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of questions or fields of a web form as a CDBResult instance.

Parameters

Parameter | Description
form_id | The web form ID.
get_only_fields The following values are possible:
  • Y - the returned list should contain only the web form fields;
  • N - the returned list should contain only the web form questions;
  • ALL - the returned list can contain both questions and fields of a web form.
by Reference to the variable containing the field used to sort the result. The following values are possible:
  • s_id - ID;
  • s_active - active state flag;
  • s_sid - the symbolic identifier;
  • s_sort - sort index;
  • s_title - the text of the question or the web form field title;
  • s_comments - administrative comments;
  • s_required - specifies the web form question must be answered;
  • s_in_results_table - specifies the question is to be included in the HTML table of results;
  • s_in_excel_table - specifies the question is to be included in the Excel table of results;
  • s_field_type - type of the web form field.
îrder Reference to the variable containing the sort order. The following values are possible:
  • asc - ascending;
  • desc - descending.
filter An array used to filter values. The following keys are possible:
  • ID* - the ID of the question or the field (by default the method accepts only the exact matches);
  • ID_EXACT_MATCH - if "N", the method performs loose searches (entry is sufficient) when filtering by ID;
  • SID* - the symbolic identifier of the question or the field (by default the method accepts only the exact matches);
  • SID_EXACT_MATCH - if "N", the method performs loose searches (entry is sufficient) when filtering by SID;
  • TITLE* - the text of the question or the web form field title (the method performs loose searches by default);
  • TITLE_EXACT_MATCH - set to "Y" for exact match searches when filtering by TITLE;
  • COMMENTS* - administrative comments (the method performs loose searches by default);
  • COMMENTS_EXACT_MATCH - set to "Y" for exact match searches when filtering by COMMENTS;
  • ACTIVE - active state flag [Y|N];
  • IN_RESULTS_TABLE - specifies the question is to be included in the HTML table of results [Y|N];
  • IN_EXCEL_TABLE - specifies the question is to be included in the Excel table of results [Y|N];
  • IN_FILTER - specifies the question is to be included in the filter [Y|N];
  • REQUIRED - specifies the web form question must be answered [Y|N].
* - complex logic allowed
is_filtered | Reference to the variable containing true if the returned list is filtered, or false if the returned list is not filtered.

See Also

  • CFormField fields
  • CFormField::GetByID
  • CFormField::GetBySID

Example

<?
$FORM_ID = 4; // The ID of the web form

// form the filter array
$arFilter = Array(
    // question ID=140 or ID=141
  "ID"                    => "140 | 141",
    // we need the ID to match exactly
  "ID_EXACT_MATCH"        => "Y",
    // symbolic identifier
  "SID"                   => "VS_BIRTHDAY",
    // match symbolic identifier exactly
  "SID_EXACT_MATCH"       => "Y",
    // text of the question
  "TITLE"                 => "Birthday",
    // entry in text of the question is sufficient
  "TITLE_EXACT_MATCH"     => "N",
    // active state flag
  "ACTIVE"                => "Y",
    // we need questions which are in the HTML table of results
  "IN_RESULTS_TABLE"      => "Y",
    // we need questions which are in the Excel table of results
  "IN_EXCEL_TABLE"        => "N",
    // we need questions which are in the filter
  "IN_FILTER"             => "Y",
    // questions requiring an answer
  "REQUIRED"              => "Y",
);

// obtain the list of all questions of the web form #4
$rsQuestions = CFormField::GetList(
    $FORM_ID,
    "N",
    $by="s_id",
    $order="desc",
    $arFilter,
    $is_filtered
    );
while ($arQuestion = $rsQuestions->Fetch())
{
    echo "<pre>"; print_r($arQuestion); echo "</pre>";
}
?>


Reset

CFormField::Reset

bool
CFormField::Reset(
 int field_id,
 string check_rights = "Y"
)

The method Reset deletes all answers of the specified question or field results. Returns true on success, or false otherwise.

Parameters

Parameter | Description
field_id | The ID of the question or the field.
check_rights Flag specifying the current user permissions should be checked. One of the following values is possible:
  • Y - permissions should be checked;
  • N - no checks need to be performed.
For this method to succeed, you should have the permission [30] Full access for the destination web form containing the field field_id.

Optional. "Y" by default which means the permissions should be checked.

See Also

  • CForm::Reset
  • CFormResult::Reset

Example

<?
$FIELD_ID = 4;
// delete all answers of the question with ID=140 from results
if (CFormField::Reset($FIELD_ID))
{
    echo "Deletion OK.";
}
else
{
    // display the error description
    global $strError;
    echo $strError;
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


Set

CFormField::Set

mixed
CFormField::Set(
 array fields,
 mixed field_id = false,
 string check_rights = "Y"
)

The method Set adds a new question or a field or modifies the existing one. Returns the ID of the modified or added question or field on success, or false otherwise.

Parameters

Parameter Description
fields Array of values which accept the following keys:
  • SID* - the symbolic identifier of the question or the field;
  • FORM_ID* - the web form ID;
  • ACTIVE - active state flag. The following values are possible:
    • Y - the question or the field is active;
    • N - the question or the field is inactive (by default).
  • ADDITIONAL - the following values are possible:
    • Y - the record is the web form field;
    • N - the record is the web form question (by default).
  • FIELD_TYPE* - type of the field. The following values are possible:
    • text - text;
    • integer - number;
    • date - date.
  • TITLE - the text of the question or the field title;
  • TITLE_TYPE* - type of the question. The following values are possible:
    • text - text;
    • html - HTML code.
  • C_SORT - sort order;
  • REQUIRED* - specifies the question must be answered:
    • Y - answer to this question is mandatory;
    • N - answer to this question is mandatory (by default).
  • FILTER_TITLE - filter field title;
  • IN_RESULTS_TABLE - specifies the entity (question or field) should be included in the HTML table of results:
    • Y - included;
    • N - not included (by default).
  • IN_EXCEL_TABLE - specifies the entity (question or field) should be included in the Excel table of results:
    • Y - included;
    • N - not included (by default).
  • RESULTS_TABLE_TITLE - title of the result table column;
  • COMMENTS - administrative comments;
  • arIMAGE** - array containing the question image description. The following values are possible in this array:
    • name - file name;
    • size - file size;
    • tmp_name - temporary path on the server;
    • type - type of the uploaded file;
    • del - set to "Y" to delete the image;
    • MODULE_ID - the Web Form module identifier (form).
  • arANSWER** - array containing answers to the question. Has the following structure:
    Array
(
    [0] => Array
        (
            [ID] => ID
            [DELETE] => specifies to delete this answer [Y|N]
            [MESSAGE] => ANSWER_TEXT parameter
            [VALUE] => ANSWER_VALUE parameter
            [C_SORT] => sort order
            [ACTIVE] => active state flag [Y|N]
            [FIELD_TYPE] => field type. The following values are possible:

                text - single line text input field
                textarea - multiline text input field
                radio* - mutually exclusive button (radio button)
                checkbox* - multiple selection flags (checkbox)
                dropdown* - drop-down list
                multiselect* - multiple selection list
                date - date input field
                image - image upload field
                file - file upload field
                password - password input field

            [FIELD_WIDTH] => input field width
            [FIELD_HEIGHT] => input field height
            [FIELD_PARAM] => additional parameters;
                any HTML tags are allowed here;
                types marked with asterisk allows the following reserved values:

                checked - answer is selected (synonym: selected) (default);
                not_answer - if this item is selected,
                             a user has not given an answer to the question.
                          Usually, the first item in a list. Important when
                          REQUIRED="Y")
        )
    [1] => array containing the following answer
    ...
)
  • arFILTER_USER** - array of filter fields used to filter by the value of the answer entered by a user when filling in the web form. The following values are possible in this array:
    • text - filter text field;
    • integer - filter fields for number ranges;
    • date - filter fields for date ranges;
    • exist - field for filtering by the presence of the entered answer.
  • arFILTER_ANSWER_TEXT** - array of filter fields used to filter by the value of the ANSWER_TEXT answer parameter. The following values are possible in this array:
    • text - filter text field;
    • integer - filter fields for number ranges;
    • dropdown - single selection drop-down list;
    • exist - field for filtering by the presence of the filter answer text.
  • arFILTER_ANSWER_VALUE** - array of filter fields used to filter by the value of the ANSWER_VALUE answer parameter. The following values are possible in this array:
    • text - filter text field;
    • integer - filter fields for number ranges;
    • dropdown - single selection drop-down list;
    • exist - field for filtering by the presence of filter answer value.
  • arFILTER_FIELD* - array of filter fields used to filter by the web form fields values:
    • text - filter text field;
    • integer - filter fields for number ranges;
    • date - filter fields for date ranges.

* - required;
* - required by web form fields only;
** - required by web form questions only.
field_id The ID of the modified question or field.
Optional. False by default (adds a new question or a field).
check_rights Flag specifying the current user permissions should be checked. One of the following values is possible:
  • Y - permissions should be checked;
  • N - no checks need to be performed.
To add a new question or a field or to modify their parameters, you should have the permission [30] Full access for the destination web form specified in fields["FORM_ID"].

Optional. "Y" by default which means the permissions should be checked.

See Also

  • CFormField fields
  • Web form permissions
  • CFile::MakeFileArray

Example

<?
/*************************************************
         Add a web form question
*************************************************/

// create an array containing the description of image
// stored in the file on server
$arIMAGE = CFile::MakeFileArray($_SERVER["DOCUMENT_ROOT"]."/images/question.gif");
$arIMAGE["MODULE_ID"] = "form";

// build an array of answers
$arANSWER = array();

$arANSWER[] = array(
    "MESSAGE"     => "yes",                           // ANSWER_TEXT parameter
    "C_SORT"      => 100,                            // sort order
    "ACTIVE"      => "Y",                            // active state flag
    "FIELD_TYPE"  => "radio",                        // type of the answer
    "FIELD_PARAM" => "checked class=\"inputradio\""  // the answer parameters
    );

$arANSWER[] = array(
    "MESSAGE"     => "no",
    "C_SORT"      => 200
    "ACTIVE"      => "Y",
    "FIELD_TYPE"  => "radio"
    );

// build an array of fields
$arFields = array(
    "FORM_ID"              => 4,                     // The web form ID
    "ACTIVE"               => Y,                     // active state flag
    "TITLE"                => "Are you married?",    // text of the question
    "TITLE_TYPE"           => "text",                // type of the question text
    "SID"                  => "VS_MARRIED",          // question symbolic identifier
    "C_SORT"               => 400,                   // sort order
    "ADDITIONAL"           => "N",                   // we need a web form question
    "REQUIRED"             => "Y",                   // the question must be answered
    "IN_RESULTS_TABLE"     => "Y",                   // add to HTML table of results
    "IN_EXCEL_TABLE"       => "Y",                   // add to Excel table of results
    "FILTER_TITLE"         => "Married",             // filter field title
    "RESULTS_TABLE_TITLE"  => "Married",             // table title
    "arIMAGE"              => $arIMAGE,              // question image
    "arFILTER_ANSWER_TEXT" => array("dropdown"),     // type of filter by ANSWER_TEXT
    "arANSWER"             => $arANSWER,             // array of answers
);

// add a new question
$NEW_ID = CFormField::Set($arFields);
if ($NEW_ID>0) echo "A new question with ID=".$NEW_ID has been added;
else // error
{
    // display the error description
    global $strError;
    echo $strError;
}
?>

<?
/*************************************************
          Add a web form field
*************************************************/

$arFields = array(
    "FORM_ID"             => 4
    "ACTIVE"              => "Y",
    "TITLE"               => "Calculated price",
    "SID"                 => "VS_PRICE",
    "C_SORT"              => 1000,
    "ADDITIONAL"          => "Y",
    "IN_RESULTS_TABLE"    => "Y",
    "IN_EXCEL_TABLE"      => "Y",
    "FIELD_TYPE"          => "text",
    "FILTER_TITLE"        => "Price",
    "RESULTS_TABLE_TITLE" => "Price",
    "arFILTER_FIELD"      => array("text")
    );

// add a new field
$NEW_ID = CFormField::Set($arFields);
if ($NEW_ID>0) echo "A new field with ID=".$NEW_ID has been added;
else // error
{
    // display the error description
    global $strError;
    echo $strError;
}
?>


CFormResult

The CFormResult class facilitates handling the web form results.

Methods

Method | Description
GetList | The method is used to get a list of form results with respect to the current user permissions.
Add | Saves a new result in the database.
Update | The method updates an existing result in the database.
GetByID | The function returns a selection from the database containing the result fields and some parameters of a form.
GetDataByID | The function returns answers to the form questions and form fields values from the result stored in the database.
GetDataByIDForWeb | Returns an array of the result values in the special format used by the template for the result editing.
GetPermissions | The function returns an array of permissions to the result depending on its status.
SetField | The method sets a new value of the form field result.


Add

CFormResult::Add

int
CFormResult::Add(
 int WEB_FORM_ID,
 array arrVALUES=false
 char(1) CHECK_RIGHTS=Y
 integer USER_ID=false
);

Saves a new result in the database.

Parameters

Parameter | Description
WEB_FORM_ID | The web form ID.
arVALUES | Array of input values. In this parameter is false or not specified, it is taken from the array stored in $HTTP_POST_VARS. If $HTTP_POST_VARS is empty, it is taken from the array $HTTP_GET_VARS.
CHECK_RIGHTS | If set to "Y", user permissions will be checked when adding a result. If "N", no checks are performed.
USER_ID | The ID of a user who created this result. By default, the ID of the current user is recorded.

Return Values

Returns the ID of the saved result on success, or 0 otherwise.

Example

The following is an example of array $HTTP_POST_VARS passed to arrVALUES.

Array
(
    [form_text_586] => John Smith
    [form_date_587] => 10.03.1992
    [form_textarea_588] => London
    [form_radio_VS_MARRIED] => 589
    [form_checkbox_VS_INTEREST] => Array
        (
            [0] => 592
            [1] => 593
            [2] => 594
        )

    [form_dropdown_VS_AGE] => 597
    [form_multiselect_VS_EDUCATION] => Array
        (
            [0] => 603
            [1] => 604
        )

    [form_text_606] => 2345
    [form_image_607] => 1045
)

The below example shows the sample file "form_fill.php" displaying the form.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("form"))
{
    if (intval($WEB_FORM_ID)>0)
        $z = <b>CForm::GetByID</b>($WEB_FORM_ID);
    else
        $z = CForm::GetBySID($WEB_FORM_NAME);

    if (!($zr=$z->Fetch()))
    {
        $FORM_EXIST = "N";
        $strError .= "Invalid form ID.<br>";
    }
    else
    {
        $FORM_EXIST = "Y";
        $WEB_FORM_ID = $zr["ID"];
        $WEB_FORM_NAME = $zr["VARNAME"];
        if ($REQUEST_METHOD=="POST" &&
            intval($WEB_FORM_ID)>0 &&
            strlen($web_form_submit)>0)
        {
            $arrVALUES = $HTTP_POST_VARS;
            $error = CForm::Check($WEB_FORM_ID);
            if (strlen($error)<=0)
            {
                if ($RESULT_ID = CFormResult::Add($WEB_FORM_ID))
                {
                    $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
                    $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
                    CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
                    CForm::SetEvent($RESULT_ID);
                    CForm::Mail($RESULT_ID);
                    LocalRedirect("index.php?WEB_FORM_NAME=".$WEB_FORM_NAME. "&strNote=".urlencode("information saved"));
                }
            }
            else
                $strError .= $error;
        }
    }
}

if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle("Visitor survey");

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
echo ShowNote($strNote);
echo ShowError($strError);
?><?
if (CModule::IncludeModule("form"))
    CForm::Show($WEB_FORM_NAME, $arrVALUES);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetByID

CFormResult::GetByID

record set
CFormResult::GetByID(
 int ID
);

The function returns a selection from the database containing the result fields and some parameters of a form.

Parameters

Parameter | Description
ID | Result ID.

Return Values

Returns a database record containing the form parameters. See Example for details on handling the result.

Example

The following is an example of one row of the selection returned by CFormResult::GetByID.

Array
(
    [ID] => 176 (result ID)
    [TIMESTAMP_X] => 22.09.2003 17:11:04 (result modification date)
    [DATE_CREATE] => 22.09.2003 17:11:04 (result creation date)
    [STATUS_ID] => 4 (ID of the result status)
    [FORM_ID] => 4 (ID of the form)
    [USER_ID] => 2 (ID of the user who created the result)
    [USER_AUTH] => Y (user authorized)
    [STAT_GUEST_ID] => 32904 (user ID in the statistics module)
    [STAT_SESSION_ID] => 40348 (session ID in the statistics module)
    [NAME] => Visitor review (form name)
    [VARNAME] => ANKETA (form identifier)
    [IMAGE_ID] => 717 (ID of the form image)
    [DESCRIPTION] => This form is for test only (description)
    [DESCRIPTION_TYPE] => text (description type)
    [SHOW_RESULT_TEMPLATE] => default.php (form view template)
    [PRINT_RESULT_TEMPLATE] => default.php (form print template)
)

The below example shows the sample file "form_edit.php" allowing to edit the result.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
include(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/admin/lang/",
                        "/form_result_edit.php"));
$RESULT_ID = intval($RESULT_ID);
$z = CFormResult::GetByID($RESULT_ID);
if (!($arrResult=$z->Fetch()))
{
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
    echo ShowError("Survey form not found");
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
    die();
}
$WEB_FORM_ID = intval($arrResult["FORM_ID"]);
$F_RIGHT = intval(CForm::GetPermission($WEB_FORM_ID));

/*
Y - allow to edit the form fields
N - do not allow to edit the form fields
*/
$EDIT_ADDITIONAL = "N";

if ($F_RIGHT>=25 || ($F_RIGHT>=15 && $USER->GetID()==$arrResult["USER_ID"])) :

    // "Save results" clicked
    if ($REQUEST_METHOD=="POST" &&
             intval($WEB_FORM_ID)>0 &&
             (strlen($web_form_submit)>0 || strlen($apply)>0))
    {
        // obtain the form data array
        $arrVALUES = $HTTP_POST_VARS;
        $error = CForm::Check($WEB_FORM_ID, $arrVALUES, $RESULT_ID);
        if (strlen($error)<=0)
        {
            CFormResult::Update($RESULT_ID, $arrVALUES, $EDIT_ADDITIONAL);
            $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
            $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
            CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
            if (strlen($web_form_submit)>0)
                LocalRedirect("index.php?WEB_FORM_NAME=".$arrResult["VARNAME"]);
        }
        else $strError .= $error;
    }
    else
    // obtain the data array from the database
        $arrVALUES = CFormResult::GetDataByIDForWeb($RESULT_ID,$EDIT_ADDITIONAL);
endif;

$title = str_replace("#RESULT_ID#","$RESULT_ID","Editing form # #RESULT_ID#");
$APPLICATION->SetTitle($title);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
<a href="index.php?WEB_FORM_NAME=<?=$arrResult["VARNAME"]?>" class="navchain">Forms</a>
<br><br>
<table cellspacing="0" cellpadding="2">
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b>ID:</b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["ID"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_FORM_NAME")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?
        echo "[<a class='tablebodylink' href='form_edit.php?lang=".LANG."&ID=".$WEB_FORM_ID."'>". $WEB_FORM_ID."</a>] (".$arrResult["VARNAME"].") ".$arrResult["NAME"];
        ?></font></td>
    </tr>
    <?endif;?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_DATE_CREATE")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["DATE_CREATE"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_TIMESTAMP")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["TIMESTAMP_X"]?></font></td>
    </tr>
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_USER")?></b></font></td>
        <td valign="top" nowrap><font class="tablebodytext"><?
            if (intval($arrResult["USER_ID"])>0) :
                echo "<font class='tablebodytext'>[</font><a class='tablebodylink' title='".GetMessage("FORM_EDIT_USER")."' href='user_edit.php?lang=".LANG."&ID=".$arrResult["USER_ID"]."'>".$arrResult["USER_ID"]."</a><font class='tablebodytext'>] (".htmlspecialchars($arrResult["LOGIN"]).") ".htmlspecialchars($arrResult["USER_NAME"])."</font>";
                echo ($arrResult["USER_AUTH"]=="N") ? " <font class='filteroff'>".GetMessage("FORM_NOT_AUTH")."</font>" : "";
            else :
                echo "<font class='tablebodytext'>".GetMessage("FORM_NOT_REGISTERED")."</font>";
            endif;
            ?></font></td>
    </tr>
    <?if (CModule::IncludeModule("statistic")):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_GUEST")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_GUEST_ALT")?>" class="tablebodylink" href="/bitrix/admin/guest_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_GUEST_ID"]?>&set_filter=Y"><?=$arrResult["STAT_GUEST_ID"]?></a>]</font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_SESSION")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_SESSION_ALT")?>" class="tablebodylink" href="/bitrix/admin/session_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_SESSION_ID"]?>&set_filter=Y"><?=$arrResult["STAT_SESSION_ID"]?></a>]</font></td>
    </tr>
    <?endif;?>
    <?endif;?>
</table>
<br>
<?
CForm::EditResult($RESULT_ID, $arrVALUES, $EDIT_RESULT_TEMPLATE, $EDIT_ADDITIONAL);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetDataByID

CFormResult::GetDataByID

array
CFormResult::GetDataByID(
 int RESULT_ID,
 array arrFIELD_VARNAME,
 array &arrRES,
 array &arrANSWER
);

The function returns answers to the form questions and form fields values from the result stored in the database.

Parameters

Parameter | Description
RESULT_ID | Result ID.
arrFIELD_VARNAME | Array of ID's of the form questions and fields for which the values are to be returned.
arrRES | Array containing the form result fields on return (see Example).
arrANSWER | Array containing answers to the form questions and the fields values on return (see Example).

Example

Sample array arrRES

Array
(
    [ID] => 146
    [TIMESTAMP_X] => 2003-09-18 01:20:15
    [DATE_CREATE] => 18.09.2003 01:20:15
    [VALID] => Y
    [FORM_ID] => 4
    [USER_ID] => 1
    [USER_AUTH] => Y
    [STAT_GUEST_ID] => 33
    [STAT_SESSION_ID] => 171
)

Sample array arrANSWER

arrANSWERArray
(
    [VS_NAME] => Array
        (
            [586] => Array
                (
                    [RESULT_ID] => 147
                    [FIELD_ID] => 140
                    [ANSWER_ID] => 586
                    [ANSWER_TEXT] =>
                    [ANSWER_VALUE] =>
                    [USER_TEXT] => John
                    [USER_FILE_ID] =>
                    [USER_FILE_NAME] =>
                    [USER_DATE] =>
                    [VARNAME] => VS_NAME
                    [TITLE] => name
                    [TITLE_TYPE] => html
                    [MESSAGE] =>
                    [VALUE] =>
                    [FIELD_TYPE] => text
                    [FIELD_WIDTH] => 50
                    [FIELD_HEIGHT] => 0
                    [FIELD_PARAM] =>
                )

        )

    [VS_PHOTO] => Array
        (
            [607] => Array
                (
                    [RESULT_ID] => 147
                    [FIELD_ID] => 148
                    [ANSWER_ID] => 607
                    [ANSWER_TEXT] =>
                    [ANSWER_VALUE] =>
                    [USER_TEXT] =>
                    [USER_FILE_ID] => 704
                    [USER_FILE_NAME] => apc.jpg
                    [USER_DATE] =>
                    [VARNAME] => VS_PHOTO
                    [TITLE] => photo
                    [TITLE_TYPE] => text
                    [MESSAGE] =>
                    [VALUE] =>
                    [FIELD_TYPE] => image
                    [FIELD_WIDTH] => 30
                    [FIELD_HEIGHT] => 0
                    [FIELD_PARAM] =>
                )

        )

)

Sample array returned by GetDataByID

Array
(
    [VS_NAME] => Array
        (
            [0] => Array
                (
                    [RESULT_ID] => 147
                    [FIELD_ID] => 140
                    [ANSWER_ID] => 586
                    [ANSWER_TEXT] =>
                    [ANSWER_VALUE] =>
                    [USER_TEXT] => John
                    [USER_FILE_ID] =>
                    [USER_FILE_NAME] =>
                    [USER_DATE] =>
                    [VARNAME] => VS_NAME
                    [TITLE] => name
                    [TITLE_TYPE] => html
                    [MESSAGE] =>
                    [VALUE] =>
                    [FIELD_TYPE] => text
                    [FIELD_WIDTH] => 50
                    [FIELD_HEIGHT] => 0
                    [FIELD_PARAM] =>
                )

        )

    [VS_PHOTO] => Array
        (
            [0] => Array
                (
                    [RESULT_ID] => 147
                    [FIELD_ID] => 148
                    [ANSWER_ID] => 607
                    [ANSWER_TEXT] =>
                    [ANSWER_VALUE] =>
                    [USER_TEXT] =>
                    [USER_FILE_ID] => 704
                    [USER_FILE_NAME] => apc.jpg
                    [USER_DATE] =>
                    [VARNAME] => VS_PHOTO
                    [TITLE] => Photo
                    [TITLE_TYPE] => text
                    [MESSAGE] =>
                    [VALUE] =>
                    [FIELD_TYPE] => image
                    [FIELD_WIDTH] => 30
                    [FIELD_HEIGHT] => 0
                    [FIELD_PARAM] =>
                )

        )

)

The below example shows the sample file "form_fill.php" displaying the form.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("form"))
{
    if (intval($WEB_FORM_ID)>0)
        $z = <b>CForm::GetByID</b>($WEB_FORM_ID);
    else
        $z = CForm::GetBySID($WEB_FORM_NAME);

    if (!($zr=$z->Fetch()))
    {
        $FORM_EXIST = "N";
        $strError .= "Invalid form ID.<br>";
    }
    else
    {
        $FORM_EXIST = "Y";
        $WEB_FORM_ID = $zr["ID"];
        $WEB_FORM_NAME = $zr["VARNAME"];
        if ($REQUEST_METHOD=="POST" &&
            intval($WEB_FORM_ID)>0 &&
            strlen($web_form_submit)>0)
        {
            $arrVALUES = $HTTP_POST_VARS;
            $error = CForm::Check($WEB_FORM_ID);
            if (strlen($error)<=0)
            {
                if ($RESULT_ID = CFormResult::Add($WEB_FORM_ID))
                {
                    $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
                    $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
                    CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
                    CForm::SetEvent($RESULT_ID);
                    CForm::Mail($RESULT_ID);
                    LocalRedirect("index.php?WEB_FORM_NAME=".$WEB_FORM_NAME. "&strNote=".urlencode("Information saved"));
                }
            }
            else
                $strError .= $error;
        }
    }
}

if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle("Visitor survey");

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
echo ShowNote($strNote);
echo ShowError($strError);
?><?
if (CModule::IncludeModule("form"))
    CForm::Show($WEB_FORM_NAME, $arrVALUES);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetDataByIDForWeb

CFormResult::GetDataByIDForWeb

array
CFormResult::GetDataByIDForWeb(
 int RESULT_ID,
 char(1) GET_ADDITIONAL="N"
);

Returns an array of the result values in the special format used by the template for the result editing.

Parameters

Parameter | Description
RESULT_ID | Result ID
GET_ADDITIONAL | If "Y", the returned array also contains form fields. Otherwise, it contains questions only.

Example

Sample return:

Array
(
    [form_text_586] => John
    [form_date_587] => 10.03.1992
    [form_textarea_588] => London
    [form_radio_VS_MARRIED] => 589
    [form_checkbox_VS_INTEREST] => Array
        (
            [0] => 592
            [1] => 593
            [2] => 594
        )

    [form_dropdown_VS_AGE] => 597
    [form_multiselect_VS_EDUCATION] => Array
        (
            [0] => 603
            [1] => 604
        )

    [form_text_606] => 2345
    [form_image_607] => 1045
)

The below example shows the sample file "form_edit.php" allowing to edit the result.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
include(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/admin/lang/",
                        "/form_result_edit.php"));
$RESULT_ID = intval($RESULT_ID);
$z = CFormResult::GetByID($RESULT_ID);
if (!($arrResult=$z->Fetch()))
{
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
    echo ShowError("Survey form not found");
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
    die();
}
$WEB_FORM_ID = intval($arrResult["FORM_ID"]);
$F_RIGHT = intval(CForm::GetPermission($WEB_FORM_ID));

/*
Y - allow to edit the form fields
N - do not allow to edit the form fields
*/
$EDIT_ADDITIONAL = "N";

if ($F_RIGHT>=25 || ($F_RIGHT>=15 && $USER->GetID()==$arrResult["USER_ID"])) :

    // "Save results" clicked
    if ($REQUEST_METHOD=="POST" &&
             intval($WEB_FORM_ID)>0 &&
             (strlen($web_form_submit)>0 || strlen($apply)>0))
    {
        // obtain the form data array
        $arrVALUES = $HTTP_POST_VARS;
        $error = CForm::Check($WEB_FORM_ID, $arrVALUES, $RESULT_ID);
        if (strlen($error)<=0)
        {
            CFormResult::Update($RESULT_ID, $arrVALUES, $EDIT_ADDITIONAL);
            $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
            $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
            CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
            if (strlen($web_form_submit)>0)
                LocalRedirect("index.php?WEB_FORM_NAME=".$arrResult["VARNAME"]);
        }
        else $strError .= $error;
    }
    else
    // obtain the data array from the database
        $arrVALUES = CFormResult::GetDataByIDForWeb($RESULT_ID,$EDIT_ADDITIONAL);
endif;

$title = str_replace("#RESULT_ID#","$RESULT_ID","Editing form # #RESULT_ID#");
$APPLICATION->SetTitle($title);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
<a href="index.php?WEB_FORM_NAME=<?=$arrResult["VARNAME"]?>" class="navchain">Forms</a>
<br><br>
<table cellspacing="0" cellpadding="2">
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b>ID:</b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["ID"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_FORM_NAME")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?
        echo "[<a class='tablebodylink' href='form_edit.php?lang=".LANG."&ID=".$WEB_FORM_ID."'>". $WEB_FORM_ID."</a>] (".$arrResult["VARNAME"].") ".$arrResult["NAME"];
        ?></font></td>
    </tr>
    <?endif;?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_DATE_CREATE")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["DATE_CREATE"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_TIMESTAMP")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["TIMESTAMP_X"]?></font></td>
    </tr>
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_USER")?></b></font></td>
        <td valign="top" nowrap><font class="tablebodytext"><?
            if (intval($arrResult["USER_ID"])>0) :
                echo "<font class='tablebodytext'>[</font><a class='tablebodylink' title='".GetMessage("FORM_EDIT_USER")."' href='user_edit.php?lang=".LANG."&ID=".$arrResult["USER_ID"]."'>".$arrResult["USER_ID"]."</a><font class='tablebodytext'>] (".htmlspecialchars($arrResult["LOGIN"]).") ".htmlspecialchars($arrResult["USER_NAME"])."</font>";
                echo ($arrResult["USER_AUTH"]=="N") ? " <font class='filteroff'>".GetMessage("FORM_NOT_AUTH")."</font>" : "";
            else :
                echo "<font class='tablebodytext'>".GetMessage("FORM_NOT_REGISTERED")."</font>";
            endif;
            ?></font></td>
    </tr>
    <?if (CModule::IncludeModule("statistic")):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_GUEST")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_GUEST_ALT")?>" class="tablebodylink" href="/bitrix/admin/guest_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_GUEST_ID"]?>&set_filter=Y"><?=$arrResult["STAT_GUEST_ID"]?></a>]</font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_SESSION")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_SESSION_ALT")?>" class="tablebodylink" href="/bitrix/admin/session_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_SESSION_ID"]?>&set_filter=Y"><?=$arrResult["STAT_SESSION_ID"]?></a>]</font></td>
    </tr>
    <?endif;?>
    <?endif;?>
</table>
<br>
<?
CForm::EditResult($RESULT_ID, $arrVALUES, $EDIT_RESULT_TEMPLATE, $EDIT_ADDITIONAL);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


GetList

CFormResult::GetList

record set
CFormResult::GetList(
 int FORM_ID,
 varchar &by,
 varchar &order,
 array arFilter=array(),
 boolean &is_filtered
 char(1) CHECK_RIGHTS="Y"
);

The method is used to get a list of form results with respect to the current user permissions. The list returned is the selection from the database (a record set) with the result fields. Use the function CForm::GetResultAnswerArray get the form questions, fields and their values.

Parameters

Parameter | Description
FORM_ID | Form ID.
by Allows to specify the name of the field by which the sorting is to be performed. The following values allowed:
  • s_id - by result ID
  • s_date_create - by the creation date
  • s_timestamp - by the modification date (default)
  • s_user_id - by the user ID
  • s_guest_id - by the visitor ID (Statistics module)
  • s_session_id - by the session ID (Statistics module)
  • s_status - by the status ID
order Sort order. The following values apply:
  • desc - descending (default)
  • asc - ascending
arFilter Array used as the values filter. The following key names apply:
  • ID - result ID (complex logics allowed)
  • ID_EXACT_MATCH - set to "Y" for exact match searches or to "N" to let ID match partially;
  • STATUS - status ID
  • STATUS_ID - status ID (complex logics allowed)
  • STATUS_ID_EXACT_MATCH - set to "Y" for exact match searches or to "N" to let status ID match partially;
  • TIMESTAMP_1 - minimum modification date in the format of the current site;
  • TIMESTAMP_2 - maximum modification date in the format of the current site;
  • DATE_CREATE_1 - minimum creation date in the format of the current site;
  • DATE_CREATE_2 - maximum creation date in the format of the current site;
  • REGISTERED - is the result creator a registered user (Y/ N)
  • USER_AUTH - is the result creator authorized (Y/ N)
  • USER_ID - ID of a user who created the result (complex logics allowed)
  • USER_ID_EXACT_MATCH - set to "Y" for exact match searches or to "N" to let user ID match partially;
  • GUEST_ID - ID of a visitor as the result creator (visitor ID is assigned by the Statistics module) (complex logics allowed)
  • GUEST_ID_EXACT_MATCH - set to "Y" for exact match searches or to "N" to let visitor ID match partially;
  • SESSION_ID - session ID of a visitor (session ID is assigned by the Statistics module) (complex logics allowed)
  • SESSION_ID_EXACT_MATCH - set to "Y" for exact match searches or to "N" to let session ID match partially;
  • FIELDS - array of arrays describing a single field used to filter answers and fields.

    IMPORTANT!     This array can contain only fields with the flag Use in result filter set.

    These arrays allow the following fields.
    • CODE - code of the field by which the result is filtered
    • PARAMETER_NAME - type of data by which the result is filtered:
      • USER - user-supplied text
      • ANSWER_TEXT - by ANSWER_TEXT
      • ANSWER_VALUE - by ANSWER_VALUE
    • VALUE - value by which the result is filtered (complex logics allowed)
    • FILTER_TYPE - filter type, defines the data type:
      • integer - treat data as integers (only used with PARAMETER_NAME = [ USER | ANSWER_TEXT | ANSWER_VALUE ])
      • text - treat data as text (only used with PARAMETER_NAME = [ USER | ANSWER_TEXT | ANSWER_VALUE ])
      • date - treat data as a date (only used with PARAMETER_NAME = USER)
      • answer_id - filter by matching ID of an answer only (PARAMETER_NAME does not matter)
    • PART - if FILTER_TYPE = [ integer | date ], this field is required to have one of the following values:
      • 0 - match exactly;
      • 1 - left part of the range ("from");
      • 2 - right part of the range ("to");
    • EXACT_MATCH - if the type is "text", this filed may be one of the following:
      • Y - match exactly;
      • N - allow partial matches (default).
is_filtered | Contains true on return if the results has been filtered, or false otherwise.
CHECK_RIGHTS | If set to "Y", user permissions will be checked when adding a result. If "N", no checks are performed.

Example

Sample PHP code used to define the array arFilter:

$arFilter = array(
    "ID"                   => "1 | 2"
    "STATUS_ID"            => "9 | 10",
    "TIMESTAMP_1"          => "10.10.2003",
    "TIMESTAMP_2"          => "15.10.2003",
    "DATE_CREATE_1"        => "10.10.2003",
    "DATE_CREATE_2"        => "12.10.2003",
    "REGISTERED"           => "Y",
    "USER_AUTH"            => "N",
    "USER_ID"              => "45 | 35",
    "USER_ID_EXACT_MATCH"  => "Y", // match ID or login name exactly
    "GUEST_ID"             => "4456 | 7768",
    "SESSION_ID"           => "456456 | 778768",
    "FIELDS"               => array(
        0 => array(
            "CODE"              => "GAME_ID",       // code of the filtering field
            "FILTER_TYPE"       => "integer",       // filter by integer field
            "PARAMETER_NAME"    => "USER",          // filter by user text
            "VALUE"             => $arGame["ID"],   // value to filter by
            "PART"              => 0                // exact match
            ),
        1 => array(
            "CODE"              => "GAME_NAME",     // code of the filtering field
            "FILTER_TYPE"       => "text",          // filter by integer field
            "PARAMETER_NAME"    => "USER",          // filter by user text
            "VALUE"             => "Tetris",        // value to filter by
            "EXACT_MATCH"       => "Y"              // exact match
            )
        2 => array(
            "CODE"              => "GENRE_ID",      // code of the filtering field
            "FILTER_TYPE"       => "integer",       // filter by integer field
            "PARAMETER_NAME"    => "ANSWER_VALUE",  // filter by ANSWER_VALUE
            "VALUE"             => "3",             // value to filter by
            "PART"              => 1                // from
            ),
        3 => array(
            "CODE"              => "GENRE_ID",      // code of the filtering field
            "FILTER_TYPE"       => "integer",       // filter by integer field
            "PARAMETER_NAME"    => "ANSWER_VALUE",  // filter by ANSWER_VALUE
            "VALUE"             => "6",             // value to filter by
            "PART"              => 2                // to
            )
        )
    );

Example

$arFilter = array(
    "STATUS_ID" => "9 | 10",                   // filter results with status 9 or 10
    "FIELDS"    => array(
        0 => array(
            "CODE"           => "GAME_ID",     // code of the filtering field
            "FILTER_TYPE"    => "integer",     // filter as integer
            "PARAMETER_NAME" => "USER",        // filter by user text
            "VALUE"          => $arGame["ID"], // value to filter by
            "PART"           => 0              // exact match
            ),
        )
    );
$rsComments = CFormResult::GetList($arForm["ID"],
                                   ($by="s_timestamp"),
                                   ($order="desc"),
                                   $arFilter, $is_filtered);


GetPermissions

CFormResult::GetPermissions

array
CFormResult::GetPermissions(
 int RESULT_ID,
 int &STATUS_ID
);

The function returns an array of permissions to the result depending on its status.

Parameters

Parameter | Description
RESULT_ID | Result ID.
STATUS_ID | Returned status ID in which the result is.

Return Values

  • "VIEW" - result view allowed;
  • "EDIT" - result editing allowed;
  • "DELETE" - result deletion allowed.

Example

The below example shows the sample file "form_view.php" used to display the result.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
include(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/admin/lang/", "/form_result_view.php"));
$APPLICATION->SetTitle(str_replace("#RESULT_ID#","$RESULT_ID","View form # #RESULT_ID#"));
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
<?
$z = CFormResult::GetByID($RESULT_ID);
if ($arrResult = $z->Fetch()) :

    ?><a href="index.php?WEB_FORM_NAME=<?=$zr["VARNAME"]?>" class="navchain">Forms
<?
    echo ShowError($strError);
    echo ShowNote($strNote);

    $F_RIGHT = CAllForm::GetPermission($arrResult["FORM_ID"]);

?>
<br>
<table cellspacing="0" cellpadding="2">
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b>ID:</b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["ID"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_FORM_NAME")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?
        echo "[<a class='tablebodylink' href='form_edit.php?lang=".LANG."&ID=".$arrResult["FORM_ID"]."'>". $arrResult["FORM_ID"]."</a>] (".$arrResult["VARNAME"].") ".$arrResult["NAME"];
        ?></font></td>
    </tr>
    <?endif;?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_DATE_CREATE")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["DATE_CREATE"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_TIMESTAMP")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["TIMESTAMP_X"]?></font></td>
    </tr>
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_USER")?></b></font></td>
        <td valign="top" nowrap><font class="tablebodytext"><?
            if (intval($arrResult["USER_ID"])>0) :
                echo "<font class='tablebodytext'>[</font><a class='tablebodylink' title='".GetMessage("FORM_EDIT_USER")."' href='user_edit.php?lang=".LANG."&ID=".$arrResult["USER_ID"]."'>".$arrResult["USER_ID"]."</a><font class='tablebodytext'>] (".htmlspecialchars($arrResult["LOGIN"]).") ".htmlspecialchars($arrResult["USER_NAME"])."</font>";
                echo ($arrResult["USER_AUTH"]=="N") ? " <font class='filteroff'>".GetMessage("FORM_NOT_AUTH")."</font>" : "";
            else :
                echo "<font class='tablebodytext'>".GetMessage("FORM_NOT_REGISTERED")."</font>";
            endif;
            ?></font></td>
    </tr>
    <?if (CModule::IncludeModule("statistic")):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_GUEST")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_GUEST_ALT")?>" class="tablebodylink" href="/bitrix/admin/guest_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_GUEST_ID"]?>&set_filter=Y"><?=$arrResult["STAT_GUEST_ID"]?></a>]</font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_SESSION")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_SESSION_ALT")?>" class="tablebodylink" href="/bitrix/admin/session_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_SESSION_ID"]?>&set_filter=Y"><?=$arrResult["STAT_SESSION_ID"]?></a>]</font></td>
    </tr>
    <?endif;?>
    <?endif;?>
</table>
<br>
<?
    /*
    Y - show the required form fields in both filter and table;
    N - hide form fields
    */
    $SHOW_ADDITIONAL = "N";

    /*
    Y - show values of ANSWER_VALUE in round brackets
    N - do not show values of ANSWER_VALUE
    */
    $SHOW_ANSWER_VALUE = "N";

    CForm::ShowResult($RESULT_ID, $VIEW_TEMPLATE, "show", $SHOW_ADDITIONAL, $SHOW_ANSWER_VALUE);

else :
    echo ShowError("Form not found");
endif;
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


SetField

CFormResult::SetField

CFormResult::SetField(
 int RESULT_ID,
 varchar(255) FIELD_VARNAME,
 mixed VALUE
);

The method sets a new value of the form field result.

Parameters

Parameter | Description
RESULT_ID | Result ID.
FIELD_VARNAME | Form field symbolic identifier.
VALUE | New value to be set.

Example

The below example shows the sample file "form_fill.php" displaying the form.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (CModule::IncludeModule("form"))
{
    if (intval($WEB_FORM_ID)>0)
        $z = <b>CForm::GetByID</b>($WEB_FORM_ID);
    else
        $z = CForm::GetBySID($WEB_FORM_NAME);

    if (!($zr=$z->Fetch()))
    {
        $FORM_EXIST = "N";
        $strError .= "Invalid form ID.<br>";
    }
    else
    {
        $FORM_EXIST = "Y";
        $WEB_FORM_ID = $zr["ID"];
        $WEB_FORM_NAME = $zr["VARNAME"];
        if ($REQUEST_METHOD=="POST" &&
            intval($WEB_FORM_ID)>0 &&
            strlen($web_form_submit)>0)
        {
            $arrVALUES = $HTTP_POST_VARS;
            $error = CForm::Check($WEB_FORM_ID);
            if (strlen($error)<=0)
            {
                if ($RESULT_ID = CFormResult::Add($WEB_FORM_ID))
                {
                    $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
                    $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
                    CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
                    CForm::SetEvent($RESULT_ID);
                    CForm::Mail($RESULT_ID);
                    LocalRedirect("index.php?WEB_FORM_NAME=".$WEB_FORM_NAME. "&strNote=".urlencode("Information saved"));
                }
            }
            else
                $strError .= $error;
        }
    }
}

if (strlen($APPLICATION->GetTitle()) <= 0)
    $APPLICATION->SetTitle("Visitor survey");

require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
echo ShowNote($strNote);
echo ShowError($strError);
?><?
if (CModule::IncludeModule("form"))
    CForm::Show($WEB_FORM_NAME, $arrVALUES);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


Update

CFormResult::Update

CFormResult::Update(
 int WEB_FORM_ID,
 array arrVALUES=false,
 char(1) UPDATE_ADDITIONAL="N"
);

The method updates an existing result in the database.

Parameters

Parameter | Description
WEB_FORM_ID | Form ID.
arVALUES | Array of input values. In this parameter is false or not specified, it is taken from the array stored in $HTTP_POST_VARS. If $HTTP_POST_VARS is empty, it is taken from the array $HTTP_GET_VARS.
UPDATE_ADDITIONAL | If set to "Y", the method updates both questions and fields. Otherwise, questions only are affected.

Example

The following is an example of array $HTTP_POST_VARS passed to arrVALUES.

Array
(
    [form_text_586] => John Smith
    [form_date_587] => 10.03.1992
    [form_textarea_588] => London
    [form_radio_VS_MARRIED] => 589
    [form_checkbox_VS_INTEREST] => Array
        (
            [0] => 592
            [1] => 593
            [2] => 594
        )

    [form_dropdown_VS_AGE] => 597
    [form_multiselect_VS_EDUCATION] => Array
        (
            [0] => 603
            [1] => 604
        )

    [form_text_606] => 2345
    [form_image_607] => 1045
)

The below example shows the sample file "form_edit.php" allowing to edit the result.

<?
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/include.php");
include(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/form/admin/lang/",
                        "/form_result_edit.php"));
$RESULT_ID = intval($RESULT_ID);
$z = CFormResult::GetByID($RESULT_ID);
if (!($arrResult=$z->Fetch()))
{
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
    echo ShowError("Survey form not found");
    require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
    die();
}
$WEB_FORM_ID = intval($arrResult["FORM_ID"]);
$F_RIGHT = intval(CForm::GetPermission($WEB_FORM_ID));

/*
Y - allow to edit the form fields
N - do not allow to edit the form fields
*/
$EDIT_ADDITIONAL = "N";

if ($F_RIGHT>=25 || ($F_RIGHT>=15 && $USER->GetID()==$arrResult["USER_ID"])) :

    // "Save results" clicked
    if ($REQUEST_METHOD=="POST" &&
             intval($WEB_FORM_ID)>0 &&
             (strlen($web_form_submit)>0 || strlen($apply)>0))
    {
        // obtain the form data array
        $arrVALUES = $HTTP_POST_VARS;
        $error = CForm::Check($WEB_FORM_ID, $arrVALUES, $RESULT_ID);
        if (strlen($error)<=0)
        {
            CFormResult::Update($RESULT_ID, $arrVALUES, $EDIT_ADDITIONAL);
            $arr = CFormResult::GetDataByID($RESULT_ID, array("VS_PHOTO"));
            $PHOTO_EXIST = (intval($arr["VS_PHOTO"][0]["USER_FILE_ID"])>0) ? "Y" : "N";
            CFormResult::SetField($RESULT_ID, "VS_PHOTO_EXIST", $PHOTO_EXIST);
            if (strlen($web_form_submit)>0)
                LocalRedirect("index.php?WEB_FORM_NAME=".$arrResult["VARNAME"]);
        }
        else $strError .= $error;
    }
    else
    // obtain the data array from the database
        $arrVALUES = CFormResult::GetDataByIDForWeb($RESULT_ID,$EDIT_ADDITIONAL);
endif;

$title = str_replace("#RESULT_ID#","$RESULT_ID","Editing form # #RESULT_ID#");
$APPLICATION->SetTitle($title);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_after.php");
?>
<a href="index.php?WEB_FORM_NAME=<?=$arrResult["VARNAME"]?>" class="navchain">Forms</a>
<br><br>
<table cellspacing="0" cellpadding="2">
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b>ID:</b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["ID"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_FORM_NAME")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?
        echo "[<a class='tablebodylink' href='form_edit.php?lang=".LANG."&ID=".$WEB_FORM_ID."'>". $WEB_FORM_ID."</a>] (".$arrResult["VARNAME"].") ".$arrResult["NAME"];
        ?></font></td>
    </tr>
    <?endif;?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_DATE_CREATE")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["DATE_CREATE"]?></font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_TIMESTAMP")?></b></font></td>
        <td valign="top"><font class="tablebodytext"><?=$arrResult["TIMESTAMP_X"]?></font></td>
    </tr>
    <?if ($F_RIGHT>=25):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_USER")?></b></font></td>
        <td valign="top" nowrap><font class="tablebodytext"><?
            if (intval($arrResult["USER_ID"])>0) :
                echo "<font class='tablebodytext'>[</font><a class='tablebodylink' title='".GetMessage("FORM_EDIT_USER")."' href='user_edit.php?lang=".LANG."&ID=".$arrResult["USER_ID"]."'>".$arrResult["USER_ID"]."</a><font class='tablebodytext'>] (".htmlspecialchars($arrResult["LOGIN"]).") ".htmlspecialchars($arrResult["USER_NAME"])."</font>";
                echo ($arrResult["USER_AUTH"]=="N") ? " <font class='filteroff'>".GetMessage("FORM_NOT_AUTH")."</font>" : "";
            else :
                echo "<font class='tablebodytext'>".GetMessage("FORM_NOT_REGISTERED")."</font>";
            endif;
            ?></font></td>
    </tr>
    <?if (CModule::IncludeModule("statistic")):?>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_GUEST")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_GUEST_ALT")?>" class="tablebodylink" href="/bitrix/admin/guest_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_GUEST_ID"]?>&set_filter=Y"><?=$arrResult["STAT_GUEST_ID"]?></a>]</font></td>
    </tr>
    <tr>
        <td align="right" valign="top"><font class="tablebodytext"><b><?=GetMessage("FORM_SESSION")?></b></font></td>
        <td valign="top"><font class="tablebodytext">[<a title="<?=GetMessage("FORM_SESSION_ALT")?>" class="tablebodylink" href="/bitrix/admin/session_list.php?lang=<?=LANG?>&find_id=<?=$arrResult["STAT_SESSION_ID"]?>&set_filter=Y"><?=$arrResult["STAT_SESSION_ID"]?></a>]</font></td>
    </tr>
    <?endif;?>
    <?endif;?>
</table>
<br>
<?
CForm::EditResult($RESULT_ID, $arrVALUES, $EDIT_RESULT_TEMPLATE, $EDIT_ADDITIONAL);
require_once ($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog.php");
?>


CFormStatus

The CFormStatus class is used with statuses.

Fields

Field | Type | Description
ID | int | The status ID.
FORM_ID | int | The web form ID.
TIMESTAMP_X | datetime | The time the parameters of the status were last modified.
ACTIVE | char | Active state flag [Y|N].
C_SORT | int | Status sort weight.
TITLE | varchar(255) | Status title.
DESCRIPTION | varchar(2000) | Status description.
DEFAULT_VALUE | char | Flag indicating the result status is default [Y|N].
CSS | varchar(255) | Name of the CSS class to display the status title.
HANDLER_OUT | varchar(255) | Path relative to the root to the handler called when changing this result status to another.
HANDLER_IN | varchar(255) | Path relative to the root to the handler called when changing a result status to this.

Methods

Method | Description
Set | Adds a new status or modifies the existing one.
GetList | Returns a list of statuses of the specified web form.
GetByID | Returns the parameters of a status.
Copy | Copies a status.
Delete | Deletes a status.
GetPermissions | Returns an array of the current user permissions for the specified status.
GetPermissionList | Returns arrays containing user groups that have the specified permissions for the specified status.
GetDropdown | Returns a list of statuses in the format suitable to display a single selection drop-down list.


Copy

CFormStatus::Copy

mixed
CFormStatus::Copy(
 int status_id,
 string check_rights = "Y",
 mixed form_id = false
)

The method Copy copies a status. Returns the ID of the new status on success, or false otherwise.

Parameters

Parameter | Description
status_id | The ID of the status which is to be copied.
check_rights Flag specifying the current user permissions should be checked. One of the following values is possible:
  • Y - permissions should be checked;
  • N - no checks need to be performed.
A user must have the following permissions to copy a status:
  1. [25] view web form parameters for the source web form;
  2. [30] full access for the destination web form.
Optional. "Y" by default which means the permissions should be checked.
form_id The ID of the destination web form to which a status should be copied.
Optional. False by default which means that the current web form is used.

See Also

  • CForm::Copy
  • CFormField::Copy
  • CFormAnswer::Copy

Example

<?
$status_id = 1; // The status ID
// copy status
if ($NEW_STATUS_ID = CFormStatus::Copy($status_id))
{
    echo "The status #1 has been successfully copied to the new status #".$NEW_STATUS_ID;
}
else
{
    // display the error description
    global $strError;
    echo $strError;
}
?>


Delete

CFormStatus::Delete

bool
CFormStatus::Delete(
 int status_id,
 string check_rights = "Y"
)

The method Delete deletes a status. Returns true on success, or false otherwise.

Note!
Statuses containing at least one result can not be deleted.

Parameters

Parameter | Description
status_id | The ID of the status to be deleted.
check_rights Flag specifying the current user permissions should be checked. One of the following values is possible:
  • Y - permissions should be checked;
  • N - no checks need to be performed.
For this method to succeed, you should have the permission [30] full access for the destination web form containing the field status_id.
Optional. "Y" by default which means the permissions should be checked.

See Also

  • CForm::Delete
  • CFormField::Delete
  • CFormAnswer::Delete
  • CFormResult::Delete

Example

<?
$status_id = 1; // The status ID
// delete the status
if (CFormStatus::Delete($status_id))
{
    echo "The status #1 has been deleted.";
}
else
{
    // display the error description
    global $strError;
    echo $strError;
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


GetByID

CFormStatus::GetByID

CDBResult
CFormStatus::GetByID(
 int status_id
)

The method GetByID returns the parameters of a status as a CDBResult instance.

Parameters

status_id The status ID.

See Also

  • CFormStatus fields
  • CFormStatus::GetList

Example

<?
$status_id = 1; // The status ID
$rsStatus = CFormStatus::GetByID($status_id);
$arStatus = $rsStatus->Fetch();
echo "<pre>"; print_r($arStatus); echo "</pre";
?>


GetDropDown

CFormStatus::GetDropDown

CDBResult
CFormStatus::GetDropDown(
 int form_id,
 array permission = array("MOVE"),
 int owner_user_id = 0
)

The method GetDropDown returns a list of statuses as a CDBResult instance in the format suitable to display a single selection drop-down list.

The resulting list will contain statuses of the specified web form form_id. A status will be included in the resulting list only if the current user has at least one of the permissions specified in the parameter permission.

Parameters

Parameter | Description
form_id | The web form ID.
permission Array of permissions one of which the current user must have. The following values are possible in this array:
  • VIEW - view permission;
  • MOVE - permission to change status;
  • EDIT - edit permission;
  • DELETE - delete permission.
Optional. Array("MOVE") by default which means the current user must have the permission to change the result status.
owner_user_id If the method is used to build a drop-down list of available statuses of the specified result, pass the ID of the user that created the result in this parameter (result owner, result field is USER_ID).

Optional. 0 by default.

See Also

  • Permissions for the result

Example

<?
$FORM_ID = 4; // The web form ID

// obtain the list of all the available statuses
// the current user has the permission to view
$rsStatuses = CFormStatus::GetDropdown($FORM_ID, array("VIEW"));

// display the drop-down list
echo SelectBox("STATUS_ID", $rsStatuses, "(select status)", htmlspecialchars($STATUS_ID));
?>


GetList

CFormStatus::GetList

CDBResult
CFormStatus::GetList(
 int form_id,
 string &by = "s_sort",
 string &order = "asc",
 array filter = array(),
 bool &is_filtered
)

The method GetList returns a list of statuses as a CDBResult instance.

Parameters

form_id | The web form ID.
by Reference to the variable containing the field used to sort the result list. The following values are possible:
  • s_id - the status ID;
  • s_sort - sort index;
  • s_timestamp - the time the status was last modified;
  • s_active - active state flag;
  • s_default - flag indicating the status is default;
  • s_title - title;
  • s_description - description;
  • s_results - number of results in this status.
order Reference to the variable containing the sort order. The following values are possible:
  • asc - ascending;
  • desc - descending.
filter An array used to filter values. The following keys are possible:
  • ID* - the status ID (by default the method accepts only the exact matches);
  • ID_EXACT_MATCH - if "N", the method performs loose searches (entry is sufficient) when filtering by ID;
  • ACTIVE - active state flag. The following values are possible:
    • Y - status is active;
    • N - status is inactive.
  • TITLE* - status title (the method performs loose searches by default);
  • TITLE_EXACT_MATCH - set to "Y" for exact match searches when filtering by TITLE;
  • DESCRIPTION* - status description (the method performs loose searches by default);
  • DESCRIPTION_EXACT_MATCH - set to "Y" for exact match searches when filtering by DESCRIPTION.
* - complex logic allowed
is_filtered | Reference to the variable containing true if the returned list is filtered, or false if the returned list is not filtered.

See Also

  • CFormStatus fields
  • CFormStatus::GetByID

Example

<?
$FORM_ID = 4; // The web form ID

// build the filter array
$arFilter = Array(
    "ID"                       => "1 | 4",           // status ID=1 or ID=4
    "ID_EXACT_MATCH"           => "Y",               // we need the ID to match exactly
    "ACTIVE"                   => "Y",               // active state flag
    "TITLE"                    => "published",       // title
    "TITLE_EXACT_MATCH"        => "N",               // we need the TITLE to match exactly
    "DESCRIPTION"              => "final status",    // description
    "DESCRIPTION_EXACT_MATCH"  => "N",               // we need the DESCRIPTION to match exactly
);

// obtain the list of all answers to the question #143
$rsStatuses = CFormStatus::GetList(
    $FORM_ID,
    $by="s_id",
    $order="desc",
    $arFilter,
    $is_filtered
    );
while ($arStatus = $rsStatuses->Fetch())
{
    echo "<pre>"; print_r($arStatus); echo "</pre>";
}
?>


GetPermissionList

CFormStatus::GetPermissionList

CFormStatus::GetPermissionList(
 int status_id,
 array &can_view,
 array &can_move,
 array &can_edit,
 array &can_delete
)

The method GetPermissionList returns arrays containing user groups that have the specified permissions for the specified status.

Parameters

Parameter | Description
status_id | The status ID.
can_view | Reference to an array containing the ID's of user groups that have the permission to view the result in the status status_id.
can_move | Reference to an array containing the ID's of user groups that have the permission to change the results to the status status_id.
can_edit | Reference to an array containing the ID's of user groups that have the permission to edit the results in the status status_id.
can_delete | Reference to an array containing the ID's of user groups that have the permission to delete the results in the status status_id.

See Also

  • Permissions for the result
  • CForm::GetPermission
  • CFormResult::GetPermissions

Example

<?
$STATUS_ID = 1;

// obtain an array of the groups that have the specified permissions for the status #1
CFormStatus::GetPermissionList($STATUS_ID, $arVIEW, $arMOVE, $arEDIT, $arDELETE);

// display an array of the groups that have the permission
// to view the result in the status #1
echo "<pre>"; print_r($arVIEW); echo "</pre>";

// display an array of the groups that have the permission
// change the results to the status #1
echo "<pre>"; print_r($arMOVE); echo "</pre>";

// display an array of the groups that have the permission
// to edit the results in the status #1
echo "<pre>"; print_r($arEDIT); echo "</pre>";

// display an array of the groups that have the permission
// to delete the results in the status #1
echo "<pre>"; print_r($arDELETE); echo "</pre>";

?>


GetPermissions

CFormStatus::GetPermissions

array
CFormStatus::GetPermissions(
 int status_id
)

The method GetPermissions returns an array of the current user permissions for the specified status. The following values are possible in this array:

  • VIEW - permission to view the results in this status;
  • MOVE - permission to change the results to this status;
  • EDIT - permission to edit the results in this status;
  • DELETE - permission to delete the results in this status.

Parameters

Parameter | Description
status_id | The status ID.

See Also

  • Permissions for the result
  • CForm::GetPermission
  • CFormResult::GetPermissions

Example

<?
$STATUS_ID = 1;

// obtain the current user permissions for the specified status
$arPerm = CFormStatus::GetPermissions($STATUS_ID);

if (in_array("VIEW", $arPerm))
    echo "You can view the results in this status";

if (in_array("EDIT", $arPerm))
    echo "You can edit the results in this status";

if (in_array("MOVE", $arPerm))
    echo "You can assign this status to a result";

if (in_array("DELETE", $arPerm))
    echo "You can delete the results in this status";
?>


Set

CFormStatus::Set

mixed
CFormStatus::Set(
 array fields,
 mixed status_id = false,
 string check_rights = "Y"
)

The method Set adds a new status or modifies the existing one. Returns the ID of the modified or added status on success, or false otherwise.

Parameters

Parameter Description
fields Array of values which accept the following keys:
  • FORM_ID* - the web form ID;
  • TITLE* - status title;
  • C_SORT - sort order;
  • ACTIVE - active state flag. The following values are possible:
    • Y - the answer is active;
    • N - the answer is inactive (by default).
  • DESCRIPTION - status description;
  • CSS - name of the CSS class to display the status title;
  • HANDLER_OUT - path relative to the root to the handler called when changing this result status to another;
  • HANDLER_IN - path relative to the root to the handler called when changing a result status to this;
  • DEFAULT_VALUE - flag indicating the status is default. The following values are possible:
    • Y - status is default;
    • N - status is not default (by default).
  • arPERMISSION_VIEW* - array containing the ID's of user groups having the permission "View results in this status";
  • arPERMISSION_MOVE* - array containing the ID's of user groups having the permission "Change results to this status";
  • arPERMISSION_EDIT* - array containing the ID's of user groups having the permission "Edit results in this status";
  • arPERMISSION_DELETE* - array containing the ID's of user groups having the permission "Delete results in this status".

* - required.
* - these arrays may have values of "0"which means the result creator.
status_id The ID of the modified status.
Optional. False by default (adds a new status).
check_rights Flag specifying the current user permissions should be checked. One of the following values is possible:
  • Y - permissions should be checked;
  • N - no checks need to be performed.
To modify a status or create a new one, you should have the permission [30] Full access for the form specified in fields["FORM_ID"].

Optional. "Y" by default which means the permissions should be checked.

See Also

  • CFormStatus fields

Example

<?
$FORM_ID = 4; // The web form ID

$arFields = array(
    "FORM_ID"             => $FORM_ID,               // The web form ID
    "C_SORT"              => 100,                    // sort order
    "ACTIVE"              => "Y",                    // status is active
    "TITLE"               => "Published",            // status title
    "DESCRIPTION"         => "Final status",         // status description
    "CSS"                 => "statusgreen",          // CSS class
    "HANDLER_OUT"         => "",                     // handler
    "HANDLER_IN"          => "",                     // handler
    "DEFAULT_VALUE"       => "N",                    // not default
    "arPERMISSION_VIEW"   => array(2),               // view permission for all
    "arPERMISSION_MOVE"   => array(),                // move permission for admins only
    "arPERMISSION_EDIT"   => array(),                // edit permission for admins
    "arPERMISSION_DELETE" => array(),                // delete permission for admins only
);

$NEW_ID = CFormStatus::Set($arFields);
if ($NEW_ID>0) echo "The ID=".$NEW_ID has been added;
else // error
{
    // display the error description
    global $strError;
    echo $strError;
}
?>


CFormValidator

The CFormValidator class is used with validators.

Methods

Method | Description
Clear | Clears the list of validators assigned to a question.
Execute | Applies the validator to a value.
GetAllList | Returns the full list (optionally filtered) of registered validators.
GetList | Returns the list of validators assigned to a question.
GetListForm | Returns the list of validators assigned to form fields.
GetSettings | Returns an array of validator parameters.
GetSettingsArray | Returns an array of validator settings applied to a certain question.
GetSettingsString | Returns a string of validator settings to be stored in the database.
Set | Attaches a validator with the specified settings to a question.
SetBatch | Attaches a set of validators with the specified settings to a question.
© 2001-2007 Bitrix Bitrix Site Manager


Clear

CFormValidator::Clear

CFormValidator::Clear(
 int FIELD_ID,
)

The method Clear removes all validators assigned to this question/field/.

Parameters

Parameter | Description
FIELD_ID | The field ID.
© 2001-2007 Bitrix Bitrix Site Manager


Execute

CFormValidator::Execute

bool
CFormValidator::Execute(
 array arValidator,
 array arQuestion,
 array arAnswers,
 array arValues,
)

The method Execute executes validator for specified answer values when applied to a question.

Parameters

Parameter | Description
arValidator Validator description array; one of the array elements obtained by CFormValidator::GetList. Contains the following parameters:
  • NAME - the validator identifier;
  • PARAMS - an array of values of validator settings.
arQuestion | The question description. The parameter is not used in validators shipped with the product, but can be used in custom validators.
arAnswers | Array containing descriptions of answers. The parameter is not used in validators shipped with the product, but can be used in custom validators.
arValues | An array of answers to a question in the format array('value1', 'value2', .... 'value n').
&reset; 2001-2007 Bitrix Bitrix Site Manager


GetAllList

CFormValidator::GetAllList

CDBResult
CFormValidator::GetAllList(
 mixed arFilter = array(),
)

The method GetAllList returns a list of registered validators as a CDBResult object.

Parameters

Parameter Description
arFilter Filtering array. The following keys are possible:
  • TYPE - list of field types

Example

if (CModule::IncludeModule("form"))
{
  $arFilter = array("TYPE" => array("text", "textarea"));

  $sType = "<b>".implode("</b>, <b>", $arFilter["TYPE"])."</b>";

  $rsValidators = CFormValidator::GetAllList($arFilter);
  if ($rsValidators->SelectedRowsCount() > 0)
  {
    echo "Found validators for fields ".$sType.":<ul>";
    while ($arValidator = $rsValidators->GetNext())
    {
      echo "<li>[".$arValidator["NAME"]."] ".$arValidator["DESCRIPTION"]."</li>";
    }
    echo "</ul>";
  }
  else
  {
    echo "Validators applicable to fields ".$sType." are not found.";
  }
}
else
{
  ShowError('The Web forms module is not installed');
}
© 2001-2007 Bitrix Bitrix Site Manager


GetList

CFormValidator::GetList

CDBResult
CFormValidator::GetList(
 int FIELD_ID,
 mixed arFilter = array(),
 string &by = "s_sort",
 string &order = "asc",
)

The method GetList returns a list of validators for the specified field as a CDBResult object.

Parameters

Parameter | Description
FIELD_ID | The question ID.
arFilter Filtering array. The following keys are possible:
  • ACTIVE - the validator active state flag;
  • NAME - the validator identifier.
by Reference to the variable containing the name of a field by which the list is to be sorted. The following values are possible:
  • VALIDATOR_SID - the validator ID;
  • C_SORT - sorting index.
оrder Reference to the variable containing the sorting order. The following values are possible:
  • asc - ascending;
  • desc - descending.
© 2001-2007 Bitrix Bitrix Site Manager


GetListForm

CFormValidator::GetListForm

CDBResult
CFormValidator::GetListForm(
 int FORM_ID,
 mixed arFilter = array(),
 string &by = "s_sort",
 string &order = "asc",
)

The method GetListForm returns a list of validators for fields of the specified form as a CDBResult object.

Parameters

Parameter | Description
FORM_ID | The web form ID.
arFilter Filtering array. The following keys are possible:
  • FIELD_ID - the question ID;
  • ACTIVE - the validator active state flag;
  • NAME - the validator identifier.
by Reference to a variable containing the name of a field by which the list is to be sorted. The following values are possible:
  • VALIDATOR_SID - the validator ID;
  • C_SORT - sorting index.
оrder Reference to a variable containing the sorting order. The following values are possible:
  • asc - ascending;
  • desc - descending.
© 2001-2007 Bitrix Bitrix Site Manager


GetSettings

CFormValidator::GetSettings

array
CFormValidator::GetSettings(
 array arValidator,
)

The method GetSettings returns a list of validator settings. The method is similar to calling the validator settings method directly.

Parameters

Parameter | Description
arValidator | An array describing the validator (obtained, for instance, by calling CFormValidators::GetAllList).
© 2001-2007 Bitrix Bitrix Site Manager


GetSettingsArray

CFormValidator::GetSettingsArray

array
CFormValidator::GetSettingsArray(
 array arValidator,
 string strParams
)

The method GetSettingsArray returns validator settings as a list of values converted from strings fetched from the database. The method is similar to calling the validator conversion routine (CONVERT_FROM_DB) directly. CFormValidator::GetList and CFormValidator::GetListForm call this method automatically.

Parameters

Parameter | Description
arValidator | An array describing the validator (obtained, for instance, by calling CFormValidators::GetList).
strParams | A string with the settings stored in the database.
© 2001-2007 Bitrix Bitrix Site Manager


GetSettingsString

CFormValidator::GetSettingsString

string
CFormValidator::GetSettingsString(
 array arValidator,
 array arParams
)

The method GetSettingsString returns a list of validator settings values sutable for enrolling in the database. The method is similar to calling the validator settings conversion routine (CONVERT_TO_DB) directly. It is called automatically when CFormValidator::Set and CFormValidator::SetBatch are called.

Parameters

Parameter | Description
arValidator | An array describing the validator (obtained, for instance, by calling CFormValidators::GetList).
arParams | An array of validator settings.
© 2001-2007 Bitrix Bitrix Site Manager


Set

CFormValidator::Set

bool
CFormValidator::Set(
 int WEB_FORM_ID,
 int FIELD_ID,
 string VALIDATOR_SID,
 array arParams = array(),
)

The method Set attaches a validator with the specified settings to a form field. Returns true on success, or false otherwise (if there is no validator with the ID specified, error in validator etc.).

Parameters

Parameter | Description
WEB_FORM_ID | The web form ID.
FIELD_ID | The question ID.
VALIDATOR_SID | The validator identifier.
arParams | An array containing the validator parameters.
© 2001-2007 Bitrix Bitrix Site Manager


SetBatch

CFormValidator::SetBatch

CFormValidator::SetBatch(
 int WEB_FORM_ID,
 int FIELD_ID,
 array arValidators = array(),
)

The method SetBatch attaches a group of validators with specified settings to a form field. The method is similar to calling the CFormValidator::Set for each validator.

Parameters

Parameter | Description
WEB_FORM_ID | The web form ID.
FIELD_ID | The question ID.
arValidators An array of validators. Each array element is an associated array with the following keys:
  • NAME - the validator identifier;
  • PARAMS - an array of validator parameters.
© 2001-2007 Bitrix Bitrix Site Manager


Классы модуля Web Service

Classes

The following PHP classes are used to implement web services in components.

Classes

Class | Description
CWebServiceDesc | This structure describes methods and types of web services.
IWebService | The web service interface used for registration in CWebService.
CWebService | A web service manager.

The following PHP classes implement SOAP protocol, WSDL, XML generation in the webservice module.

Implemented classes

Class | Description
CXMLCreator | This class is used to generate XML.
CSOAPFault | Processes the SOAP server's and client's errors.
CSOAPRequest | Builds a SOAP request/envelope.
CSOAPServerResponser | This interface is used to implement custom handlers of SOAP requests.
CSOAPServer | Implements a SOAP server.
CSOAPClient | Implements a SOAP client.
CWSDLCreator | Used for automated generation of WSDL for a web service. Document/literal binding only.
CSOAPCodec | Transforms data to XML according to the web service specification.
CSOAPResponse | Creates and processes SOAP responses.
CWSSOAPResponser | Processes requests to web services via SOAP. Inherits from CSOAPServerResponser.

Abstract classes

Class | Description
CSOAPHeader | Abstract class used for processing of a SOAP packet.
CSOAPBody | Abstract class used for processing of a SOAP packet.
CSOAPEnvelope | Abstract class used for processing of a SOAP packet.
© 2001-2007 Bitrix Bitrix Site Manager


CSOAPClient

Methods

Method | Description
CSOAPClient | Constructor. Configures a SOAP client to use a specific server ($server), SOAP server access point ($path = '/'), web server port ($port).
send | Sends a SOAP request created by CSOAPRequest.
setTimeout | Sets the response waiting period of a SOAP server.
getRawRequest | Returns a string which is a request sent to a SOAP server.
getRawResponse | Returns a string which is a response obtained from a SOAP server.
setLogin | Sets the SOAP request login for authorisation via HTTP Basic.
setPassword | Sets the SOAP request password for authorisation via HTTP Basic.
login | Returns the previously set login.
password | Returns the previously set password.

Example 1 (internal test)

function TestComponent()
{
    global $APPLICATION;
    $client = new CSOAPClient( "bitrix.soap", $APPLICATION->GetCurPage() );
    $request = new CSOAPRequest( "wsTestStartOut1", "http://bitrix.soap/" );
    $request->addParameter("str1", "qwe");
    $request->addParameter("str2", "fjdfhgfdh");
    $request->addParameter("int3", "123");
    $response = $client->send( $request );
    echo "Call wsTestStartOut1";
    if ( $response->isFault() )
    {
        print( "SOAP fault: " . $response->faultCode(). " - " . $response->faultString() . "" );
    }
    else
        echo "[OK]: ".mydump($response->Value);
}

Example 2 (external test)

function TestComponent()
{
    $client = new CSOAPClient("ws.strikeiron.com", "/relauto/iplookup/DNS");
    $request = new CSOAPRequest( "DNSLookup", "http://tempuri.org/");
    $request->addSOAPHeader( "LicenseInfo xmlns=\"http://ws.strikeiron.com\"",
            array("UnregisteredUser" => array( "EmailAddress" => "qwerty@mail.ru" ))
        );
    $request->addParameter("server", "www.yandex.ru");
    $response = $client->send( $request );

    echo "SOAPRequest: ".htmlspecialchars($client->getRawRequest());
    echo "SOAPResponse: ".htmlspecialchars($client->getRawResponse());
}
© 2001-2007 Bitrix Bitrix Site Manager


CSOAPFault

Members

Parameter | Description
$FaultCode | Contains the SOAP error code.
$FaultString | Contains the SOAP error description in human-readable format.

CSOAPFault constructor

CSOAPFault::CSOAPFault(
    string faultCode = "",
    string faultString = ""
)

Notes

An instance of CSOAPFault is usually passed to the ShowResponse method of a SOAP server, which passes it to CSOAPResponse::payload. The latter can distinguish the type of a response value: an error (a CSOAPFault instance), or the data type. This allows to add SOAP server errors (CSOAPFault) to a server response appropriately. All other data types are strictly encoded according to the web service data type specification, or using CXMLCreator::encodeValueLight.

Example

// Fragment of a SOAP server web service handler
$this->ShowResponse( $cserver, $functionName, $namespaceURI,
    new CSOAPFault(
        'Server Error',
        'Method not found'
    ) );
© 2001-2007 Bitrix Bitrix Site Manager


CSOAPRequest

Methods

Method | Description
CSOAPRequest | A standard constructor.
addSOAPHeader | Adds a named value to a SOAP request.
addBodyAttribute | Adds a specified attribute to the body tag of a SOAP request.
addParameter | Adds data to be passed in a SOAP request. For a web service, the data are the method parameters.
payload | Returns a built SOAP request as a string.

Example

// Create a request to a web service "ws.strikeiron.com/relauto/iplookup/DNS"

$request = new CSOAPRequest( "DNSLookup", "http://tempuri.org/");
    $request->addSOAPHeader( "LicenseInfo xmlns=\"http://ws.strikeiron.com\"",
            array("UnregisteredUser" => array( "EmailAddress" => "qwerty@mail.ru" ))
        );
    $request->addParameter("server", "www.yandex.ru");
© 2001-2007 Bitrix Bitrix Site Manager


CSOAPRequest::CSOAPRequest

CSOAPRequest::CSOAPRequest(
    string name = "",
    string namespace = "",
    array  parameters = array()
);

A standard constructor.

Parameters

Parameter | Description
name | The name of a message in a request.
namespace | The request namespace.
parameters | Request parameters in the format array("parameter name" => "value"). The value can be specified in the same format as in the addParameter method.

Example

// Call the web service method "DNSLookup"
$request = new CSOAPRequest( "DNSLookup", "http://tempuri.org/");
© 2001-2007 Bitrix Bitrix Site Manager


addParameter

CSOAPRequest::addParameter

void
CSOAPRequest::addParameter(
    string name,
        ЛюбойТипДанных value
)

The method addParameter adds parametrized data to be passed in a SOAP request. Those are parameters for a web service.

Parameters

Parameter | Description
name | The name of a parameter.
value | Associated array describing the message contents in the request header. See CXMLCreator::encodeValueLight.

Example

// An example of creating a request to call a web servicу from webservice.wsdl.phpt
$request = new CSOAPRequest( "wsTestStart4", "http://bitrix.soap/" );
$request->addParameter("str1", "qwe");
$request->addParameter("str2", array(
    "1:ArrayOfsGenTestXEl" => array(
        "id" => "123",
        "name" => "qwe",
        "testa" => array(
                "1:ArrayOfsGenLiteEl" => array("id" => "56", "name" => "asd"),
                "2:ArrayOfsGenLiteEl" => array("id" => "13", "name" => "fjhg")
                )
    ),
    "2:ArrayOfsGenTestXEl" => array(
        "id" => "7653",
        "name" => "dfgsdf DASD",
        "testa" => array(
                "1:ArrayOfsGenLiteEl" => array("id" => "78", "name" => "ty"),
                "2:ArrayOfsGenLiteEl" => array("id" => "99", "name" => "3425rte")
            )
    )
));
© 2001-2007 Bitrix Bitrix Site Manager


addSOAPHeader

CSOAPRequest::addSOAPHeader

void
CSOAPRequest::addSOAPHeader(
    string name,
    AnyDataType value
)

The method addSOAPHeader adds a named value to a SOAP request.

Parameters

Parameter | Description
name | The name of a message in the SOAP request header.
value | Associated array describing the message contents in the request header. See CXMLCreator::encodeValueLight.

Example

$request->addSOAPHeader(
    "LicenseInfo xmlns=\"http://ws.strikeiron.com\"",
    array(
        "UnregisteredUser" => array( "EmailAddress" => "qwerty@mail.ru" ))
    );
© 2001-2007 Bitrix Bitrix Site Manager


addBodyAttribute

CSOAPRequest::addBodyAttribute

void
CSOAPRequest::addBodyAttribute(
    string name,
    string value
)

The method addBodyAttribute adds an attribute to the body tag of a SOAP request.

Parameters

Parameter | Description
name | The name of an attribute to be added.
value | The value of an attribute.
© 2001-2007 Bitrix Bitrix Site Manager


CSOAPServer

Methods

Method | Description
GetRequestData | Returns the received SOAP request.
GetResponseData | Returns the SOAP packet sent in response to a request. GetResponseData can only be used after calling ProcessRequest.
boolean AddServerResponser( CSOAPServerResponser &respobject ) | Registers the SOAP request handler. Handlers that inherit from CSOAPServerResponser must be registered prior to calling ProcessRequest.
ShowRawResponse | Creates and sends a SOAP response packet containing data as CXMLCreator.
ShowResponse | Creates and sends a SOAP response packet containing the converted data.
ShowSOAPFault | Creates and sends a SOAP error response packet.
ProcessRequest | Performs SOAP request processing. Handlers (CSOAPServerResponser) must be registered using AddServerResponser before calling this method. Returns true on success, or false otherwise.
stripHTTPHeader | Removes the HTTP header from an XML document.

Example

In this example, $arParams["SOAPSERVER_RESPONSER"] contains SOAP handlers.

Usually, a SOAP handler is created in a component and saved to an array $arParams["SOAPSERVER_RESPONSER"]. Then, after the webservice.server component becomes active, the following code is executed.

// In a component

// Create a handler instance
$research =& new CMSSOAPResearch();

// Set the handler parameters
$research->provider_id = '{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}';
$research->service_id = '{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}';
$research->add_tittle = "";
$research->query_path = "http://{$_SERVER[HTTP_HOST]}/ws/wscauth.php";
$research->registration_path = "http://{$_SERVER[HTTP_HOST]}/ws/wscauth.php";

// Store the handler to be passed to webservice.server
$arParams["SOAPSERVER_RESPONSER"] = array( &$research );

.........

// In "webservice.server"
$server = new CSOAPServer();

for ($i = 0; $i<count($arParams["SOAPSERVER_RESPONSER"]); $i++)
{
    $server->AddServerResponser($arParams["SOAPSERVER_RESPONSER"][$i]);
}

$result = $server->ProcessRequest();
© 2001-2007 Bitrix Bitrix Site Manager


CSOAPServerResponser

Methods

Method | Description
void OnBeforeRequest( CSOAPServer &cserver ) | Called on all CSOAPServerResponser based handers registered in a SOAP server when an event fires: after a request has been received but before it is decoded.
void OnAfterResponse( CSOAPServer &cserver ) | Called on all CSOAPServerResponser based handers when an event fires: after a request has been processed and a response has been sent(ProcessRequestBody returned true).
boolean ProcessRequestBody( CSOAPServer &cserver, CDataXMLNode body ) | Processes a SOAP server request. If the method has processed a request and called ShowResponse, it returns true. Otherwise, it returns false and the system calls methods ProcessRequestBody of other handlers until the current callee returns true or there is no more handlers to call.

Parameters of methods

Parameter | Description
cserver | Reference to an instance of CSOAPServer that handles a SOAP request.
body | A piece of an XML query following the body tag as CDataXMLNode.

Example

class CMSSOAPResearch extends CSOAPServerResponser
{
    var $provider_id;
    var $service_id;
    var $add_tittle;
    var $query_path;
    var $registration_path;

    function OnBeforeRequest(&$cserver)
    {
        AddMessage2Log(mydump($cserver->GetRequestData()));
    }

    function ProcessRequestBody(&$cserver, $body)
    {
        $functionName = $body->name();
        $namespaceURI = $body->namespaceURI();
        $requestNode = $body;

        if ($functionName == "Registration")
        {
            $root = new CXMLCreator("RegistrationResponse");
            $root->setAttribute("xmlns", "urn:Microsoft.Search");

            $regres = new CXMLCreator("RegistrationResult");
            $root->addChild($regres);

            $prup = new CXMLCreator("ProviderUpdate");
            $prup->setAttribute("xmlns", "urn:Microsoft.Search.Registration.Response");
            $prup->setAttribute("revision", "1");
            $prup->setAttribute("build", "1");
            $regres->addChild($prup);

            $stat = new CXMLCreator("Status");
            $stat->setData("SUCCESS");
            $prup->addChild($stat);

            $providers = array(

                "Provider" => array (
                    "Message" => "Oanoiaay neo?aa.",
                    "Id" => "{$this->provider_id}",
                    "Name" => "Oanoiaay neo?aa. {$this->add_tittle}",
                    "QueryPath" => $this->query_path,
                    "RegistrationPath" => $this->registration_path,
                    "AboutPath" => "http://www.bitrix.ru/",
                    "Type" => "SOAP",
                    "Revision" => "1",
                    "Services" => array(
                        "Service" => array(
                            "Id" => "{$this->service_id}",
                            "Name" => "Test service. {$this->add_tittle}",
                            "Description" => "SOAP server test service.",
                            "Copyright" => "(c) Bitrix.",
                            "Display" => "On",
                            "Category" => "ECOMMERCE_GENERAL",
                            "Parental" => "Unsupported",
                        )
                    )
                )

            );

            $providersEncoded = CSOAPRequest::encodeValueLight("Providers", $providers);
            $prup->addChild($providersEncoded);

            $cserver->ShowRawResponse($root, true);

            AddMessage2Log($cserver->GetResponseData());

            return true;
        }

        return false;
    }
}
© 2001-2007 Bitrix Bitrix Site Manager


CWebService

Class methods

Method | Description
SetComponentContext | Stores the component configuration context ($arParams), to be passed to a web service method calling context.
GetComponentContext | Returns the component configuration context ($arParams) of a web service. Can be called from CWebService::GetComponentContext.
SOAPServerProcessRequest | Calls the SOAP server handler to process an incoming POST request. The handler is called on a web server instance specified in the method parameters.
RegisterWebService | Registers the specified web service.
GetSOAPServerRequest | Returns a SOAP request (string) received by a SOAP server.
GetSOAPServerResponse | Returns a response (string) of a SOAP server.
MethodRequireHTTPAuth | Verifies whether the HTTP Basic authorisation is passed. Used for methods that require authorisation.
TestComponent | Calls IWebService::TestComponent of a registered web service being queried.
GetWSDL | Returns the automatically generated WSDL code (if CWebServiceDesc->wsdlauto is true).
GetDefaultEndpoint | Returns an access point (e.g. http://site.com/ws.php) for the default web service.
GetDefaultTargetNS | Returns a namespace for the default web service.
GetWebServiceDeclaration | Returns an instance of CWebServiceDesc via IWebService.
GetInterface | Returns an instance of the web service class that implements IWebService.
© 2001-2007 Bitrix Bitrix Site Manager


RegisterWebService

CWebService::RegisterWebService

boolean
CWebService::RegisterWebService(string className);

The method RegisterWebService registers the specified web service. Returns true on success or false otherwise.

If a web service is implemented using components, RegisterWebService is called automatically in webservice.server. In this case, className = $arParams["WEBSERVICE_NAME"].

Parameters

Parameter | Description
className | The name of a web service class that implements IWebService.

Example

// In webservice.server
CWebService::RegisterWebService($arParams["WEBSERVICE_CLASS"]);

// In the web service component
$arParams["WEBSERVICE_NAME"] = "bitrix.webservice.checkauth";
// The following parameter is passed directly to SOAPServerProcessRequest
$arParams["WEBSERVICE_CLASS"] = "CCheckAuthWS";
$arParams["WEBSERVICE_MODULE"] = "";
$APPLICATION->IncludeComponent(
    "bitrix:webservice.server",
    "",
    $arParams
    );
© 2001-2007 Bitrix Bitrix Site Manager


CWebServiceDesc

Web service diagram

CWebServiceDesc members

Parameter | Type | Description
wsname | string | The name of a web service (e.g. bitrix.ws.users).
wsclassname | string | The class that implements a web service and IWebService.
wsdlauto | boolean | Specifies whether the WSDL code is to be generated automatically.
wstargetns | string | A namespace (e.g. http://bitrix.ru/)
wsendpoint | string | A web service access point (e.g. http://bitrix.ru/ws/testws.php).
classes | array | An array describing the web service methods.
structTypes | array | An array describing complex data types (structures) of a web service.
classTypes | array | Describes complex types of data deserialized from XML to class instances.

The CWebServiceDesc class (web service descriptor) must be fully initialized. This class is returned by IWebService::GetWebServiceDesc. After the web service descriptor has been registered, instances of a SOAP server and a WSDL generator are created in it.

Web service methods

Web service methods always:

  • belong to a class that implements a web service;
  • fully describe both input and output parameters;
  • maintain types of input and output parameters according to their description.

Data types

Web server methods can use the following data types:

  • Simple types: string, bool, boolean, int, integer, double, float, number;
  • Complex types: arrays, structures (can be serialized to associated arrays), classes (can be serialized to class instances). They can be described using structTypes, classTypes.

Data types are defined in the following sections of CWebServiceDesc:

  • classes - arrays as method parameters (see Web Service Classes);
  • structTypes - structures;
  • classTypes - classes.

Web service description

If WSDL is generated automatically, Document/Literal binding is also generated. A SOAP server can support only Document/Literal binding. The XSD schema is generated for all types and parameters.

Parameter Description
classes This class member must be initialized. It defines web service methods via the class, input and output parameters. Arrays (as complex data types) can be used if attributes arrType and varType are specified. A corresponding data type is automatically created in the XSD shema.

Associated array:
$wsdesc->classes = array(
    "web service class with methods" => array(
        "web service method" => array(
            // method is public
            "type"        => "public",
            "name"        => "web service method",
            // method parameters
            // "strict" => "no" means the parameter is not required;
            // and can be omitted in a soap request.
            "input"        => array(
                // "DataType" - name of a complex or simple data type
                "ParameterName" =>array("varType" => "DataType"[, "strict" => "no"]),

                // Array parameters:
                // varType - array name (data type for xsd schema)
                // arrType - array element typeа
                "ParameterName" =>array("varType" => "ArrayOf"."DataType",
                                        "arrType" => "DataType"),

                // Example of complex data types.
                // Complex types must be defined in structTypes, classTypes
                "ParameterName" =>array("varType" => "sGenTest"),

                // Example of passing complex array
                "ParameterName" =>array("varType" => "ArrayOfSGenTest",
                                        "arrType" => "sGenTest")
            ...
            // Output parameeters
            "output"    => array(
                // only one output parameter can be defined
                "user" => array("varType" => "DataType")
            ),
            // whether HTTP Basic authorisation is required.
            "httpauth" => "Y или N"
        ), ...
    ), ...
);
structTypes Defines structured data types (associated arrays in PHP; structures and classes in VisualStudio). A SOAP server deserilizes these types to associated arrays.

Names of data types can be used in web service method parameter declarations (in classes). "ComplexType" is automatically created for these data types in the XSD schema.

Associated array:
$wsdesc->structTypes["StructureName"] =
    array(
        "FieldName" => array("varType" => "DataType"),
        ...
    );
classTypes Defines classes as data types. They are represented as classes in PHP and VisualStudio. A SOAP server deserializes these types to instances of defined classes. A class must be defined before it can be deserialized.

Names of data types can be used in web service method parameter declarations (in classes). "ComplexType" is automatically created for these data types in the XSD schema.

Associated array:
$wsdesc->classTypes["ClassName"] =
    array(
        "FieldName" => array("varType" => "DataType"),
        ...
    );

Example

You can find a good example of using CWebServiceDesc in \bitrix\modules\webservice\classes\general\webservice.wsdl.phpt:

class CCheckAuthWS extends IWebService
{
    ...

    function GetWebServiceDesc()
    {
        $wsdesc = new CWebServiceDesc();
        $wsdesc->wsname = "bitrix.webservice.checkauth";
        $wsdesc->wsclassname = "CCheckAuthWS";
        $wsdesc->wsdlauto = true;
        $wsdesc->wsendpoint = CWebService::GetDefaultEndpoint();
        $wsdesc->wstargetns = CWebService::GetDefaultTargetNS();

        $wsdesc->classTypes = array();
        $wsdesc->structTypes["CUser"] =
        array(
            "ID" => array("varType" => "integer"),
            "NAME" => array("varType" => "string"),
            "TIMESTAMP_X" => array("varType" => "string"),
            "LOGIN" => array("varType" => "string"),
            "PASSWORD" => array("varType" => "string"),
            "CHECKWORD" => array("varType" => "string"),
            "ACTIVE" => array("varType" => "string"),
            "LAST_NAME" => array("varType" => "string"),
            "EMAIL" => array("varType" => "string")
        );

        $wsdesc->classes = array(
            "CCheckAuthWS" => array(
                "CheckAuthorization" => array(
                    "type"        => "public",
                    "name"        => "CheckAuthorization",
                    "input"        => array(
                        "user" =>array("varType" => "string"),
                        "password" =>array("varType" => "string")),
                    "output"    => array(
                        "user" => array("varType" => "CUser")
                        )
                ),
            "GetHTTPUserInfo" => array(
                    "type"        => "public",
                    "name"        => "GetHTTPUserInfo",
                    "input"        => array(),
                    "output"    => array(
                        "user" => array("varType" => "CUser")
                        ),
                    "httpauth" => "Y"
                )
            )
        );

        return $wsdesc;
    }

    ...
}
© 2001-2007 Bitrix Bitrix Site Manager


CXMLCreator

CXMLCreator is a class that represents an XML document tag containing attributes, child elements, text data and CDATA.

Methods

Method | Description
CXMLCreator( string tag, boolean cdata ) | Standard constructor. Takes the name of the tag as an input parameter.
static CXMLCreator createTagAttributed( string heavyTag ) | Creates a new tag (CXMLCreator) based on the tag name heavyTag in a special format.
static CXMLCreator encodeValueLight( string name, AnyType Value ) | Creates an XML tree of a document with the name Name and a structure Value. Name is the tag name in the heavyTag format of createTagAttributed. Value can be any data type, e.g. nested associated arrays See the example below.
setCDATA | Sets the tag CDATA contents.
setAttribute | Sets the tag attribute.
setData | Sets the tag text.
setName | Sets the tag name.
addChild | Adds an element to a list of child items.
getChildrenCount | Returns the number of children elements.
getXML | Returns an XML document as a string.
getXMLHeader | Returns the header of an XML document.

Using SOAP server requests in a SOAP handler

class CMSSOAPResearch extends CSOAPServerResponser
{
    ...

    function ProcessRequestBody(&$cserver, $body)
    {
        $functionName = $body->name();
        $namespaceURI = $body->namespaceURI();
        $requestNode = $body;

        if ($functionName == "Registration")
        {
            $root = new CXMLCreator("RegistrationResponse");
            $root->setAttribute("xmlns", "urn:Microsoft.Search");

            $regres = new CXMLCreator("RegistrationResult");
            $root->addChild($regres);

            $prup = new CXMLCreator("ProviderUpdate");
            $prup->setAttribute("xmlns", "urn:Microsoft.Search.Registration.Response");
            $prup->setAttribute("revision", "1");
            $prup->setAttribute("build", "1");
            $regres->addChild($prup);

            $stat = new CXMLCreator("Status");
            $stat->setData("SUCCESS");
            $prup->addChild($stat);

            $providers = array(

                "Provider" => array (
                    "Message" => "Test service.",
                    "Id" => "{$this->provider_id}",
                    "Name" => "Тестовая служба. {$this->add_tittle}",
                    "QueryPath" => $this->query_path,
                    "RegistrationPath" => $this->registration_path,
                    "AboutPath" => "http://www.bitrix.ru/",
                    "Type" => "SOAP",
                    "Revision" => "1",
                    "Services" => array(
                        "Service" => array(
                            "Id" => "{$this->service_id}",
                            "Name" => "Тестовая служба. {$this->add_tittle}",
                            "Description" => "SOAP server test service.",
                            "Copyright" => "(c) Bitrix.",
                            "Display" => "On",
                            "Category" => "ECOMMERCE_GENERAL",
                            "Parental" => "Unsupported",
                        )
                    )
                )

            );

            $providersEncoded = CSOAPRequest::encodeValueLight("Providers", $providers);
            $prup->addChild($providersEncoded);

            ...

            return true;
        }

        return false;
    }
}
© 2001-2007 Bitrix Bitrix Site Manager


createTagAttributed

CXMLCreator::createTagAttributed

static
CXMLCreator
CXMLCreator::createTagAttributed(string heavyTag);

The method createTagAttributed creates a new tag (CXMLCreator) based on the tag name heavyTag in a special format. Returns true if heavyTag is invalid.

Parameters

Parameter | Description
heavyTag | A string defining the tag name in the following format: [Index:]TagName [Attribute="Attribute value" ...] Index is a number that can be used to add a series of similar tags in an associated array. Attribute can be specified as: attrPart:attrPart = "Value".

Example

CXMLCreator::createTagAttributed( "LicenseInfo xmlns=\"http://ws.strikeiron.com\"");

// Or
CXMLCreator::encodeValueLight( "LicenseInfo xmlns=\"http://ws.strikeiron.com\"",
array(
    "1:ArrayOfStringEl" => "String1",
    "2:ArrayOfStringEl" => "String2"
    )
);
© 2001-2007 Bitrix Bitrix Site Manager


IWebService

IWebService methods

Method | Description
GetWebServiceDesc | Returns a fully initialized web service class (defines methods, data types etc.).
TestComponent | Performs a series of internal tests on a web service.

IWebService is an web service interface that is registered in CWebService. A class that implements a web service must inherit from IWebService.

© 2001-2007 Bitrix Bitrix Site Manager


GetWebServiceDesc

IWebService::GetWebServiceDesc

CWebServiceDesc
IWebService::GetWebServiceDesc();

The method GetWebServiceDesc returns an instance of CWebServiceDesc - a fully initialized web service class (defines methods, data types etc.).

© 2001-2007 Bitrix Bitrix Site Manager


TestComponent

IWebService::TestComponent

void
IWebService::TestComponent();

The method TestComponent runs a series of tests using a SOAP client. This method is called in the public section of a web service.

class CCheckAuthWS extends IWebService
{
    ...

    function TestComponent()
    {
        global $APPLICATION;
        $client = new CSOAPClient("bitrix.soap", $APPLICATION->GetCurPage());

        // HTTP Authorization required by GetHTTPUserInfo method
        $client->setLogin("admin");
        $client->setPassword("123456");
        $request = new CSOAPRequest("GetHTTPUserInfo", CWebService::GetDefaultTargetNS());

        //$request->addParameter("stub", 0);
        $response = $client->send( $request );
        if ($response->FaultString)
            echo $response->FaultString;
        else
            echo "Call GetHTTPUserInfo():
".mydump($response->Value)."
";

    }

    ...
}
© 2001-2007 Bitrix Bitrix Site Manager


Frequently Asked Questions - Bitrix Site Manager - Content Management & Portal Solutions

Frequently Asked Questions

How do I use the Flash banners?

First of all, upload your flash banner to /upload/advertising/flash/.

When creating a banner, specify the following code in the Banner code field:

<a
href="/bitrix/click.php?id=#BANNER_ID#&event1=banner&event2=click&event3=#BANNER_ID#&goto=[URL]">
<div>
<OBJECT
classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"
id="banner"
WIDTH="190"
HEIGHT="190"
ALIGN="">
<PARAM NAME=movie VALUE="/upload/advertising/flash/banner.swf">
<PARAM NAME=quality VALUE=high>
<PARAM NAME=bgcolor VALUE=#FFFFFF>

<EMBED
src="/upload/advertising/flash/banner.swf"
quality=high
bgcolor=#FFFFFF
WIDTH="190"
HEIGHT="190"
NAME="banner"
ALIGN=""
TYPE="application/x-shockwave-flash"
PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
</EMBED>
</OBJECT>
</div>
</a>
Replace banner.swf with the file name of your banner and specify its dimensions. It would be a better idea to not handle clicks and redirects in the Flash banner but specify an URL-encoded link in the [URL] field.

I cannot count visitors who view the banners. Why?

The problem is that the Advertising module is unable to write the cookie for the user viewing a banner. This cookie is installed by the function CAdvBanner::Show, but in most cases this function is called after the HTML stream is opened and the content is being sent to a client browser, thus the cookie cannot be installed due to the HTTP protocol restrictions. There are two ways to solve the problem.

If using the editions Expert or Business, install the Compression module. This module buffers the parsing result before it is compressed and transmitted to a client browser. Buffering allows to correctly track visitors viewing the banners.

If your site bases on PHP completely, please add the following code to the file /bitrix/php_interface/dbconn.php:

ob_start();

This function turns on the buffered parsing of PHP pages, which allows to correctly track visitors viewing the banners.

If your site cannot make use of buffering, you can change the design blocks (prolog_main.php, epilog_main.php) according to the following schema:

<?
// get the banner HTML code before the page contents is transferred
if (CModule::IncludeModule("advertising")):
    $strBanner_top = CAdvBanner::Show("TOP");
    $strBanner_bottom = CAdvBanner::Show("BOTTOM");
    $strBanner_left = CAdvBanner::Show("LEFT");
endif;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head></head>
<body>
         <?
         // write the banner HTML code to the previously reserved advertising areas
         echo $strBanner_top;
         echo $strBanner_bottom;
         echo $strBanner_left;
         ?>
</body>
</html>

In the example above, the banner HTML code is stored in the PHP variables before transferring the HTML content. The banner HTML code is written later as your design requires.


Export setup - Bitrix Site Manager - Content Management & Portal Solutions

Export setup

Currently, there are several catalogs on the Internet containing information on the availability of commodities in online stores. You will succeed in promoting your products if you opportunely update information in such catalogs.

Catalogs require product information in the definite format. The Bitrix Site Manager allows to automate the process of product information dispatching without having to call for web developer services. The system implements the dispatch of user catalogs in the following formats:

  • CSV - common standard format appropriate for further processing;
  • Froogle - format for the Google product catalog;
  • Yandex - format for the Yandex product catalog;
  • Yandex Simple - simplified Yandex format.

To facilitate exporting the frequently used product groups to a certain format, each of the formats provides for creating export profiles containing information on exported product groups and selected information blocks.

If your site runs under control of UNIX family operating system, you can establish periodic export of the product catalog. You can do that by assigning the specific export profile to the system daemon cron.

You can also utilize agent functions for automated catalog export. Agent is a PHP function which is run on regular basis. Every time a page is requested, the system automatically checks for agents waiting execution and runs such agents.

This page allows you to assign export to the cron daemon and create export agents.

Export settings

Field | Description
Exporter
Profile For the profile type - name of the export profile and path to the PHP script that is responsible for export.

For the profile - default or user-defined name of an export profile.

Default profile always requires that you specify information block to export before you proceed with exporting. User profiles perform export automatically; that is, the information block that had been specified when creating a profile is exported.
Profile parameters
In menu | If set to Yes, places a link to this profile to the left menu of the administrative section for faster access. You can enable this option by clicking Add to menu in the Actions column.
In agents | Yes means that an agent exists which periodically attempts to perform export of the catalog every time a page is requested. You can create an agent by clicking Create agent in the Actions column.
On cron | Yes means that the profile is bound to the cron daemon for periodic export of the catalog. You can create an agent by clicking Bind to cron in the Actions column.
Last run | Date and time of the last export using this profile.
Actions
Actions Operations which can be applied to a profile.
  • Add profile - creates a new export profile based on this profile type.
  • Export - performs export using this profile.
  • Add to menu - places a link to this profile to the left menu of the administrative section.
  • Create agent - create a PHP agent to run upon page request.
  • Bind to cron - binds the profile to the cron daemon for automatic export.
  • Delete profile - deletes a profile.

See Also

Export details

© 2001-2005 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Creating and editing a coupon or discount

In this topic

Page menu
Fields
Controls

This form is used to provide parameters of a new or existing discount or coupon.

Note
A coupon is a special kind of discount. The distinction is that a special number (coupon code) can be assigned to a coupon. After the coupon code was rendered to a customer in whatever way, they can use it to receive discounts on purchases.

Page menu

Link | Description
Discounts and coupons | Switches to the form displaying the list of discounts and coupons.

Fields

Field | Description
Site | Names of sites to whose products the discount or coupon can be applied.
Active | Indicates the discount or coupon is active.
Active period | The first and last values of the date range within which the discount or coupon is active.
Name* | Name of the discount or coupon.
Sort index | Sort weight of the discount or coupon. The more this value is, the higher the discount or coupon is positioned in lists.
Discount type Specify here how the discount is to be applied:
  • percent - the discount is calculated as the specified percentage off the product price;
  • fixed amount - specifies the absolute amount.
Discount amount | Value of discount. Depending on the chosen discount type, this can be either the percentage or an absolute amount.
Discount currency | Currency in which the discount is specified.
Maximum amount of discount | Maximum possible amount of discount calculated. Generally used with percentage discount type. The value is to be specified in the currency provided in the previous field.
Applicable to subscription renewals | If checked, the discount or coupon can be applied to purchases of the subscription renewals.
Coupon (for coupon discounts)
Coupon code | If the discount is to be formed as a coupon, type the desired coupon code here. You can generate the random code by clicking Generate.
User groups to use the discount
List of user groups | Select which user groups are allowed to use the discount. If none is selected, the discount is available to all groups.
Price types to which this discount is applicable
List of price types | Select to which price types the discount can be applied. If none is selected, the discount can be applied to price types.
Sections to which this discount is applicable
Add to Select to products of which site sections the discount can be applied.
Click Add to select another section.
Click Delete (above) to delete a selected section.
Short description
Type here the short description for the discount (at most 255 symbols).

Controls

Button | Description
Add | Adds the created discount (coupon) and switches to the list of discounts. Available when creating a new discount.
Save | Applies changes performed on this page and switches to the list of discounts. Displayed when editing an existing discount.
Apply | Applies changes performed on this page without switching to the list of discounts.
Reset | Cancels current changes and restores parameters to their original values.


Types of discounts - Bitrix Site Manager - Content Management & Portal Solutions

Types of discounts

The Types of discounts form is used to manage discounts and extra charges (hereinafter referred to as the discount) in the system.

A discount is the pre-established value that is added or deducted from the product price shown to the customer. Discounts are relative values (percentage).

Type of discount is the named discount value. You assign names to discounts to facilitate handling these values.

If you have to often set the same values of discounts for your products, you can specify these as discounts. In this case, the system will calculate prices relying on the base price and recalculate all prices automatically as soon as the discount rate changes.

Adding a Discount

To add a new discount, type its name in the Name field of the first empty row. This name is used only in the administrative section. Enter the value of discount in the Percent field. This value will be added to the base price when calculating the real price shown to a customer. Click Save.

Changing a Discount

To change the percent of the existing discount, enter a new discount value. Clear the option Recalculate prices if you do not want the current prices affected by this discount to be recalculated. Click Save.

Deleting a Discount

To delete one or more discounts, check boxes in the Delete field of the discounts you want to delete. If you delete a type of discount currently used to form product prices, such prices will become fixed (not depending on the value of discount, see Entering prices).

Remember to click Save after you have made any modifications; otherwise all changes will be lost.


Delete

CFormResult::Delete

bool
CFormResult::Delete(
 int result_id,
 string check_rights = "Y"
)

The method Delete Удаляет указанный результат. В случае успеха функция возвращает "true", иначе - "false".

Parameters

Parameter | Description
result_id | ID результата.
check_rights Флаг необходимости проверки прав текущего пользователя. Возможны следующие значения:
  • Y - права необходимо проверить;
  • N - права не нужно проверять.
Для успешного удаления результата необходимо обладать следующими правами:
  1. На веб-форму, к которой принадлежит редактируемый результат:

    [20] Работа со всеми результатами в соответствии с их статусами

    или, в случае, если вы являетесь создателем удаляемого результата, достаточно права

    [15] Работа со своим результатом в соответствии с его статусом.
  2. На статус в котором находится редактируемый результат необходимо иметь право:

    [DELETE] удаление.
Параметр Optional. По умолчанию - "Y" (права необходимо проверить).

See Also

  • CForm::Delete
  • CFormField::Delete;
  • CFormAnswer::Delete
  • CFormStatus::Delete

Example

<?
$RESULT_ID = 189; // ID результата

// удалим результат с проверкой прав текущего пользователя
if (CFormResult::Delete($RESULT_ID))
{
    echo "Результат # ".$RESULT_ID." успешно удален.";
}
else // ошибка
{
    global $strError;
    echo $strError;
}
?>


GetDataByIDForHTML

CFormResult::GetDataByIDForHTML

array
CFormResult::GetDataByIDForHTML(
 int result_id,
 string get_fields = "N"
)

The method GetDataByIDForHTML Возвращает массив значений ответов на вопросы веб-формы, а также значения полей веб-формы для указанного результата.

Ключи возвращаемого массива в точности соответствуют правилам формирования имен HTML полей для веб-формы.

Пример массива, возвращаемого функцией:

Array
(
    [form_text_586] => Иванов Иван Иванович
    [form_date_587] => 10.03.1992
    [form_textarea_588] => г. Мурманск
    [form_radio_VS_MARRIED] => 589
    [form_checkbox_VS_INTEREST] => Array
        (
            [0] => 592
            [1] => 593
            [2] => 594
        )

    [form_dropdown_VS_AGE] => 597
    [form_multiselect_VS_EDUCATION] => Array
        (
            [0] => 603
            [1] => 604
        )

    [form_text_606] => 2345
    [form_image_607] => 1045
)

Parameters

Parameter | Description
result_id | ID результата.
get_fields | Если значение данного параметра равно "Y", то в в массиве возвращаемом данной функцией будет также значения полей веб-формы; в противном случае, в возвращаемом массиве будут только значения ответов на вопросов веб-формы. Параметр Optional. По умолчанию - "N".

See Also

  • Имена HTML полей
  • CFormResult::Add
  • CFormResult::Update
  • CForm::Check

Example

<?
$RESULT_ID = 189; // ID результата

// получим данные результата
$arValues = CFormResult::GetDataByIDForHTML($RESULT_ID, "Y");

// выведем ответ на вопрос "Фамилия, имя, отчество"
echo $arValues["form_text_586"]; // "Иванов Василий"

// выведем фотографию загруженную в качестве ответа на вопрос "Фотография"
CFile::ShowImage($arValues["form_image_607"], 200, 200, "border=0", "", true);

// выведем значение поля веб-формы "Рассчитанная стоимость"
echo $arValues["form_textarea_ADDITIONAL_149"]; // 134 руб.
?>


Mail

CFormResult::Mail

bool
CFormResult::Mail(
 int result_id,
 mixed template_id = false
)

The method Mail Создает почтовое событие для отсылки данных результата по e-mail. Возвращает "true" в случае успеха, or false otherwise.

Parameters

Parameter | Description
result_id | ID результата.
template_id | ID почтового шаблона. Параметр Optional. По умолчанию - "false" (будут использованы почтовые шаблоны из настроек соответствующей веб-формы).

Example

<?
$RESULT_ID = 189; // ID результата

// создадим почтовое событие для отсылки по EMail данных результата
if (CFormResult::Mail($RESULT_ID))
{
    echo "Почтовое событие успешно создано.";
}
else // ошибка
{
    global $strError;
    echo $strError;
}
?>


Reset

CFormResult::Reset

bool
CFormResult::Reset(
 int result_id,
 bool del_files = true,
 string del_fields = "N",
 array exception = array()
)

The method Reset Удаляет все значения ответов на вопросы веб-формы, а также значения полей веб-формы для указанного результата. Сам результат при этом остается. Если в процессе работы функции ошибок не возникло, то функция возвращает "true".

Parameters

Parameter | Description
result_id | ID результата.
del_files | Флаг необходимости удаления файлов, загруженных в качестве значения ответа на вопрос. Параметр Optional. По умолчанию - "true" (файлы необходимо удалить).
del_fields | Флаг необходимости удаления значений полей веб-формы. Параметр Optional. По умолчанию - "N" (значения полей необходимо удалить).
exception | Массив ID вопросов и полей веб-формы, для которых не нужно удалять значения. Параметр Optional. По умолчанию - пустой массив.

See Also

  • CForm::Reset;
  • CFormField::Reset

Example

<?
$RESULT_ID = 189; // ID результата

// удалим все значения ответов на вопросы и полей веб-формы
// вместе с файлами
// исключение составят вопросы с ID = 140 и ID = 141
CFormResult::Reset($RESULT_ID, true, "Y", array(140, 141));
?>


SetEvent

CFormResult::SetEvent

bool
CFormResult::SetEvent(
 int result_id,
 string event1 = false,
 string event2 = false,
 string event3 = false,
 mixed money = "",
 mixed currency = "",
 mixed goto = "",
 mixed chargeback = "N"
)

The method SetEvent Создает событие в модуле "Статистика". Возвращает "true" в случае успеха, or false otherwise.

Parameters

Parameter | Description
result_id | The ID of the result.
event1 | The event type identifier - event1. Optional. "false" by default (which means "form").
event2 | The event type identifier - event2. Optional. "false" by default (which means the symbolic identifier of the web form).
event3 | The event type identifier - event3. Optional. "false" by default (which means link to the administrative page for viewing the result result_id).
money | The event amount of money. Optional. Default is "".
currency | Three character currency identifier of money. Optional. Default is "".
chargeback | Setting this parameter to "Y" causes the amount of money to be registered as the negative value in the Statistics module. Optional. Default is "".

Example

<?
$RESULT_ID = 189; // ID результата

// создадим событие в модуле "Статистика"
if (CFormResult::SetEvent($RESULT_ID))
{
    echo "Событие успешно создано.";
}
else // ошибка
{
    global $strError;
    echo $strError;
}
?>


SetStatus

CFormResult::SetStatus

bool
CFormResult::SetStatus(
 int result_id,
 int status_id,
 string check_rights = "Y"
)

The method SetStatus assigns a new status to a result.

Parameters

Parameter | Description
result_id | The result ID.
status_id | The new status ID.
check_rights Specifies that the current user access permissions should be checked.

The following values are possible:
  • Y - permissions should be checked;
  • N - do not check permissions should not be checked.
The following permissions are required for the new status to be assigned successfully:
  1. For the web form to which the result being edited belongs:

    [20] Handle all results according to their status

    or, if you are the author of the status to be deleted, the following permission is sufficiet:

    [15] Handle own result according to its status
  2. For the status in which the currently edited result is:

    [EDIT] edit
  3. For the new status status_id:

    [MOVE] move results to this status
Optional. "Y" by default (check permissions).

Return Values

Returns true on success, or false otherwise.

Example

<?
$RESULT_ID = 189; // the result ID
$STATUS_ID = 1; // the ID of the status "Published"

// assign a new status to a result
// check current user permissions
if (CFormResult::SetStatus($RESULT_ID, $STATUS_ID))
{
    echo "Status #".$STATUS_ID." for result #".$RESULT_ID." successfully set.";
}
else // error
{
    global $strError;
    echo $strError;
}
?>


Profiles - Bitrix Site Manager - Content Management & Portal Solutions

Profiles

Forum profiles can be filled by means of the two forms: the form of managing forum groups and the form of managing icons and smileys.

The form of managing forum groups serves for adding and changing forums groups. Groups are used for grouping forums in the public section of the site. Each forum can be either linked to one of the forums groups or not.

The form of managing icons and smileys serves for changing the available set of smileys and icons. When you add a smiley or icon of the non-standard size, check the appearance of the forum public section. Sometimes you will have to make some changes.


Структура таблиц модуля обучения

The learning module table structure

Table fields

Training course

Field | Description | Type | Required | Default
ID | The course ID. | Int | Yes |
TIMESTAMP_X | The time when the course was last modified. | Datetime |  | Current
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
CODE | Mnemonic identifier. | String(50) |  |
NAME | The course name. | String(255) | Yes |
SORT | Sort index. | Int | Yes | 500
PREVIEW_PICTURE | The picture ID in the preview file table. | Int |  |
PREVIEW_TEXT | Short course description. | Text |  |
PREVIEW_TEXT_TYPE | The type of short course description (text/html). | String(4) | Yes | Text
DESCRIPTION | Description. | Text |  |
DESCRIPTION_TYPE | The description type (text/html). | String(4) | Yes | Text
ACTIVE_FROM | The date from which the course is active. | Datetime |  |
ACTIVE_TO | The date from which the course is inactive. | Datetime |  |

Chapters

Field | Description | Type | Required | Default
ID | The chapter ID. | Int | Yes |
TIMESTAMP_X | The date when the chapter was last modified. | Datetime |  | Current
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
COURSE_ID | The course ID. | Int | Yes |
CHAPTER_ID | The parent chapter ID, or root if not specified. | Int |  |
NAME | The chapter name. | String(255) | Yes |
CODE | Mnemonic identifier. | String(50) |  |
SORT | Sort index. | Int | Yes | 500
PREVIEW_PICTURE | The picture ID in the preview file table. | Int |  |
PREVIEW_TEXT | Short chapter description. | Text |  |
PREVIEW_TEXT_TYPE | The type of short description (text/html). | String(4) | Yes | Text
DETAIL_PICTURE | The picture ID in the detail view file table. | Int |  |
DETAIL_TEXT | Detailed description. | Text |  |
DETAIL_TEXT_TYPE | The type of detailed description (text/html). | String(4) | Yes | Text

Lessons
Уроки

Field | Description | Type | Required | Default
ID | The lesson ID. | Int | Yes |
TIMESTAMP_X | The time when the lesson was last modified. | Datetime |  | Current
DATE_CREATE | The date when the lesson was created. | Datetime | Yes | Current
CREATED_BY | The ID of the user who has created the lesson. | Int | Yes | Current user.
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
COURSE_ID | The course ID. | Int | Yes |
CHAPTER_ID | The chapter ID. If not specified, the lesson is not bound to chapter. | Int |  |
NAME | The lesson name. | String(255) | Yes |
SORT | Sort index. | Int | Yes | 500
PREVIEW_PICTURE | The picture ID in the preview file table. | Int |  |
PREVIEW_TEXT | Short lesson description. | Text |  |
PREVIEW_TEXT_TYPE | The type of short description (text/html). | String(4) | Yes | Text
DETAIL_PICTURE | The picture ID in the detail view file table. | Int |  |
DETAIL_TEXT | Detailed description. | Text |  |
DETAIL_TEXT_TYPE | The type of detailed description (text/html). | String(4) | Yes | Text

Questions

Field | Description | Type | Required | Default
ID | The question ID. | Int | Yes |
TIMESTAMP_X | The time when the question was last modified. | Datetime |  | Current
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
LESSON_ID | The lesson ID. | Int | Yes |
QUESTION_TYPE | The question type (S - single choice, M - multiple choice). | Char(1) | Yes | S
NAME | The question name. | String(255) | Yes |
SORT | Sort index. | Int | Yes | 500
DESCRIPTION | Description. | Text |  |
DESCRIPTION_TYPE | The description type (text/html). | String(4) | Yes | Text
FILE_ID | The picture/file ID in the file table. | Int |  |
SELF | Indicates if the question is self-check (Y/N). | Char(1) | Yes | Y
POINT | Score. | Int | Yes | 10

Variants of answers

Field | Description | Type | Required | Default
ID | The answer ID. | Int | Yes |
QUESTION_ID | The question ID. | Int | Yes |
SORT | Sort index. | Int | Yes | 10
ANSWER | Variant of answer. | Text | Yes |
CORRECT | Indicates if the answer is correct (Y/N). | Char(1) | Yes |
FEEDBACK | Comment to the answer. | Text |  |

Tests

Field | Description | Type | Required | Default
ID | The test ID. | Int | Yes
COURSE_ID | The course ID. | Int | Yes
TIMESTAMP_X | The time when the test was last modified. | Datetime | Current
SORT | Sort index. | Int | Yes | 500
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
NAME | The test name. | String(255) | Yes
DESCRIPTION | Description. | Text
DESCRIPTION_TYPE | The description type (text/html). | String(4) | Yes | Text
ATTEMPT_LIMIT | Maximum count of attempts. 0 means unlimited. | Int | Yes
TIME_LIMIT | Testing session time limit (min). 0 means unlimited. | Int
COMPLETED_SCORE | The required percent of correct answers for the test to be passed. | Int
QUESTIONS_FROM | Indicates which questions are included in test: A - from the whole course, C - from each chapter, L - from each lesson. | Char(1) | Yes | A
QUESTIONS_AMOUNT | Number of questions in test. | Int | Yes
RANDOM_QUESTIONS | Indicates the random order of questions (Y|N). | Char(1) | Yes | Y
RANDOM_ANSWERS | Indicates the random order of answers (Y/N). | Char(1) | Yes | Y
APPROVED | Whether results are checked automatically (Y|N). | Char(1) | Yes | Y
INCLUDE_SELF_TEST | Whether self-check questions are included (Y/N). | Char(1) | Yes | N
PASSAGE_TYPE The test process design:

0 - the student cannot switch to the next question without answering the current one, and cannot change their answers;

1 - the student can switch to the next question without answering the current one but cannot change their answers;

3 - the student can switch to the next question without answering the current one, and can change their answers.

Char(1) Yes 0

Test attempts

Field | Description | Type | Required | Default
ID | The attempt ID. | Int | Yes |
TEST_ID | The test ID. | Int | Yes |
STUDENT_ID | The ID of the user who is currently taking the test. | Int | Yes |
DATE_START | The time when a test started. | Datetime | Yes | Current
DATE_END | The time when a test was completed. | Datetime |  |
STATUS | The attempt status: B - started, D - aborted, F - completed. | Char(1) | Yes | B
SCORE | Score. | Int |  |
MAX_SCORE | Maximum score. | Int |  | Automatically
QUESTIONS | Number of questions in an attempt. | Int |  | Automatically

Examination schema

Field | Description | Type | Required | Default
ID | The result ID. | Int | Yes |
ATTEMPT_ID | The attempt ID. | Int | Yes |
QUESTION_ID | The question ID. | Int | Yes |
RESPONSE | The student answer. | Text |  |
POINT | Score. | Int | Yes |
ANSWERED | The question is answered (Y/N). | Char(1) | Yes | N
CORRECT | The question is answered correctly (Y/N). | Char(1) | Yes | N

Grade book

Field | Description | Type | Required | Default
ID | The record ID in the grade book. | Int | Yes |
STUDENT_ID | The ID of the user who is currently taking the test. | Int | Yes |
TEST_ID | The test ID. | Int | Yes |
RESULT | The result score. | Int |  |
MAX_RESULT | Maximum result score. | Int |  | Automatically
COMPLETED | The test is completed (Y/N). | Char(1) | Yes | N
ATTEMPTS | Number of attempts allowed. | Int. |  | Automatically

Certificates

Field | Description | Type | Required | Default
ID | The certificate ID. | Int | Yes |
STUDENT_ID | The user ID. | Int | Yes |
COURSE_ID | The course ID. | Int | Yes |
TIMESTAMP_X | The time when the certificate was modified. | Datetime |  | Current
DATE_CREATE | The time when certificate was created. | Datetime |  |
ACTIVE | Active state flag (Y|N). | Char(1) | Yes | Y
SORT | Sort index. | Int | Yes | 500
FROM_ONLINE | The certificate was obtained via an online training course (Y/N). | Char(1) | Yes | Y
PUBLIC_PROFILE | The certificate will be published in the profile (Y/N). | Char(1) | Yes | Y
SUMMARY | The number of points collected while taking all tests of the course. | Int | Yes |
MAX_SUMMARY | Maximum number of points collected while taking all tests of the course. | Int | Yes | Automatically

Student profile

Field | Description | Type | Required | Default
USER_ID | The user ID. | Int | Yes |
TRANSCRIPT | Random numeric identifier. | Int | Yes | Automatically
PUBLIC_PROFILE | Whether profile is public or not (Y/N). | Char(1) | Yes | N
RESUME | The student resume. | Text |  |
© 2001-2007 Bitrix Bitrix Site Manager - Content Management & Portal Solutions


Help Section - Bitrix Site Manager - Content Management & Portal Solutions

Help Section

The Bitrix Site Manager help section is aimed at both product users and web developers who build their projects with the use of Bitrix Site Manager. Web site visitors may also find useful information in some of the help section's parts, for example Forum.

This help system is available on-line (Administrative section -> Help) as well as in the form of compiled HTMLHelp file (http://www.bitrixsoft.com/download/bsm.chm).


Система обновлений

Система обновлений служит для осуществления взаимодействия между копией продукта (клиент) и сервером обновлений. Основными видами взаимодействия являются:

  • обновление модулей продукта до последней версии (это позволяет получить новый функционал модулей и исправить в них возможные ошибки);
  • загрузка новых модулей, которые доступны в соответствии с лицензией;
  • загрузка языковых файлов (файлов переводов языкозависимых сообщений продукта на разные языки);
  • загрузка системы помощи на разных языках;
  • регистрация копии продукта с помощью лицензионного ключа;
  • загрузка исходных текстов скриптов модулей продукта;
  • добавление купонов на дополнительные сайты.

Некоторые термины системы обновлений

Ядро продукта - каталог /bitrix/modules/ (пути везде задаются относительно корневой папки, если явно не указано противное). Часто в понятие ядра продукта включается так же структура базы данных продукта.

Служебная область - все подкаталоги каталога /bitrix/, за исключением каталогов /bitrix/modules/ (т.е. ядра продукта) и /bitrix/updates/. Часто в понятие служебной области включаются так же данные служебных таблиц базы данных (например, записи таблицы b_event_type).

Каталог системы обновлений - каталог /bitrix/updates/. Этот каталог предназначен исключительно для работы системы обновлений и не может использоваться других целях.

Публичная часть - все каталоги, относящиеся к данной копии продукта, за исключением ядра продукта, служебной области и каталога системы обновлений. Часто в понятие публичной части включаются все данные базы данных, за исключением данных служебных таблиц.

Регистрация копии продукта - снятие с данной копии продукта ограничений, которые имеет демонстрационная версия (например, ограничение по времени работы).

Лицензионный ключ - специальный ключ (последовательность символов), который подтверждает право на использование копии продукта.

Купон на дополнительный сайт - специальный ключ (последовательность символов), который подтверждает право на создание одного дополнительного сайта в рамках данной копии продукта.

Сервер обновлений - сервер, который отдает обновления продукта системе обновлений. Адрес сервера обновлений задается на странице глобальных настроек главного модуля (должен иметь значение www.bitrixsoft.ru или www.bitrixsoft.com).

Важные замечания по работе системы обновлений

Система обновлений не изменяет публичную часть. Служебная область изменяется только в рамках необходимости, при этом существующие файлы и записи не изменяются (т.к. они уже могли быть изменены владельцем копии продукта под свои нужды). Ядро продукта может быть изменено системой обновлений сколь угодно сильно (при этом, конечно, обеспечивается обратная совместимость).

Важно!
Если вы самостоятельно изменили хотя бы один файл ядра продукта или структуру базы данных, то автоматическая установка обновления может иметь непредсказуемый результат.

Система обновлений не собирает и не передает никаких конфиденциальных данных копии продукта, на которой она работает. Система обновлений обменивается с сервером обновлений исключительно техническими данными, напрямую необходимыми для корректной работы системы обновлений (например, текущие версии модулей или дата последнего обновления системы помощи).

Система обновлений производит технически сложную серьезную модификацию ядра продукта. Если эта модификация будет произведена с ошибками, то сайты, работающие на этом ядре, могут оказаться неработоспособными. Перед установкой обновлений рекомендуется убедится в наличии резервной копии как базы данных, так и скриптов ядра продукта и служебной области. Рекомендуется для проведения процедуры обновления выбирать время, когда нагрузка на сервер минимальна. При возникновении проблем с установкой обновления вам необходимо незамедлительно обратиться в службу технической поддержки компании Битрикс.

Главная страница системы обновлений (первый шаг)

После выбора в левом меню административной части сайта пункта "Обновление" вы попадаете на главную страницу системы обновлений.

Если на главной странице системы обновлений выводится сообщение о том, что лицензионный ключ не верен (или лицензия не найдена), то возможны следующие ситуации:
- если у вас уже есть лицензионный ключ, то этот ключ необходимо ввести в соответствующее поле на главной странице системы обновлений или в соответствующее поле на странице глобальных настроек главного модуля;
- если у вас нет лицензионного ключа, то вы можете запросить пробный лицензионный ключ. Для этого воспользуйтесь соответствующей ссылкой на главной странице системы обновлений. Полученный лицензионный ключ нужно ввести в соответствующее поле на главной странице системы обновлений или в соответствующее поле на странице глобальных настроек главного модуля.

Если на главной странице системы обновлений выводится сообщение о том, что лицензионный ключ не активирован, и предлагается к заполнению форма, то вам необходимо заполнить все поля этой формы. После этого лицензионный ключ будет активирован.

Если на главной странице системы обновлений выводится сообщение о том, что доступно обновление самой системы обновлений, то необходимо установить это обновление. До установки этого обновления остальной функционал системы будет недоступен.

Если в систему введен валидный активный лицензионный ключ и обновление самой системы обновлений не доступно, то главная страница системы обновлений предлагает на выбор набор действий, которые можно совершить согласно текущей лицензии:

  • Просмотр и загрузка обновлений - действие доступно в случае наличия на сервере обновлений новых версий доступных для текущей лицензии модулей
  • Просмотр и загрузка языковых файлов - действие доступно в случае наличия на сервере обновлений новых версий языковых файлов
  • Просмотр и загрузка системы помощи - действие доступно в случае наличия на сервере обновлений новых версий файлов помощи
  • Регистрация продукта - действие доступно, если копия продукта не зарегистрирована, а текущая лицензия позволяет произвести регистрацию. Регистрацию копии продукта необходимо произвести незамедлительно после получения лицензионного ключа, так как после истечения срока пробного использования продукта восстановить работоспособность сайта будет затруднительно. Регистрация продукта выполняется в один шаг без дополнительных вопросов.
  • Загрузка исходных текстов - действие доступно, если скрипты копии продукта закодированы, а текущая лицензия позволяет получить исходные тексты скриптов. Перед загрузкой исходных текстов ядро продукта должно быть обновлено до последней версии (т.е. никакие обновления ядра продукта не должны быть доступны). Загрузка исходных текстов выполняется в один шаг без дополнительных вопросов. Обратите внимание, что в случае медленного канала или большой загрузки сервера загрузка исходных текстов может занять некоторое время.
  • Добавление дополнительного сайта - действие доступно всегда. Если у вас есть купон на получение дополнительного сайта, то вы можете применить его незамедлительно.
  • Просмотр журнала установки - журнал установки содержит информацию о 20 последних установленных обновлениях, включая информацию по статусам и ошибкам установки.
© 2001-2005 Битрикс Битрикс: Управление сайтом


Добавление дополнительного сайта

Система Битрикс: Управление сайтом позволяет создавать несколько сайтов с применением одной копии (лицензии) продукта, размещая ядро и базу данных системы в единственном экземпляре на сервере. Максимальное количество сайтов на одной копии продукта ограничено лицензией. Если необходимо создать дополнительные сайты сверх текущего максимального количества, то следует приобрести лицензии на дополнительные сайты.

При приобретении лицензий на дополнительные сайты вам выдаются купоны на дополнительные сайты (один купон - одна дополнительная лицензия). Дополнительные лицензии (и купоны соответственно) зависят от редакции продукта. Например, для создания дополнительного сайта в продукте редакции Эксперт MySQL необходимо приобрести лицензию (купон) на дополнительный сайт для редакции Эксперт MySQL.

После получения купона вам необходимо воспользоваться ссылкой "Добавить сайт" на главной странице системы обновлений. На открывшейся странице необходимо ввести полученный купон в соответствующее поле и нажать на кнопку "Получить сайт".

Если купон действителен, принадлежит соответствующей редакции продукта и не был уже применен ранее, то максимальное количество сайтов для данной копии продукта будет увеличено на одну штуку.

© 2001-2005 Битрикс Битрикс: Управление сайтом


Обновление ядра продукта

Если доступны обновления ядра продукта, то на главной странице системы обновлений появляется ссылка на просмотр и загрузку этих обновлений.

Система обновлений производит технически сложную серьезную модификацию ядра продукта. Если эта модификация будет произведена с ошибками, то сайты, работающие на этом ядре, могут оказаться неработоспособными. Перед установкой обновлений рекомендуется убедится в наличии резервной копии как базы данных, так и скриптов ядра продукта и служебной области. Рекомендуется для проведения процедуры обновления выбирать время, когда нагрузка на сервер минимальна. При возникновении проблем с установкой обновления вам необходимо незамедлительно обратиться в службу технической поддержки компании Битрикс.

Обратите внимание, что в случае медленного канала или большой загрузки сервера обновление ядра продукта может занять некоторое время.

Обновление ядра продукта осуществляется в несколько шагов: выбор требуемого действия (первый шаг), просмотр и загрузка выбранных обновлений (второй шаг), установка выбранных обновлений (третий шаг) и отчет об установке (четвертый шаг).

Выбор требуемого действия (первый шаг)

Этот шаг соответствует главной странице системы обновлений. Если доступны обновления ядра продукта, то на главной странице системы обновлений появляется ссылка на просмотр и загрузку этих обновлений (на второй шаг).

Просмотр и загрузка выбранных обновлений (второй шаг)

На этом шаге показывается список доступных обновлений, которые можно загрузить с сервера обновлений. По умолчанию будут загружены все доступные обновления. Если какое-либо из обновлений загружать не нужно, то можно убрать его из списка загрузки с помощью соответствующей кнопки "Удалить". Обновления, которые были убраны из списка загрузки, можно вернуть обратно в этот список с помощью соответствующей кнопки "Добавить". Обратите внимание, что в случае связанных обновлений в списке загрузки должны быть все связанные обновления либо не должно быть ни одного из них (система обновлений контролирует выполнение этого правила).

На этом шаге показывается так же общий размер выбранных для загрузки обновлений. Если размер обновлений велик и ваш хостинг не дает возможности поставить все обновления за один раз, то можно попробовать установить обновления по частям (по одному или нескольким модулям).

Внимание!
Внимательно прочитайте описания обновлений модулей - они содержат важную информацию по установке обновления и предупреждают о возможных проблемах в работе.

Для перехода на третий шаг процедуры обновления ядра продукта необходимо нажать на кнопку "Далее". Это действие запустит механизм загрузки выбранных обновлений с сервера обновлений. Загрузка может занять некоторое время.

Просмотр и установка выбранных обновлений (третий шаг)

К этому шагу выбранные обновления загружены с сервера обновлений и готовы к установке. Страница показывает список доступных обновлений, которые можно установить. По умолчанию будут установлены все загруженные обновления. Если какое-либо из обновлений устанавливать не нужно, то можно убрать его из списка установки с помощью соответствующей кнопки Удалить. Обновления, которые были убраны из списка установки, можно вернуть обратно в этот список с помощью соответствующей кнопки Добавить. Обратите внимание, что в случае связанных обновлений в списке установки должны быть все связанные обновления либо не должно быть ни одного из них (система обновлений контролирует выполнение этого правила).

Для начала установки необходимо нажать на кнопку Установить. Это действие запустит механизм установки выбранных обновлений. Установка может занять некоторое время, которое зависит от объема обновления и текущей загруженности системы. Крайне рекомендуется для установки обновлений выбирать время, когда загруженность системы минимальна.

Отчет об установке (четвертый шаг)

На этом шаге выводится информация об итогах установки обновления и произошедших при установке ошибках.

Внимание!
Не обновляйте эту страницу и не используйте кнопку Назад браузера.

Если страница сообщает о наличии каких-либо ошибок или если страница вообще не загрузилась корректно, вам необходимо незамедлительно проверить работоспособность сайта и выяснить причину возникновения ошибки. Если вы не можете сделать это самостоятельно, вам необходимо незамедлительно обратиться в службу техподдержки компании Битрикс. Для ускорения решения проблемы мы рекомендуется сразу приложить к обращению файл /bitrix/updates/updater.log.

Просмотреть результаты работы системы обновлений вы можете так же в журнале установки.

© 2001-2005 Битрикс Битрикс: Управление сайтом


Просмотр и загрузка системы помощи

Если доступны обновления системы помощи продукта, то на главной странице системы обновлений появляется ссылка на просмотр и загрузку этих обновлений.

Обратите внимание, что в случае медленного канала или большой загрузки системы обновление системы помощи продукта может занять некоторое время.

Обновление системы помощи продукта осуществляется в несколько шагов: выбор требуемого действия (первый шаг), просмотр и установка системы помощи (второй шаг), отчет об установке (третий шаг).

Выбор требуемого действия (первый шаг)

Этот шаг соответствует главной странице системы обновлений. Если доступны обновления системы помощи продукта, то на главной странице системы обновлений появляется ссылка на просмотр и установку этих обновлений (на второй шаг).

Просмотр и установка помощи (второй шаг)

На этом шаге показывается список систем помощи на разных языках, которые можно загрузить с сервера обновлений. Особо выделены те языки, которые присутствуют в системе. После выбора одного из доступных обновлений и нажатия на кнопку Загрузить указанное обновление будет загружено с сервера обновлений и установлено. Загрузка может занять некоторое время.

Отчет об установке (третий шаг)

На этом шаге выводится информация об итогах установки обновления и произошедших при установке ошибках.

Внимание!
Не обновляйте эту страницу и не используйте кнопку Назад браузера.

Просмотреть результаты работы системы обновлений вы можете также в журнале установки.

© 2001-2005 Битрикс Битрикс: Управление сайтом


Просмотр и загрузка языковых файлов

Если доступны обновления языковых файлов (т.е. файлов с переводами языкозависимых сообщений продукта на какой-либо язык), то на главной странице системы обновлений появляется ссылка на просмотр и загрузку этих обновлений.

Обратите внимание, что в случае медленного канала или большой загрузки системы обновление языковых файлов продукта может занять некоторое время.

Обновление языковых файлов продукта осуществляется в несколько шагов: выбор требуемого действия (первый шаг), просмотр и установка языковых файлов (второй шаг), отчет об установке (третий шаг).

Выбор требуемого действия (первый шаг)

Этот шаг соответствует главной странице системы обновлений. Если доступны обновления языковых файлов продукта, то на главной странице системы обновлений появляется ссылка на просмотр и установку этих обновлений (на второй шаг).

Просмотр и установка языковых файлов (второй шаг)

На этом шаге показывается список наборов языковых файлов для разных языков, которые обновились с момента последней установки. Особо выделены те языки, которые присутствуют в системе. После выбора тех из доступных обновлений, которые необходимо установить, и нажатия на кнопку Загрузить указанные обновления будут загружены с сервера обновлений и установлены. Загрузка может занять некоторое время.

Отчет об установке (третий шаг)

На этом шаге выводится информация об итогах установки обновления и произошедших при установке ошибках.

Внимание!
Не обновляйте эту страницу и не используйте кнопку Назад браузера.

Просмотреть результаты работы системы обновлений вы можете так же в журнале установки.

© 2001-2005 Битрикс Битрикс: Управление сайтом


Getting Started. Settings - Bitrix Site Manager - Content Management & Portal Solutions

Getting Started. Settings

After installing the e-Store module, you need to correctly customize its settings.

In this topic

  • Global settings of the module
  • Currency settings
  • Setting of payer types
  • Group of properties settings
  • Properties settings
  • Location settings
  • Groups of locations settings
  • Delivery service settings
  • Payment system settings
  • Order statuses settings
  • Currency exchange rates settings
  • Discounts settings
  • Tax settings
  • Tax rates settings
  • Public section settings

Global settings of the module

Where?
Menu item in the left of System settings -> Settings, choose Online store in the drop-down list, click the Choose button.

After the sale module installing, go to the global settings page of the module (System settings -> Settings, choose e-Store in the drop-down list). Define the appropriate settings in the appropriate fields, and click the Save button.

Order department E-Mail
E-Mail address for sending information messages of the sale module.
Default registration E-Mail
The e-Store allows purchasing for registered site users. If the customer is not registered in the system, this field contains the default E-Mail to be used for registration of customers during ordering. If the E-Mail properties for the order are also defined, the order E-Mail will be used (see Order properties section) instead of the registration E-Mail.
Payment system details
The parameters Postal order address, Bank transfer details, Savings bank transfer details, ShopID, wbp_ShopKeyID, wbp_ShopEncryptionKey, Shop_IDP, Login, Password are outdated and not recommended for usage. To set the new details of payment systems, you need to copy the payment system template from the system core, and modify the needed parameters in it.

Currency settings

Where?
Menu item on the left of Currencies -> Currencies.

The currency settings are customized in the currency module.

Open the currency settings page (Currencies -> Currencies). Define the site currencies list (see the Currencies section). A store will not function, until at least one currency is set in the system.

Setting of payer types

Where?
Menu item on the left of e-Store -> Payer types.

Open the payer types settings page (e-Store -> Payer types). Define the payers types list. For example, you can create the following payer types:

  • natural person;
  • businessman;
  • legal person.

Every payer type has its own properties to be completed at ordering, and its own payment system processing (see Payer type section). A store customer chooses the appropriate payer type at ordering. According to this type, the customer is offered the corresponding set of fields to fill at ordering and corresponding set of payment systems interfaces. The payer type depends on the site. Customer can choose from different payer types sets on different sites.

Setting of property groups

Where?
Menu item on the left of e-Store -> Property groups.

Go to the page of setting the property groups (e-Store -> Property groups). For each payer type, define a list of property group for the order (for example, Delivery address, Package, etc). Property groups are used for classification of order properties, making them user-friendly (see the Property groups section). Property groups are defined according to the payer type, so different payers have different property groups.

Property settings

Where?
Menu item on the left of e-Store -> Order properties.

Go to the properties settings page (e-Store -> Order properties). For every payer type, define the order properties list (for example, E-Mail, City, Contact person, etc). The order properties are needed at ordering and getting the delivery information (Order properties section). Order properties depend on the payer type, so payers of different type have different order properties.
By using the Preview function, you can view how the page of order properties page will look.

Location settings

Where?
Menu item on the left of e-Store -> Locations.

Location - geographic unit with common delivery conditions. Location defines the full delivery address or part of it.

Go to the location setting page (e-Store -> Locations). Define the list of locations. Usually the location is defined by the combination Country-City.

Moreover, for each country it's required to envision a location without any city. This location will be used in case the customer has no appropriate combination Country - City (see Location section).

Setting of location groups

Where?
Menu item on the left of e-Store -> Location groups.

Go to the page of location groups settings (e-Store -> Groups of locations). Define the list of location groups. Grouping of locations makes easier the creation of links between locations and delivery services. It is sufficient to add a location into the location group with the defined delivery rates ones to further use it for setting the delivery services. It also simplifies location deletion and creation (see Location groups section).

Delivery service settings

Where?
Menu item on the left of e-Store -> Delivery.

Go to the delivery services settings page (e-Store -> Delivery). Define the delivery services list. Delivery service can depend on the order total weight and cost and always depends on location groups.

Be sure that the delivery services list covers all the possible variants. For example, if you've specified that this service is used for orders with cost more than $500, make sure that there are delivery services for the same locations for the order cost less than $500.

Be sure that the list contains the delivery services for all available locations (see Delivery service section).

Delivery services are set per sites. Customers can choose from various delivery services depending on the site.

Payment system settings

Where?
Menu item n the left of e-Store -> Payment systems.

Go to the payment systems setting page (e-Store -> Payment systems). Define the payment system list.

Payment systems can be set for all or for some payer types. You need to set the payment system processing file and possibly the processor of payment system results for every payer type linked to the payment system. The processing file is used for printing the required payment documents or initializing the payment procedure which uses electronic means of payment. The payment system result processor is used for those electronic means of payment which can return the order payment status by request (see Payment systems section).

Payment systems depend on sites. Customers can choose from various payment systems interfaces depending on the site.

Order statuses settings

Where?
Menu item n the left of e-Store -> Statuses.

Go to the order statuses settings page (e-Store -> Statuses). Define the order statuses list (for example Accepted, In process, Shipment is expected, Shipped, Delivered, etc).

Statuses inform customers and e-Store employees about the current state of the order (see Statuses).

Currency exchange rates settings

Where?
Menu item on the left of e-Store -> Currency exchange rates.

The settings of the currency exchange rates are defined in the currency module.

Go to the page of setting the currency exchange rates (e-Store -> Currency exchange rates). Enter the required currency exchange rates (see Currencies exchange rates).

Discounts settings

Where?
Menu item on the left of e-Store -> Discounts.

Go to the page of setting discounts which depend on the order cost (e-Store -> Discounts). Enter the required discounts (see Discounts).

Discounts depend on sites. Customer receives different discounts depending on the sites.

Tax settings

Where?
Menu item on the left of e-Store -> Taxes.

Go to the tax settings page (e-Store -> Taxes) and enter the taxes to be used for calculating the order cost).

Tax rate settings

Where?
Menu item on the left of e-Store -> Tax rates.

Go to the tax rates settings page (e-Store -> Tax rates), and enter the tax rates according to the payer type and its location (see Taxes).

If some customers are exempt from taxes, select user groups to which these customers belong on the page of exempt-from-taxes settings (e-Store -> Exempt from taxes).

Public section settings

Where?
Is defined by developers by changing the e-Store code.

Be sure that you have properly set the public section: add to cart, ordering procedure, customer personal section (see Information for developers section).


GetBasketList

array GetBasketList();

This function actualizes basket of the current user and returns an array containing the basket records.

Return Values

Returns an array of associated arrays having the same structure as one of those returned by the method CSaleBasket::GetList.

Example

<?
$arItems = GetBasketList();
for ($i = 0; $i < count($arItems); $i++)
{
   echo "<pre>";
   print_r($arItems[$i]);
   echo "</pre><br>";
}
?>
© 2001-2005 Bitrix Bitrix Site Manager


What are distribution lists for? - Bitrix Site Manager - Content Management & Portal Solutions

What are newsletters for?

Newsletters are a tool to group subscribers by the information topics.

Newsletters do not contain issues or subscribers. They are used as a convenient tool to group subscribers receiving certain issues.

For example, you can create the "Company news" newsletter and propose to visitors to subscribe to it. If a subscriber chooses to receive issues of this newsletters, the link between newsletter issues and e-mail address will be established. When creating a newsletter issue, you can specify that this message should be sent to the recipients from the "Company news" newsletter - the message will be sent to subscribers of this newsletter.


Create and edit a ticket - Bitrix Site Manager - Content Management & Portal Solutions

Create and edit a ticket

This form is designed to create tickets in the technical support service.

When creating a new ticket by a non-employee of the technical support, the person in charge can be appointed automatically depending on the category, emergency or source of the ticket. If the person in charge has not been appointed, in case the parameter Default person in charge is set in the module settings, the person in charge will be defined by default. After the ticket is added to the database, the person in charge will be notified by e-mail. In case the person in charge has not been selected, the notification will be sent to e-mail addresses of all users having the right "technical support administrator" (including users of the group #1).

If the person responsible for the ticket changes it, the ticket author will be notified about it. If the ticket is changed by its author, the person in charge or the support administrator will be notified about it. If the new person in charge is appointed, both the ticket author and the new person in charge will be notified. If you deselect the Hide a message, not notify an author checkbox, the author of the ticket will not be notified.

Changing a ticket means:

  • changing its category, emergency, state or estimating replies to it;
  • appointing a new person responsible for the ticket;
  • adding a new ticket;
  • closing or opening a ticket.

Form of ticket editing

Field | Description
Source / Author | Source and author of the ticket.
Created Time of creating a ticket; name of the user who created a ticket.

This field is displayed only in the ticket editing mode.
Modified Time of the last modification of the ticket; author of modification.

This field is displayed only in the ticket editing mode.
Closed Time of ticket closure.

This field is displayed only in the ticket editing mode.
Discussion

This section is displayed only in the ticket editing mode.
  • # - ticket serial number. It defines the order in which tickets are displayed in the discussion.
  • Author - author of the ticket.
  • Created - time of creating a ticket.
  • [Quote] – link allowing to insert quotations.
  • [Original] - link to the original e-mail in the e-mail module (if the message was created in the e-mail module).
  • [Change] – link that allows to edit a message. It's accessible only to administrators.
  • [Delete] – link that allows to delete a message. It's accessible only to administrators.
Image and message body
Hide a message, not notify an author Select this checkbox to create a message as hidden from the ticket author (if he doesn't belong to the support group). Any changes being made at the moment will not be e-mailed to the author; the technical support group will be notified about these changes.

This field is displayed only in the ticket editing mode.
Source / Author | In this group, a technical support engineer can specify the message source and author. If the support engineer is entitled with the Read right for the main module, users can be selected in an additional window (button "..."). In addition, when the user ID is entered, information about this user (login, name) will be displayed next to it.
Reply template In the drop-down list, the administrator or the person responsible can select the reply template.

This field is displayed only in the ticket editing mode.
Message | Field for entering a new message.
Image | Field for inserting an image of the new message.
Person responsible | User responsible for the message.
State | Ticket state.
Reply estimate Estimate of replies provided by the ticket author.

This field is displayed only in the ticket editing mode.
Emergency | Ticket emergency.
Category | Ticket category.
Close Checkbox that allows to open or close a ticket.

This field is displayed only in the ticket editing mode.
Administrator note Field for the commentary visible only to users belonging to the support group.

This field is displayed only in the ticket editing mode.

If you belong to the technical support group, you can specify any author and source of the ticket when you create or add a new message to it. By default, all operations will be performed on your behalf. The default source is <web>.

If you are a site administrator or a person responsible for the ticket, the following fields for modification are available to you:

  • Ticket category;
  • Person responsible for the ticket;
  • Ticket state;
  • Close a ticket;
  • Administrator note.

If you are an author of the ticket, the following fields for modification are available to you:

  • Ticket emergency;
  • Reply estimates.

Message editing

Direct message editing is available only to the site administrator or the technical support administrator.

Field | Description
Source / Author | Message source and author.
Serial number | Message serial number used to display the message in the discussion. This field is displayed only in the ticket editing mode.
Image | Fields for replacing or deleting images.
Message | Message body.