-{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"WoltLab Suite 5.5 Documentation # Introduction # This documentation explains the basic API functionality and the creation of own packages. It is expected that you are somewhat experienced with PHP , object-oriented programming and MySQL . Head over to the quick start tutorial to learn more. About WoltLab Suite # WoltLab Suite Core as well as most of the other packages are available on GitHub and are licensed under the terms of the GNU Lesser General Public License 2.1 .","title":"WoltLab Suite 5.5 Documentation"},{"location":"#woltlab-suite-55-documentation","text":"","title":"WoltLab Suite 5.5 Documentation"},{"location":"#introduction","text":"This documentation explains the basic API functionality and the creation of own packages. It is expected that you are somewhat experienced with PHP , object-oriented programming and MySQL . Head over to the quick start tutorial to learn more.","title":"Introduction"},{"location":"#about-woltlab-suite","text":"WoltLab Suite Core as well as most of the other packages are available on GitHub and are licensed under the terms of the GNU Lesser General Public License 2.1 .","title":"About WoltLab Suite"},{"location":"getting-started/","text":"Creating a simple package # Setup and Requirements # This guide will help you to create a simple package that provides a simple test page. It is nothing too fancy, but you can use it as the foundation for your next project. There are some requirements you should met before starting: Text editor with syntax highlighting for PHP, Notepad++ is a solid pick *.php and *.tpl should be encoded with ANSI/ASCII *.xml are always encoded with UTF-8, but omit the BOM (byte-order-mark) Use tabs instead of spaces to indent lines It is recommended to set the tab width to 8 spaces, this is used in the entire software and will ease reading the source files An active installation of WoltLab Suite An application to create *.tar archives, e.g. 7-Zip on Windows The package.xml File # We want to create a simple page that will display the sentence \"Hello World\" embedded into the application frame. Create an empty directory in the workspace of your choice to start with. Create a new file called package.xml and insert the code below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/package.xsd\" name= \"com.example.test\" > <packageinformation> <!-- com.example.test --> <packagename> Simple Package </packagename> <packagedescription> A simple package to demonstrate the package system of WoltLab Suite Core </packagedescription> <version> 1.0.0 </version> <date> 2019-04-28 </date> </packageinformation> <authorinformation> <author> Your Name </author> <authorurl> http://www.example.com </authorurl> </authorinformation> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"template\" /> <instruction type= \"page\" /> </instructions> </package> There is an entire chapter on the package system that explains what the code above does and how you can adjust it to fit your needs. For now we'll keep it as it is. The PHP Class # The next step is to create the PHP class which will serve our page: Create the directory files in the same directory where package.xml is located Open files and create the directory lib Open lib and create the directory page Within the directory page , please create the file TestPage.class.php Copy and paste the following code into the TestPage.class.php : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <? php namespace wcf\\page ; use wcf\\system\\WCF ; /** * A simple test page for demonstration purposes. * * @author YOUR NAME * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> */ class TestPage extends AbstractPage { /** * @var string */ protected $greet = '' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_GET [ 'greet' ])) $this -> greet = $_GET [ 'greet' ]; } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( empty ( $this -> greet )) { $this -> greet = 'World' ; } } /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'greet' => $this -> greet ]); } } The class inherits from wcf\\page\\AbstractPage , the default implementation of pages without form controls. It defines quite a few methods that will be automatically invoked in a specific order, for example readParameters() before readData() and finally assignVariables() to pass arbitrary values to the template. The property $greet is defined as World , but can optionally be populated through a GET variable ( index.php?test/&greet=You would output Hello You! ). This extra code illustrates the separation of data processing that takes place within all sort of pages, where all user-supplied data is read from within a single method. It helps organizing the code, but most of all it enforces a clean class logic that does not start reading user input at random places, including the risk to only escape the input of variable $_GET['foo'] 4 out of 5 times. Reading and processing the data is only half the story, now we need a template to display the actual content for our page. You don't need to specify it yourself, it will be automatically guessed based on your namespace and class name, you can read more about it later . Last but not least, you must not include the closing PHP tag ?> at the end, it can cause PHP to break on whitespaces and is not required at all. The Template # Navigate back to the root directory of your package until you see both the files directory and the package.xml . Now create a directory called templates , open it and create the file test.tpl . 1 2 3 4 5 6 7 { include file = 'header' } <div class=\"section\"> Hello { $greet } ! </div> { include file = 'footer' } Templates are a mixture of HTML and Smarty-like template scripting to overcome the static nature of raw HTML. The above code will display the phrase Hello World! in the application frame, just as any other page would render. The included templates header and footer are responsible for the majority of the overall page functionality, but offer a whole lot of customization abilities to influence their behavior and appearance. The Page Definition # The package now contains the PHP class and the matching template, but it is still missing the page definition. Please create the file page.xml in your project's root directory, thus on the same level as the package.xml . 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/page.xsd\" > <import> <page identifier= \"com.example.test.Test\" > <controller> wcf\\page\\TestPage </controller> <name language= \"en\" > Test Page </name> <pageType> system </pageType> </page> </import> </data> You can provide a lot more data for a page, including logical nesting and dedicated handler classes for display in menus. Building the Package # If you have followed the above guidelines carefully, your package directory should now look like this: 1 2 3 4 5 6 7 8 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 TestPage.class.php \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u2514\u2500\u2500 templates \u2514\u2500\u2500 test.tpl Both files and templates are archive-based package components, that deploy their payload using tar archives rather than adding the raw files to the package file. Please create the archive files.tar and add the contents of the files/* directory, but not the directory files/ itself. Repeat the same process for the templates directory, but this time with the file name templates.tar . Place both files in the root of your project. Last but not least, create the package archive com.example.test.tar and add all the files listed below. files.tar package.xml page.xml templates.tar The archive's filename can be anything you want, all though it is the general convention to use the package name itself for easier recognition. Installation # Open the Administration Control Panel and navigate to Configuration > Packages > Install Package , click on Upload Package and select the file com.example.test.tar from your disk. Follow the on-screen instructions until it has been successfully installed. Open a new browser tab and navigate to your newly created page. If WoltLab Suite is installed at https://example.com/wsc/ , then the URL should read https://example.com/wsc/index.php?test/ . Congratulations, you have just created your first package! Developer Tools # The developer tools provide an interface to synchronize the data of an installed package with a bare repository on the local disk. You can re-import most PIPs at any time and have the changes applied without crafting a manual update. This process simulates a regular package update with a single PIP only, and resets the cache after the import has been completed. Registering a Project # Projects require the absolute path to the package directory, that is, the directory where it can find the package.xml . It is not required to install an package to register it as a project, but you have to install it in order to work with it. It does not install the package by itself! There is a special button on the project list that allows for a mass-import of projects based on a search path. Each direct child directory of the provided path will be tested and projects created this way will use the identifier extracted from the package.xml . Synchronizing # The install instructions in the package.xml are ignored when offering the PIP imports, the detection works entirely based on the default filename for each PIP. On top of that, only PIPs that implement the interface wcf\\system\\devtools\\pip\\IIdempotentPackageInstallationPlugin are valid for import, as it indicates that importing the PIP multiple times will have no side-effects and that the result is deterministic regardless of the number of times it has been imported. Some built-in PIPs, such as sql or script , do not qualify for this step and remain unavailable at all times. However, you can still craft and perform an actual package update to have these PIPs executed. Appendix # Template Guessing # The class name including the namespace is used to automatically determine the path to the template and its name. The example above used the page class name wcf\\page\\TestPage that is then split into four distinct parts: wcf , the internal abbreviation of WoltLab Suite Core (previously known as WoltLab Community Framework) \\page\\ (ignored) Test , the actual name that is used for both the template and the URL Page (page type, ignored) The fragments 1. and 3. from above are used to construct the path to the template: <installDirOfWSC>/templates/test.tpl (the first letter of Test is being converted to lower-case).","title":"Getting Started"},{"location":"getting-started/#creating-a-simple-package","text":"","title":"Creating a simple package"},{"location":"getting-started/#setup-and-requirements","text":"This guide will help you to create a simple package that provides a simple test page. It is nothing too fancy, but you can use it as the foundation for your next project. There are some requirements you should met before starting: Text editor with syntax highlighting for PHP, Notepad++ is a solid pick *.php and *.tpl should be encoded with ANSI/ASCII *.xml are always encoded with UTF-8, but omit the BOM (byte-order-mark) Use tabs instead of spaces to indent lines It is recommended to set the tab width to 8 spaces, this is used in the entire software and will ease reading the source files An active installation of WoltLab Suite An application to create *.tar archives, e.g. 7-Zip on Windows","title":"Setup and Requirements"},{"location":"getting-started/#the-packagexml-file","text":"We want to create a simple page that will display the sentence \"Hello World\" embedded into the application frame. Create an empty directory in the workspace of your choice to start with. Create a new file called package.xml and insert the code below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/package.xsd\" name= \"com.example.test\" > <packageinformation> <!-- com.example.test --> <packagename> Simple Package </packagename> <packagedescription> A simple package to demonstrate the package system of WoltLab Suite Core </packagedescription> <version> 1.0.0 </version> <date> 2019-04-28 </date> </packageinformation> <authorinformation> <author> Your Name </author> <authorurl> http://www.example.com </authorurl> </authorinformation> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"template\" /> <instruction type= \"page\" /> </instructions> </package> There is an entire chapter on the package system that explains what the code above does and how you can adjust it to fit your needs. For now we'll keep it as it is.","title":"The package.xml File"},{"location":"getting-started/#the-php-class","text":"The next step is to create the PHP class which will serve our page: Create the directory files in the same directory where package.xml is located Open files and create the directory lib Open lib and create the directory page Within the directory page , please create the file TestPage.class.php Copy and paste the following code into the TestPage.class.php : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <? php namespace wcf\\page ; use wcf\\system\\WCF ; /** * A simple test page for demonstration purposes. * * @author YOUR NAME * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> */ class TestPage extends AbstractPage { /** * @var string */ protected $greet = '' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_GET [ 'greet' ])) $this -> greet = $_GET [ 'greet' ]; } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( empty ( $this -> greet )) { $this -> greet = 'World' ; } } /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'greet' => $this -> greet ]); } } The class inherits from wcf\\page\\AbstractPage , the default implementation of pages without form controls. It defines quite a few methods that will be automatically invoked in a specific order, for example readParameters() before readData() and finally assignVariables() to pass arbitrary values to the template. The property $greet is defined as World , but can optionally be populated through a GET variable ( index.php?test/&greet=You would output Hello You! ). This extra code illustrates the separation of data processing that takes place within all sort of pages, where all user-supplied data is read from within a single method. It helps organizing the code, but most of all it enforces a clean class logic that does not start reading user input at random places, including the risk to only escape the input of variable $_GET['foo'] 4 out of 5 times. Reading and processing the data is only half the story, now we need a template to display the actual content for our page. You don't need to specify it yourself, it will be automatically guessed based on your namespace and class name, you can read more about it later . Last but not least, you must not include the closing PHP tag ?> at the end, it can cause PHP to break on whitespaces and is not required at all.","title":"The PHP Class"},{"location":"getting-started/#the-template","text":"Navigate back to the root directory of your package until you see both the files directory and the package.xml . Now create a directory called templates , open it and create the file test.tpl . 1 2 3 4 5 6 7 { include file = 'header' } <div class=\"section\"> Hello { $greet } ! </div> { include file = 'footer' } Templates are a mixture of HTML and Smarty-like template scripting to overcome the static nature of raw HTML. The above code will display the phrase Hello World! in the application frame, just as any other page would render. The included templates header and footer are responsible for the majority of the overall page functionality, but offer a whole lot of customization abilities to influence their behavior and appearance.","title":"The Template"},{"location":"getting-started/#the-page-definition","text":"The package now contains the PHP class and the matching template, but it is still missing the page definition. Please create the file page.xml in your project's root directory, thus on the same level as the package.xml . 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/page.xsd\" > <import> <page identifier= \"com.example.test.Test\" > <controller> wcf\\page\\TestPage </controller> <name language= \"en\" > Test Page </name> <pageType> system </pageType> </page> </import> </data> You can provide a lot more data for a page, including logical nesting and dedicated handler classes for display in menus.","title":"The Page Definition"},{"location":"getting-started/#building-the-package","text":"If you have followed the above guidelines carefully, your package directory should now look like this: 1 2 3 4 5 6 7 8 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 TestPage.class.php \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u2514\u2500\u2500 templates \u2514\u2500\u2500 test.tpl Both files and templates are archive-based package components, that deploy their payload using tar archives rather than adding the raw files to the package file. Please create the archive files.tar and add the contents of the files/* directory, but not the directory files/ itself. Repeat the same process for the templates directory, but this time with the file name templates.tar . Place both files in the root of your project. Last but not least, create the package archive com.example.test.tar and add all the files listed below. files.tar package.xml page.xml templates.tar The archive's filename can be anything you want, all though it is the general convention to use the package name itself for easier recognition.","title":"Building the Package"},{"location":"getting-started/#installation","text":"Open the Administration Control Panel and navigate to Configuration > Packages > Install Package , click on Upload Package and select the file com.example.test.tar from your disk. Follow the on-screen instructions until it has been successfully installed. Open a new browser tab and navigate to your newly created page. If WoltLab Suite is installed at https://example.com/wsc/ , then the URL should read https://example.com/wsc/index.php?test/ . Congratulations, you have just created your first package!","title":"Installation"},{"location":"getting-started/#developer-tools","text":"The developer tools provide an interface to synchronize the data of an installed package with a bare repository on the local disk. You can re-import most PIPs at any time and have the changes applied without crafting a manual update. This process simulates a regular package update with a single PIP only, and resets the cache after the import has been completed.","title":"Developer Tools"},{"location":"getting-started/#registering-a-project","text":"Projects require the absolute path to the package directory, that is, the directory where it can find the package.xml . It is not required to install an package to register it as a project, but you have to install it in order to work with it. It does not install the package by itself! There is a special button on the project list that allows for a mass-import of projects based on a search path. Each direct child directory of the provided path will be tested and projects created this way will use the identifier extracted from the package.xml .","title":"Registering a Project"},{"location":"getting-started/#synchronizing","text":"The install instructions in the package.xml are ignored when offering the PIP imports, the detection works entirely based on the default filename for each PIP. On top of that, only PIPs that implement the interface wcf\\system\\devtools\\pip\\IIdempotentPackageInstallationPlugin are valid for import, as it indicates that importing the PIP multiple times will have no side-effects and that the result is deterministic regardless of the number of times it has been imported. Some built-in PIPs, such as sql or script , do not qualify for this step and remain unavailable at all times. However, you can still craft and perform an actual package update to have these PIPs executed.","title":"Synchronizing"},{"location":"getting-started/#appendix","text":"","title":"Appendix"},{"location":"getting-started/#template-guessing","text":"The class name including the namespace is used to automatically determine the path to the template and its name. The example above used the page class name wcf\\page\\TestPage that is then split into four distinct parts: wcf , the internal abbreviation of WoltLab Suite Core (previously known as WoltLab Community Framework) \\page\\ (ignored) Test , the actual name that is used for both the template and the URL Page (page type, ignored) The fragments 1. and 3. from above are used to construct the path to the template: <installDirOfWSC>/templates/test.tpl (the first letter of Test is being converted to lower-case).","title":"Template Guessing"},{"location":"javascript/code-snippets/","text":"Code Snippets - JavaScript API # This is a list of code snippets that do not fit into any of the other articles and merely describe how to achieve something very specific, rather than explaining the inner workings of a function. ImageViewer # The ImageViewer is available on all frontend pages by default, you can easily add images to the viewer by wrapping the thumbnails with a link with the CSS class jsImageViewer that points to the full version. 1 2 3 < a href = \"http://example.com/full.jpg\" class = \"jsImageViewer\" > < img src = \"http://example.com/thumbnail.jpg\" > </ a >","title":"Code Snippets"},{"location":"javascript/code-snippets/#code-snippets-javascript-api","text":"This is a list of code snippets that do not fit into any of the other articles and merely describe how to achieve something very specific, rather than explaining the inner workings of a function.","title":"Code Snippets - JavaScript API"},{"location":"javascript/code-snippets/#imageviewer","text":"The ImageViewer is available on all frontend pages by default, you can easily add images to the viewer by wrapping the thumbnails with a link with the CSS class jsImageViewer that points to the full version. 1 2 3 < a href = \"http://example.com/full.jpg\" class = \"jsImageViewer\" > < img src = \"http://example.com/thumbnail.jpg\" > </ a >","title":"ImageViewer"},{"location":"javascript/general-usage/","text":"General JavaScript Usage # WoltLab Suite 5.4 introduced support for TypeScript, migrating all existing modules to TypeScript. The JavaScript section of the documentation is not yet updated to account for the changes, possibly explaining concepts that cannot be applied as-is when writing TypeScript. You can learn about basic TypeScript use in WoltLab Suite, such as consuming WoltLab Suite\u2019s types in own packages, within in the TypeScript section . The History of the Legacy API # The WoltLab Suite 3.0 introduced a new API based on AMD-Modules with ES5-JavaScript that was designed with high performance and visible dependencies in mind. This was a fundamental change in comparison to the legacy API that was build many years before while jQuery was still a thing and we had to deal with ancient browsers such as Internet Explorer 9 that felt short in both CSS and JavaScript capabilities. Fast forward a few years, the old API is still around and most important, it is actively being used by some components that have not been rewritten yet. This has been done to preserve the backwards-compatibility and to avoid the significant amount of work that it requires to rewrite a component. The components invoked on page initialization have all been rewritten to use the modern API, but some deferred objects that are invoked later during the page runtime may still use the old API. However, the legacy API is deprecated and you should not rely on it for new components at all. It slowly but steadily gets replaced up until a point where its last bits are finally removed from the code base. Embedding JavaScript inside Templates # The <script> -tags are extracted and moved during template processing, eventually placing them at the very end of the body element while preserving their order of appearance. This behavior is controlled through the data-relocate=\"true\" attribute on the <script> which is mandatory for almost all scripts, mostly because their dependencies (such as jQuery) are moved to the bottom anyway. 1 2 3 4 5 6 7 8 9 10 11 12 13 < script data-relocate = \"true\" > $ ( function () { // Code that uses jQuery (Legacy API) }); </ script > <!-- or --> < script data-relocate = \"true\" > require ([ \"Some\" , \"Dependencies\" ], function ( Some , Dependencies ) { // Modern API }); </ script > Including External JavaScript Files # The AMD-Modules used in the new API are automatically recognized and lazy-loaded on demand, so unless you have a rather large and pre-compiled code-base, there is nothing else to worry about. Debug-Variants and Cache-Buster # Your JavaScript files may change over time and you would want the users' browsers to always load and use the latest version of your files. This can be achieved by appending the special LAST_UPDATE_TIME constant to your file path. It contains the unix timestamp of the last time any package was installed, updated or removed and thus avoid outdated caches by relying on a unique value, without invalidating the cache more often that it needs to be. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App.js?t={@LAST_UPDATE_TIME}\" ></ script > For small scripts you can simply serve the full, non-minified version to the user at all times, the differences in size and execution speed are insignificant and are very unlikely to offer any benefits. They might even yield a worse performance, because you'll have to include them statically in the template, even if the code is never called. However, if you're including a minified build in your app or plugin, you should include a switch to load the uncompressed version in the debug mode, while serving the minified and optimized file to the average visitor. You should use the ENABLE_DEBUG_MODE constant to decide which version should be loaded. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App{if !ENABLE_DEBUG_MODE}.min{/if}.js?t={@LAST_UPDATE_TIME}\" ></ script > The Accelerated Guest View (\"Tiny Builds\") # You can learn more on the Accelerated Guest View in the migration docs. The \u201cAccelerated Guest View\u201d aims to decrease page size and to improve responsiveness by enabling a read-only mode for visitors. If you are providing a separate compiled build for this mode, you'll need to include yet another switch to serve the right version to the visitor. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App{if !ENABLE_DEBUG_MODE}{if VISITOR_USE_TINY_BUILD}.tiny{/if}.min{/if}.js?t={@LAST_UPDATE_TIME}\" ></ script > The {js} Template Plugin # The {js} template plugin exists solely to provide a much easier and less error-prone method to include external JavaScript files. 1 {js application='app' file='App' hasTiny=true} The hasTiny attribute is optional, you can set it to false or just omit it entirely if you do not provide a tiny build for your file.","title":"General Usage"},{"location":"javascript/general-usage/#general-javascript-usage","text":"WoltLab Suite 5.4 introduced support for TypeScript, migrating all existing modules to TypeScript. The JavaScript section of the documentation is not yet updated to account for the changes, possibly explaining concepts that cannot be applied as-is when writing TypeScript. You can learn about basic TypeScript use in WoltLab Suite, such as consuming WoltLab Suite\u2019s types in own packages, within in the TypeScript section .","title":"General JavaScript Usage"},{"location":"javascript/general-usage/#the-history-of-the-legacy-api","text":"The WoltLab Suite 3.0 introduced a new API based on AMD-Modules with ES5-JavaScript that was designed with high performance and visible dependencies in mind. This was a fundamental change in comparison to the legacy API that was build many years before while jQuery was still a thing and we had to deal with ancient browsers such as Internet Explorer 9 that felt short in both CSS and JavaScript capabilities. Fast forward a few years, the old API is still around and most important, it is actively being used by some components that have not been rewritten yet. This has been done to preserve the backwards-compatibility and to avoid the significant amount of work that it requires to rewrite a component. The components invoked on page initialization have all been rewritten to use the modern API, but some deferred objects that are invoked later during the page runtime may still use the old API. However, the legacy API is deprecated and you should not rely on it for new components at all. It slowly but steadily gets replaced up until a point where its last bits are finally removed from the code base.","title":"The History of the Legacy API"},{"location":"javascript/general-usage/#embedding-javascript-inside-templates","text":"The <script> -tags are extracted and moved during template processing, eventually placing them at the very end of the body element while preserving their order of appearance. This behavior is controlled through the data-relocate=\"true\" attribute on the <script> which is mandatory for almost all scripts, mostly because their dependencies (such as jQuery) are moved to the bottom anyway. 1 2 3 4 5 6 7 8 9 10 11 12 13 < script data-relocate = \"true\" > $ ( function () { // Code that uses jQuery (Legacy API) }); </ script > <!-- or --> < script data-relocate = \"true\" > require ([ \"Some\" , \"Dependencies\" ], function ( Some , Dependencies ) { // Modern API }); </ script >","title":"Embedding JavaScript inside Templates"},{"location":"javascript/general-usage/#including-external-javascript-files","text":"The AMD-Modules used in the new API are automatically recognized and lazy-loaded on demand, so unless you have a rather large and pre-compiled code-base, there is nothing else to worry about.","title":"Including External JavaScript Files"},{"location":"javascript/general-usage/#debug-variants-and-cache-buster","text":"Your JavaScript files may change over time and you would want the users' browsers to always load and use the latest version of your files. This can be achieved by appending the special LAST_UPDATE_TIME constant to your file path. It contains the unix timestamp of the last time any package was installed, updated or removed and thus avoid outdated caches by relying on a unique value, without invalidating the cache more often that it needs to be. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App.js?t={@LAST_UPDATE_TIME}\" ></ script > For small scripts you can simply serve the full, non-minified version to the user at all times, the differences in size and execution speed are insignificant and are very unlikely to offer any benefits. They might even yield a worse performance, because you'll have to include them statically in the template, even if the code is never called. However, if you're including a minified build in your app or plugin, you should include a switch to load the uncompressed version in the debug mode, while serving the minified and optimized file to the average visitor. You should use the ENABLE_DEBUG_MODE constant to decide which version should be loaded. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App{if !ENABLE_DEBUG_MODE}.min{/if}.js?t={@LAST_UPDATE_TIME}\" ></ script >","title":"Debug-Variants and Cache-Buster"},{"location":"javascript/general-usage/#the-accelerated-guest-view-tiny-builds","text":"You can learn more on the Accelerated Guest View in the migration docs. The \u201cAccelerated Guest View\u201d aims to decrease page size and to improve responsiveness by enabling a read-only mode for visitors. If you are providing a separate compiled build for this mode, you'll need to include yet another switch to serve the right version to the visitor. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App{if !ENABLE_DEBUG_MODE}{if VISITOR_USE_TINY_BUILD}.tiny{/if}.min{/if}.js?t={@LAST_UPDATE_TIME}\" ></ script >","title":"The Accelerated Guest View (\"Tiny Builds\")"},{"location":"javascript/general-usage/#the-js-template-plugin","text":"The {js} template plugin exists solely to provide a much easier and less error-prone method to include external JavaScript files. 1 {js application='app' file='App' hasTiny=true} The hasTiny attribute is optional, you can set it to false or just omit it entirely if you do not provide a tiny build for your file.","title":"The {js} Template Plugin"},{"location":"javascript/helper-functions/","text":"JavaScript Helper Functions # These helper functions are deprecated since version 5.4. Refer to our migration guide on how to replace them. Introduction # Since version 3.0, WoltLab Suite ships with a set of global helper functions that are exposed on the window -object and thus are available regardless of the context. They are meant to reduce code repetition and to increase readability by moving potentially relevant parts to the front of an instruction. Elements # elCreate(tagName: string): Element # Creates a new element with the provided tag name. 1 2 3 var element = elCreate ( \"div\" ); // equals var element = document . createElement ( \"div\" ); elRemove(element: Element) # Removes an element from its parent without returning it. This function will throw an error if the element doesn't have a parent node. 1 2 3 elRemove ( element ); // equals element . parentNode . removeChild ( element ); elShow(element: Element) # Attempts to show an element by removing the display CSS-property, usually used in conjunction with the elHide() function. 1 2 3 elShow ( element ); // equals element . style . removeProperty ( \"display\" ); elHide(element: Element) # Attempts to hide an element by setting the display CSS-property to none , this is intended to be used with elShow() that relies on this behavior. 1 2 3 elHide ( element ); // equals element . style . setProperty ( \"display\" , \"none\" , \"\" ); elToggle(element: Element) # Attempts to toggle the visibility of an element by examining the value of the display CSS-property and calls either elShow() or elHide() . Attributes # elAttr(element: Element, attribute: string, value?: string): string # Sets or reads an attribute value, value are implicitly casted into strings and reading non-existing attributes will always yield an empty string. If you want to test for attribute existence, you'll have to fall-back to the native Element.hasAttribute() method. You should read and set native attributes directly, such as img.src rather than img.getAttribute(\"src\"); . 1 2 3 4 5 6 7 var value = elAttr ( element , \"some-attribute\" ); // equals var value = element . getAttribute ( \"some-attribute\" ); elAttr ( element , \"some-attribute\" , \"some value\" ); // equals element . setAttribute ( \"some-attribute\" , \"some value\" ); elAttrBool(element: Element, attribute: string): boolean # Reads an attribute and converts it value into a boolean value, the strings \"1\" and \"true\" will evaluate to true . All other values, including a missing attribute, will return false . 1 2 3 if ( elAttrBool ( element , \"some-attribute\" )) { // attribute is true-ish } elData(element: Element, attribute: string, value?: string): string # Short-hand function to read or set HTML5 data-* -attributes, it essentially prepends the data- prefix before forwarding the call to elAttr() . 1 2 3 4 5 6 7 var value = elData ( element , \"some-attribute\" ); // equals var value = elAttr ( element , \"data-some-attribute\" ); elData ( element , \"some-attribute\" , \"some value\" ); // equals elAttr ( element , \"data-some-attribute\" , \"some value\" ); elDataBool(element: Element, attribute: string): boolean # Short-hand function to convert a HTML5 data-* -attribute into a boolean value. It prepends the data- prefix before forwarding the call to elAttrBool() . 1 2 3 4 5 6 7 if ( elDataBool ( element , \"some-attribute\" )) { // attribute is true-ish } // equals if ( elAttrBool ( element , \"data-some-attribute\" )) { // attribute is true-ish } Selecting Elements # Unlike libraries like jQuery, these functions will return null if an element is not found. You are responsible to validate if the element exist and to branch accordingly, invoking methods on the return value without checking for null will yield an error. elById(id: string): Element | null # Selects an element by its id -attribute value. 1 2 3 var element = elById ( \"my-awesome-element\" ); // equals var element = document . getElementById ( \"my-awesome-element\" ); elBySel(selector: string, context?: Element): Element | null # The underlying querySelector() -method works on the entire DOM hierarchy and can yield results outside of your context element! Please read and understand the MDN article on Element.querySelector() to learn more about this. Select a single element based on a CSS selector, optionally limiting the results to be a direct or indirect children of the context element. 1 2 3 4 5 6 7 8 var element = elBySel ( \".some-element\" ); // equals var element = document . querySelector ( \".some-element\" ); // limiting the scope to a context element: var element = elBySel ( \".some-element\" , context ); // equals var element = context . querySelector ( \".some-element\" ); elBySelAll(selector: string, context?: Element, callback: (element: Element) => void): NodeList # The underlying querySelector() -method works on the entire DOM hierarchy and can yield results outside of your context element! Please read and understand the MDN article on Element.querySelector() to learn more about this. Finds and returns a NodeList containing all elements that match the provided CSS selector. Although NodeList is an array-like structure, it is not possible to iterate over it using array functions, including .forEach() which is not available in Internet Explorer 11. 1 2 3 4 5 6 7 8 var elements = elBySelAll ( \".some-element\" ); // equals var elements = document . querySelectorAll ( \".some-element\" ); // limiting the scope to a context element: var elements = elBySelAll ( \".some-element\" , context ); // equals var elements = context . querySelectorAll ( \".some-element\" ); Callback to Iterate Over Elements # elBySelAll() supports an optional third parameter that expects a callback function that is invoked for every element in the list. 1 2 3 4 5 6 7 8 9 // set the 2nd parameter to `undefined` or `null` to query the whole document elBySelAll ( \".some-element\" , undefined , function ( element ) { // is called for each element }); // limiting the scope to a context element: elBySelAll ( \".some-element\" , context , function ( element ) { // is called for each element }); elClosest(element: Element, selector: string): Element | null # Returns the first Element that matches the provided CSS selector, this will return the provided element itself if it matches the selector. 1 2 3 var element = elClosest ( context , \".some-element\" ); // equals var element = context . closest ( \".some-element\" ); Text Nodes # If the provided context is a Text -node, the function will move the context to the parent element before applying the CSS selector. If the Text has no parent, null is returned without evaluating the selector. elByClass(className: string, context?: Element): NodeList # Returns a live NodeList containing all elements that match the provided CSS class now and in the future! The collection is automatically updated whenever an element with that class is added or removed from the DOM, it will also include elements that get dynamically assigned or removed this CSS class. You absolutely need to understand that this collection is dynamic, that means that elements can and will be added and removed from the collection even while you iterate over it. There are only very few cases where you would need such a collection, almost always elBySelAll() is what you're looking for. 1 2 3 4 5 6 7 8 9 // no leading dot! var elements = elByClass ( \"some-element\" ); // equals var elements = document . getElementsByClassName ( \"some-element\" ); // limiting the scope to a context element: var elements = elByClass ( \"some-element\" , context ); // equals var elements = context . getElementsByClassName ( \".some-element\" ); elByTag(tagName: string, context?: Element): NodeList # Returns a live NodeList containing all elements with the provided tag name now and in the future! Please read the remarks on elByClass() above to understand the implications of this. 1 2 3 4 5 6 7 8 var elements = elByTag ( \"div\" ); // equals var elements = document . getElementsByTagName ( \"div\" ); // limiting the scope to a context element: var elements = elByTag ( \"div\" , context ); // equals var elements = context . getElementsByTagName ( \"div\" ); Utility Functions # elInnerError(element: Element, errorMessage?: string, isHtml?: boolean): Element | null # Unified function to display and remove inline error messages for input elements, please read the section in the migration docs to learn more about this function. String Extensions # hashCode(): string # Computes a numeric hash value of a string similar to Java's String.hashCode() method. 1 2 console . log ( \"Hello World\" . hashCode ()); // outputs: -862545276","title":"Helper Functions"},{"location":"javascript/helper-functions/#javascript-helper-functions","text":"These helper functions are deprecated since version 5.4. Refer to our migration guide on how to replace them.","title":"JavaScript Helper Functions"},{"location":"javascript/helper-functions/#introduction","text":"Since version 3.0, WoltLab Suite ships with a set of global helper functions that are exposed on the window -object and thus are available regardless of the context. They are meant to reduce code repetition and to increase readability by moving potentially relevant parts to the front of an instruction.","title":"Introduction"},{"location":"javascript/helper-functions/#elements","text":"","title":"Elements"},{"location":"javascript/helper-functions/#elcreatetagname-string-element","text":"Creates a new element with the provided tag name. 1 2 3 var element = elCreate ( \"div\" ); // equals var element = document . createElement ( \"div\" );","title":"elCreate(tagName: string): Element"},{"location":"javascript/helper-functions/#elremoveelement-element","text":"Removes an element from its parent without returning it. This function will throw an error if the element doesn't have a parent node. 1 2 3 elRemove ( element ); // equals element . parentNode . removeChild ( element );","title":"elRemove(element: Element)"},{"location":"javascript/helper-functions/#elshowelement-element","text":"Attempts to show an element by removing the display CSS-property, usually used in conjunction with the elHide() function. 1 2 3 elShow ( element ); // equals element . style . removeProperty ( \"display\" );","title":"elShow(element: Element)"},{"location":"javascript/helper-functions/#elhideelement-element","text":"Attempts to hide an element by setting the display CSS-property to none , this is intended to be used with elShow() that relies on this behavior. 1 2 3 elHide ( element ); // equals element . style . setProperty ( \"display\" , \"none\" , \"\" );","title":"elHide(element: Element)"},{"location":"javascript/helper-functions/#eltoggleelement-element","text":"Attempts to toggle the visibility of an element by examining the value of the display CSS-property and calls either elShow() or elHide() .","title":"elToggle(element: Element)"},{"location":"javascript/helper-functions/#attributes","text":"","title":"Attributes"},{"location":"javascript/helper-functions/#elattrelement-element-attribute-string-value-string-string","text":"Sets or reads an attribute value, value are implicitly casted into strings and reading non-existing attributes will always yield an empty string. If you want to test for attribute existence, you'll have to fall-back to the native Element.hasAttribute() method. You should read and set native attributes directly, such as img.src rather than img.getAttribute(\"src\"); . 1 2 3 4 5 6 7 var value = elAttr ( element , \"some-attribute\" ); // equals var value = element . getAttribute ( \"some-attribute\" ); elAttr ( element , \"some-attribute\" , \"some value\" ); // equals element . setAttribute ( \"some-attribute\" , \"some value\" );","title":"elAttr(element: Element, attribute: string, value?: string): string"},{"location":"javascript/helper-functions/#elattrboolelement-element-attribute-string-boolean","text":"Reads an attribute and converts it value into a boolean value, the strings \"1\" and \"true\" will evaluate to true . All other values, including a missing attribute, will return false . 1 2 3 if ( elAttrBool ( element , \"some-attribute\" )) { // attribute is true-ish }","title":"elAttrBool(element: Element, attribute: string): boolean"},{"location":"javascript/helper-functions/#eldataelement-element-attribute-string-value-string-string","text":"Short-hand function to read or set HTML5 data-* -attributes, it essentially prepends the data- prefix before forwarding the call to elAttr() . 1 2 3 4 5 6 7 var value = elData ( element , \"some-attribute\" ); // equals var value = elAttr ( element , \"data-some-attribute\" ); elData ( element , \"some-attribute\" , \"some value\" ); // equals elAttr ( element , \"data-some-attribute\" , \"some value\" );","title":"elData(element: Element, attribute: string, value?: string): string"},{"location":"javascript/helper-functions/#eldataboolelement-element-attribute-string-boolean","text":"Short-hand function to convert a HTML5 data-* -attribute into a boolean value. It prepends the data- prefix before forwarding the call to elAttrBool() . 1 2 3 4 5 6 7 if ( elDataBool ( element , \"some-attribute\" )) { // attribute is true-ish } // equals if ( elAttrBool ( element , \"data-some-attribute\" )) { // attribute is true-ish }","title":"elDataBool(element: Element, attribute: string): boolean"},{"location":"javascript/helper-functions/#selecting-elements","text":"Unlike libraries like jQuery, these functions will return null if an element is not found. You are responsible to validate if the element exist and to branch accordingly, invoking methods on the return value without checking for null will yield an error.","title":"Selecting Elements"},{"location":"javascript/helper-functions/#elbyidid-string-element-null","text":"Selects an element by its id -attribute value. 1 2 3 var element = elById ( \"my-awesome-element\" ); // equals var element = document . getElementById ( \"my-awesome-element\" );","title":"elById(id: string): Element | null"},{"location":"javascript/helper-functions/#elbyselselector-string-context-element-element-null","text":"The underlying querySelector() -method works on the entire DOM hierarchy and can yield results outside of your context element! Please read and understand the MDN article on Element.querySelector() to learn more about this. Select a single element based on a CSS selector, optionally limiting the results to be a direct or indirect children of the context element. 1 2 3 4 5 6 7 8 var element = elBySel ( \".some-element\" ); // equals var element = document . querySelector ( \".some-element\" ); // limiting the scope to a context element: var element = elBySel ( \".some-element\" , context ); // equals var element = context . querySelector ( \".some-element\" );","title":"elBySel(selector: string, context?: Element): Element | null"},{"location":"javascript/helper-functions/#elbyselallselector-string-context-element-callback-element-element-void-nodelist","text":"The underlying querySelector() -method works on the entire DOM hierarchy and can yield results outside of your context element! Please read and understand the MDN article on Element.querySelector() to learn more about this. Finds and returns a NodeList containing all elements that match the provided CSS selector. Although NodeList is an array-like structure, it is not possible to iterate over it using array functions, including .forEach() which is not available in Internet Explorer 11. 1 2 3 4 5 6 7 8 var elements = elBySelAll ( \".some-element\" ); // equals var elements = document . querySelectorAll ( \".some-element\" ); // limiting the scope to a context element: var elements = elBySelAll ( \".some-element\" , context ); // equals var elements = context . querySelectorAll ( \".some-element\" );","title":"elBySelAll(selector: string, context?: Element, callback: (element: Element) => void): NodeList"},{"location":"javascript/helper-functions/#callback-to-iterate-over-elements","text":"elBySelAll() supports an optional third parameter that expects a callback function that is invoked for every element in the list. 1 2 3 4 5 6 7 8 9 // set the 2nd parameter to `undefined` or `null` to query the whole document elBySelAll ( \".some-element\" , undefined , function ( element ) { // is called for each element }); // limiting the scope to a context element: elBySelAll ( \".some-element\" , context , function ( element ) { // is called for each element });","title":"Callback to Iterate Over Elements"},{"location":"javascript/helper-functions/#elclosestelement-element-selector-string-element-null","text":"Returns the first Element that matches the provided CSS selector, this will return the provided element itself if it matches the selector. 1 2 3 var element = elClosest ( context , \".some-element\" ); // equals var element = context . closest ( \".some-element\" );","title":"elClosest(element: Element, selector: string): Element | null"},{"location":"javascript/helper-functions/#text-nodes","text":"If the provided context is a Text -node, the function will move the context to the parent element before applying the CSS selector. If the Text has no parent, null is returned without evaluating the selector.","title":"Text Nodes"},{"location":"javascript/helper-functions/#elbyclassclassname-string-context-element-nodelist","text":"Returns a live NodeList containing all elements that match the provided CSS class now and in the future! The collection is automatically updated whenever an element with that class is added or removed from the DOM, it will also include elements that get dynamically assigned or removed this CSS class. You absolutely need to understand that this collection is dynamic, that means that elements can and will be added and removed from the collection even while you iterate over it. There are only very few cases where you would need such a collection, almost always elBySelAll() is what you're looking for. 1 2 3 4 5 6 7 8 9 // no leading dot! var elements = elByClass ( \"some-element\" ); // equals var elements = document . getElementsByClassName ( \"some-element\" ); // limiting the scope to a context element: var elements = elByClass ( \"some-element\" , context ); // equals var elements = context . getElementsByClassName ( \".some-element\" );","title":"elByClass(className: string, context?: Element): NodeList"},{"location":"javascript/helper-functions/#elbytagtagname-string-context-element-nodelist","text":"Returns a live NodeList containing all elements with the provided tag name now and in the future! Please read the remarks on elByClass() above to understand the implications of this. 1 2 3 4 5 6 7 8 var elements = elByTag ( \"div\" ); // equals var elements = document . getElementsByTagName ( \"div\" ); // limiting the scope to a context element: var elements = elByTag ( \"div\" , context ); // equals var elements = context . getElementsByTagName ( \"div\" );","title":"elByTag(tagName: string, context?: Element): NodeList"},{"location":"javascript/helper-functions/#utility-functions","text":"","title":"Utility Functions"},{"location":"javascript/helper-functions/#elinnererrorelement-element-errormessage-string-ishtml-boolean-element-null","text":"Unified function to display and remove inline error messages for input elements, please read the section in the migration docs to learn more about this function.","title":"elInnerError(element: Element, errorMessage?: string, isHtml?: boolean): Element | null"},{"location":"javascript/helper-functions/#string-extensions","text":"","title":"String Extensions"},{"location":"javascript/helper-functions/#hashcode-string","text":"Computes a numeric hash value of a string similar to Java's String.hashCode() method. 1 2 console . log ( \"Hello World\" . hashCode ()); // outputs: -862545276","title":"hashCode(): string"},{"location":"javascript/legacy-api/","text":"Legacy JavaScript API # Introduction # The legacy JavaScript API is the original code that was part of the 2.x series of WoltLab Suite, formerly known as WoltLab Community Framework. It has been superseded for the most part by the ES5/AMD-modules API introduced with WoltLab Suite 3.0. Some parts still exist to this day for backwards-compatibility and because some less important components have not been rewritten yet. The old API is still supported, but marked as deprecated and will continue to be replaced parts by part in future releases, up until their entire removal, including jQuery support. This guide does not provide any explanation on the usage of those legacy components, but instead serves as a cheat sheet to convert code to use the new API. Classes # Singletons # Singleton instances are designed to provide a unique \"instance\" of an object regardless of when its first instance was created. Due to the lack of a class construct in ES5, they are represented by mere objects that act as an instance. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // App.js window . App = {}; App . Foo = { bar : function () {} }; // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; return { bar : function () {} }; }); Regular Classes # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); Inheritance # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); App . Baz = App . Foo . extend ({ makeSnafucated : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); // App/Baz.js define ([ \"Core\" , \"./Foo\" ], function ( Core , Foo ) { \"use strict\" ; function Baz () {}; Core . inherit ( Baz , Foo , { makeSnafucated : function () {} }); return Baz ; }); Ajax Requests # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // App.js App . Foo = Class . extend ({ _proxy : null , init : function () { this . _proxy = new WCF . Action . Proxy ({ success : $ . proxy ( this . _success , this ) }); }, bar : function () { this . _proxy . setOption ( \"data\" , { actionName : \"baz\" , className : \"app\\\\foo\\\\FooAction\" , objectIDs : [ 1 , 2 , 3 ], parameters : { foo : \"bar\" , baz : true } }); this . _proxy . sendRequest (); }, _success : function ( data ) { // ajax request result } }); // --- NEW API --- // App/Foo.js define ([ \"Ajax\" ], function ( Ajax ) { \"use strict\" ; function Foo () {} Foo . prototype = { bar : function () { Ajax . api ( this , { objectIDs : [ 1 , 2 , 3 ], parameters : { foo : \"bar\" , baz : true } }); }, // magic method! _ajaxSuccess : function ( data ) { // ajax request result }, // magic method! _ajaxSetup : function () { return { actionName : \"baz\" , className : \"app\\\\foo\\\\FooAction\" } } } return Foo ; }); Phrases # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < script data-relocate = \"true\" > $ ( function () { WCF . Language . addObject ({ 'app.foo.bar' : '{lang}app.foo.bar{/lang}' }); console . log ( WCF . Language . get ( \"app.foo.bar\" )); }); </ script > <!-- NEW API --> < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . addObject ({ 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' }); console . log ( Language . get ( \"app.foo.bar\" )); }); </ script > Event-Listener # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < script data-relocate = \"true\" > $ ( function () { WCF . System . Event . addListener ( \"app.foo.bar\" , \"makeSnafucated\" , function ( data ) { console . log ( \"Event was invoked.\" ); }); WCF . System . Event . fireEvent ( \"app.foo.bar\" , \"makeSnafucated\" , { some : \"data\" }); }); </ script > <!-- NEW API --> < script data-relocate = \"true\" > require ([ \"EventHandler\" ], function ( EventHandler ) { EventHandler . add ( \"app.foo.bar\" , \"makeSnafucated\" , function ( data ) { console . log ( \"Event was invoked\" ); }); EventHandler . fire ( \"app.foo.bar\" , \"makeSnafucated\" , { some : \"data\" }); }); </ script >","title":"Legacy API"},{"location":"javascript/legacy-api/#legacy-javascript-api","text":"","title":"Legacy JavaScript API"},{"location":"javascript/legacy-api/#introduction","text":"The legacy JavaScript API is the original code that was part of the 2.x series of WoltLab Suite, formerly known as WoltLab Community Framework. It has been superseded for the most part by the ES5/AMD-modules API introduced with WoltLab Suite 3.0. Some parts still exist to this day for backwards-compatibility and because some less important components have not been rewritten yet. The old API is still supported, but marked as deprecated and will continue to be replaced parts by part in future releases, up until their entire removal, including jQuery support. This guide does not provide any explanation on the usage of those legacy components, but instead serves as a cheat sheet to convert code to use the new API.","title":"Introduction"},{"location":"javascript/legacy-api/#classes","text":"","title":"Classes"},{"location":"javascript/legacy-api/#singletons","text":"Singleton instances are designed to provide a unique \"instance\" of an object regardless of when its first instance was created. Due to the lack of a class construct in ES5, they are represented by mere objects that act as an instance. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // App.js window . App = {}; App . Foo = { bar : function () {} }; // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; return { bar : function () {} }; });","title":"Singletons"},{"location":"javascript/legacy-api/#regular-classes","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; });","title":"Regular Classes"},{"location":"javascript/legacy-api/#inheritance","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); App . Baz = App . Foo . extend ({ makeSnafucated : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); // App/Baz.js define ([ \"Core\" , \"./Foo\" ], function ( Core , Foo ) { \"use strict\" ; function Baz () {}; Core . inherit ( Baz , Foo , { makeSnafucated : function () {} }); return Baz ; });","title":"Inheritance"},{"location":"javascript/legacy-api/#ajax-requests","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // App.js App . Foo = Class . extend ({ _proxy : null , init : function () { this . _proxy = new WCF . Action . Proxy ({ success : $ . proxy ( this . _success , this ) }); }, bar : function () { this . _proxy . setOption ( \"data\" , { actionName : \"baz\" , className : \"app\\\\foo\\\\FooAction\" , objectIDs : [ 1 , 2 , 3 ], parameters : { foo : \"bar\" , baz : true } }); this . _proxy . sendRequest (); }, _success : function ( data ) { // ajax request result } }); // --- NEW API --- // App/Foo.js define ([ \"Ajax\" ], function ( Ajax ) { \"use strict\" ; function Foo () {} Foo . prototype = { bar : function () { Ajax . api ( this , { objectIDs : [ 1 , 2 , 3 ], parameters : { foo : \"bar\" , baz : true } }); }, // magic method! _ajaxSuccess : function ( data ) { // ajax request result }, // magic method! _ajaxSetup : function () { return { actionName : \"baz\" , className : \"app\\\\foo\\\\FooAction\" } } } return Foo ; });","title":"Ajax Requests"},{"location":"javascript/legacy-api/#phrases","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < script data-relocate = \"true\" > $ ( function () { WCF . Language . addObject ({ 'app.foo.bar' : '{lang}app.foo.bar{/lang}' }); console . log ( WCF . Language . get ( \"app.foo.bar\" )); }); </ script > <!-- NEW API --> < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . addObject ({ 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' }); console . log ( Language . get ( \"app.foo.bar\" )); }); </ script >","title":"Phrases"},{"location":"javascript/legacy-api/#event-listener","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < script data-relocate = \"true\" > $ ( function () { WCF . System . Event . addListener ( \"app.foo.bar\" , \"makeSnafucated\" , function ( data ) { console . log ( \"Event was invoked.\" ); }); WCF . System . Event . fireEvent ( \"app.foo.bar\" , \"makeSnafucated\" , { some : \"data\" }); }); </ script > <!-- NEW API --> < script data-relocate = \"true\" > require ([ \"EventHandler\" ], function ( EventHandler ) { EventHandler . add ( \"app.foo.bar\" , \"makeSnafucated\" , function ( data ) { console . log ( \"Event was invoked\" ); }); EventHandler . fire ( \"app.foo.bar\" , \"makeSnafucated\" , { some : \"data\" }); }); </ script >","title":"Event-Listener"},{"location":"javascript/new-api_ajax/","text":"Ajax Requests - JavaScript API # Promise -based API for DatabaseObjectAction # WoltLab Suite 5.5 introduces a new API for Ajax requests that uses Promise s to control the code flow. It does not rely on references to existing objects and does not use arbitrary callbacks to handle the setup and handling of the request. Usage # MyModule.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import * as Ajax from \"./Ajax\" ; type ResponseGetLatestFoo = { template : string ; }; export class MyModule { private readonly bar : string ; private readonly objectId : number ; constructor ( objectId : number , bar : string , buttonId : string ) { this . bar = bar ; this . objectId = objectId ; const button = document . getElementById ( buttonId ); button ? . addEventListener ( \"click\" , ( event ) => void this . click ( event )); } async click ( event : MouseEvent ) : Promise < void > { event . preventDefault (); const button = event . currentTarget as HTMLElement ; if ( button . classList . contains ( \"disabled\" )) { return ; } button . classList . add ( \"disabled\" ); try { const response = ( await Ajax . dboAction ( \"getLatestFoo\" , \"wcf\\\\data\\\\foo\\\\FooAction\" ) . objectIds ([ this . objectId ]) . payload ({ bar : this.bar }) . dispatch ()) as ResponseGetLatestFoo ; document . getElementById ( \"latestFoo\" ) ! . innerHTML = response . template ; } finally { button . classList . remove ( \"disabled\" ); } } } export default MyModule ; The actual code to dispatch and evaluate a request is only four lines long and offers full IDE auto completion support. This example uses a finally block to reset the button class once the request has finished, regardless of the result. If you do not handle the errors (or chose not to handle some errors), the global rejection handler will take care of this and show an dialog that informs about the failed request. This mimics the behavior of the _ajaxFailure() callback in the legacy API. Aborting in-flight requests # Sometimes new requests are dispatched against the same API before the response from the previous has arrived. This applies to either long running requests or requests that are dispatched in rapid succession, for example, looking up values when the user is actively typing into a search field. RapidRequests.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import * as Ajax from \"./Ajax\" ; export class RapidRequests { private lastRequest : AbortController | undefined = undefined ; constructor ( inputId : string ) { const input = document . getElementById ( inputId ) as HTMLInputElement ; input . addEventListener ( \"input\" , ( event ) => void this . input ( event )); } async input ( event : Event ) : Promise < void > { event . preventDefault (); const input = event . currentTarget as HTMLInputElement ; const value = input . value . trim (); if ( this . lastRequest ) { this . lastRequest . abort (); } if ( value ) { const request = Ajax . dboAction ( \"getSuggestions\" , \"wcf\\\\data\\\\bar\\\\BarAction\" ). payload ({ value }); this . lastRequest = request . getAbortController (); const response = await request . dispatch (); // Handle the response } } } export default RapidRequests ; Ajax inside Modules (Legacy API) # The Ajax component was designed to be used from inside modules where an object reference is used to delegate request callbacks. This is acomplished through a set of magic methods that are automatically called when the request is created or its state has changed. _ajaxSetup() # The lazy initialization is performed upon the first invocation from the callee, using the magic _ajaxSetup() method to retrieve the basic configuration for this and any future requests. The data returned by _ajaxSetup() is cached and the data will be used to pre-populate the request data before sending it. The callee can overwrite any of these properties. It is intended to reduce the overhead when issuing request when these requests share the same properties, such as accessing the same endpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // App/Foo.js define ([ \"Ajax\" ], function ( Ajax ) { \"use strict\" ; function Foo () {}; Foo . prototype = { one : function () { // this will issue an ajax request with the parameter `value` set to `1` Ajax . api ( this ); }, two : function () { // this request is almost identical to the one issued with `.one()`, but // the value is now set to `2` for this invocation only. Ajax . api ( this , { parameters : { value : 2 } }); }, _ajaxSetup : function () { return { data : { actionName : \"makeSnafucated\" , className : \"app\\\\data\\\\foo\\\\FooAction\" , parameters : { value : 1 } } } } }; return Foo ; }); Request Settings # The object returned by the aforementioned _ajaxSetup() callback can contain these values: data # Defaults to {} . A plain JavaScript object that contains the request data that represents the form data of the request. The parameters key is recognized by the PHP Ajax API and becomes accessible through $this->parameters . contentType # Defaults to application/x-www-form-urlencoded; charset=UTF-8 . The request content type, sets the Content-Type HTTP header if it is not empty. responseType # Defaults to application/json . The server must respond with the Content-Type HTTP header set to this value, otherwise the request will be treated as failed. Requests for application/json will have the return body attempted to be evaluated as JSON. Other content types will only be validated based on the HTTP header, but no additional transformation is performed. For example, setting the responseType to application/xml will check the HTTP header, but will not transform the data parameter, you'll still receive a string in _ajaxSuccess ! type # Defaults to POST . The HTTP Verb used for this request. url # Defaults to an empty string. Manual override for the request endpoint, it will be automatically set to the Core API endpoint if left empty. If the Core API endpoint is used, the options includeRequestedWith and withCredentials will be force-set to true. withCredentials # Enabling this parameter for any domain other than the current will trigger a CORS preflight request. Defaults to false . Include cookies with this requested, is always true when url is (implicitly) set to the Core API endpoint. autoAbort # Defaults to false . When set to true , any pending responses to earlier requests will be silently discarded when issuing a new request. This only makes sense if the new request is meant to completely replace the result of the previous one, regardless of its reponse body. Typical use-cases include input field with suggestions, where possible values are requested from the server, but the input changed faster than the server was able to reply. In this particular case the client is not interested in the result for an earlier value, auto-aborting these requests avoids implementing this logic in the requesting code. ignoreError # Defaults to false . Any failing request will invoke the failure -callback to check if an error message should be displayed. Enabling this option will suppress the general error overlay that reports a failed request. You can achieve the same result by returning false in the failure -callback. silent # Defaults to false . Enabling this option will suppress the loading indicator overlay for this request, other non-\"silent\" requests will still trigger the loading indicator. includeRequestedWith # Enabling this parameter for any domain other than the current will trigger a CORS preflight request. Defaults to true . Sets the custom HTTP header X-Requested-With: XMLHttpRequest for the request, it is automatically set to true when url is pointing at the WSC API endpoint. failure # Defaults to null . Optional callback function that will be invoked for requests that have failed for one of these reasons: 1. The request timed out. 2. The HTTP status is not 2xx or 304 . 3. A responseType was set, but the response HTTP header Content-Type did not match the expected value. 4. The responseType was set to application/json , but the response body was not valid JSON. The callback function receives the parameter xhr (the XMLHttpRequest object) and options (deep clone of the request parameters). If the callback returns false , the general error overlay for failed requests will be suppressed. There will be no error overlay if ignoreError is set to true or if the request failed while attempting to evaluate the response body as JSON. finalize # Defaults to null . Optional callback function that will be invoked once the request has completed, regardless if it succeeded or failed. The only parameter it receives is options (the request parameters object), but it does not receive the request's XMLHttpRequest . success # Defaults to null . This semi-optional callback function will always be set to _ajaxSuccess() when invoking Ajax.api() . It receives four parameters: 1. data - The request's response body as a string, or a JavaScript object if contentType was set to application/json . 2. responseText - The unmodified response body, it equals the value for data for non-JSON requests. 3. xhr - The underlying XMLHttpRequest object. 4. requestData - The request parameters that were supplied when the request was issued. _ajaxSuccess() # This callback method is automatically called for successful AJAX requests, it receives four parameters, with the first one containing either the response body as a string, or a JavaScript object for JSON requests. _ajaxFailure() # Optional callback function that is invoked for failed requests, it will be automatically called if the callee implements it, otherwise the global error handler will be executed. Single Requests Without a Module (Legacy API) # The Ajax.api() method expects an object that is used to extract the request configuration as well as providing the callback functions when the request state changes. You can issue a simple Ajax request without object binding through Ajax.apiOnce() that will destroy the instance after the request was finalized. This method is significantly more expensive for repeated requests and does not offer deriving modules from altering the behavior. It is strongly recommended to always use Ajax.api() for requests to the WSC API endpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 < script data-relocate = \"true\" > require ([ \"Ajax\" ], function ( Ajax ) { Ajax . apiOnce ({ data : { actionName : \"makeSnafucated\" , className : \"app\\\\data\\\\foo\\\\FooAction\" , parameters : { value : 3 } }, success : function ( data ) { elBySel ( \".some-element\" ). textContent = data . bar ; } }) }); </ script >","title":"Ajax"},{"location":"javascript/new-api_ajax/#ajax-requests-javascript-api","text":"","title":"Ajax Requests - JavaScript API"},{"location":"javascript/new-api_ajax/#promise-based-api-for-databaseobjectaction","text":"WoltLab Suite 5.5 introduces a new API for Ajax requests that uses Promise s to control the code flow. It does not rely on references to existing objects and does not use arbitrary callbacks to handle the setup and handling of the request.","title":"Promise-based API for DatabaseObjectAction"},{"location":"javascript/new-api_ajax/#usage","text":"MyModule.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import * as Ajax from \"./Ajax\" ; type ResponseGetLatestFoo = { template : string ; }; export class MyModule { private readonly bar : string ; private readonly objectId : number ; constructor ( objectId : number , bar : string , buttonId : string ) { this . bar = bar ; this . objectId = objectId ; const button = document . getElementById ( buttonId ); button ? . addEventListener ( \"click\" , ( event ) => void this . click ( event )); } async click ( event : MouseEvent ) : Promise < void > { event . preventDefault (); const button = event . currentTarget as HTMLElement ; if ( button . classList . contains ( \"disabled\" )) { return ; } button . classList . add ( \"disabled\" ); try { const response = ( await Ajax . dboAction ( \"getLatestFoo\" , \"wcf\\\\data\\\\foo\\\\FooAction\" ) . objectIds ([ this . objectId ]) . payload ({ bar : this.bar }) . dispatch ()) as ResponseGetLatestFoo ; document . getElementById ( \"latestFoo\" ) ! . innerHTML = response . template ; } finally { button . classList . remove ( \"disabled\" ); } } } export default MyModule ; The actual code to dispatch and evaluate a request is only four lines long and offers full IDE auto completion support. This example uses a finally block to reset the button class once the request has finished, regardless of the result. If you do not handle the errors (or chose not to handle some errors), the global rejection handler will take care of this and show an dialog that informs about the failed request. This mimics the behavior of the _ajaxFailure() callback in the legacy API.","title":"Usage"},{"location":"javascript/new-api_ajax/#aborting-in-flight-requests","text":"Sometimes new requests are dispatched against the same API before the response from the previous has arrived. This applies to either long running requests or requests that are dispatched in rapid succession, for example, looking up values when the user is actively typing into a search field. RapidRequests.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import * as Ajax from \"./Ajax\" ; export class RapidRequests { private lastRequest : AbortController | undefined = undefined ; constructor ( inputId : string ) { const input = document . getElementById ( inputId ) as HTMLInputElement ; input . addEventListener ( \"input\" , ( event ) => void this . input ( event )); } async input ( event : Event ) : Promise < void > { event . preventDefault (); const input = event . currentTarget as HTMLInputElement ; const value = input . value . trim (); if ( this . lastRequest ) { this . lastRequest . abort (); } if ( value ) { const request = Ajax . dboAction ( \"getSuggestions\" , \"wcf\\\\data\\\\bar\\\\BarAction\" ). payload ({ value }); this . lastRequest = request . getAbortController (); const response = await request . dispatch (); // Handle the response } } } export default RapidRequests ;","title":"Aborting in-flight requests"},{"location":"javascript/new-api_ajax/#ajax-inside-modules-legacy-api","text":"The Ajax component was designed to be used from inside modules where an object reference is used to delegate request callbacks. This is acomplished through a set of magic methods that are automatically called when the request is created or its state has changed.","title":"Ajax inside Modules (Legacy API)"},{"location":"javascript/new-api_ajax/#_ajaxsetup","text":"The lazy initialization is performed upon the first invocation from the callee, using the magic _ajaxSetup() method to retrieve the basic configuration for this and any future requests. The data returned by _ajaxSetup() is cached and the data will be used to pre-populate the request data before sending it. The callee can overwrite any of these properties. It is intended to reduce the overhead when issuing request when these requests share the same properties, such as accessing the same endpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // App/Foo.js define ([ \"Ajax\" ], function ( Ajax ) { \"use strict\" ; function Foo () {}; Foo . prototype = { one : function () { // this will issue an ajax request with the parameter `value` set to `1` Ajax . api ( this ); }, two : function () { // this request is almost identical to the one issued with `.one()`, but // the value is now set to `2` for this invocation only. Ajax . api ( this , { parameters : { value : 2 } }); }, _ajaxSetup : function () { return { data : { actionName : \"makeSnafucated\" , className : \"app\\\\data\\\\foo\\\\FooAction\" , parameters : { value : 1 } } } } }; return Foo ; });","title":"_ajaxSetup()"},{"location":"javascript/new-api_ajax/#request-settings","text":"The object returned by the aforementioned _ajaxSetup() callback can contain these values:","title":"Request Settings"},{"location":"javascript/new-api_ajax/#data","text":"Defaults to {} . A plain JavaScript object that contains the request data that represents the form data of the request. The parameters key is recognized by the PHP Ajax API and becomes accessible through $this->parameters .","title":"data"},{"location":"javascript/new-api_ajax/#contenttype","text":"Defaults to application/x-www-form-urlencoded; charset=UTF-8 . The request content type, sets the Content-Type HTTP header if it is not empty.","title":"contentType"},{"location":"javascript/new-api_ajax/#responsetype","text":"Defaults to application/json . The server must respond with the Content-Type HTTP header set to this value, otherwise the request will be treated as failed. Requests for application/json will have the return body attempted to be evaluated as JSON. Other content types will only be validated based on the HTTP header, but no additional transformation is performed. For example, setting the responseType to application/xml will check the HTTP header, but will not transform the data parameter, you'll still receive a string in _ajaxSuccess !","title":"responseType"},{"location":"javascript/new-api_ajax/#type","text":"Defaults to POST . The HTTP Verb used for this request.","title":"type"},{"location":"javascript/new-api_ajax/#url","text":"Defaults to an empty string. Manual override for the request endpoint, it will be automatically set to the Core API endpoint if left empty. If the Core API endpoint is used, the options includeRequestedWith and withCredentials will be force-set to true.","title":"url"},{"location":"javascript/new-api_ajax/#withcredentials","text":"Enabling this parameter for any domain other than the current will trigger a CORS preflight request. Defaults to false . Include cookies with this requested, is always true when url is (implicitly) set to the Core API endpoint.","title":"withCredentials"},{"location":"javascript/new-api_ajax/#autoabort","text":"Defaults to false . When set to true , any pending responses to earlier requests will be silently discarded when issuing a new request. This only makes sense if the new request is meant to completely replace the result of the previous one, regardless of its reponse body. Typical use-cases include input field with suggestions, where possible values are requested from the server, but the input changed faster than the server was able to reply. In this particular case the client is not interested in the result for an earlier value, auto-aborting these requests avoids implementing this logic in the requesting code.","title":"autoAbort"},{"location":"javascript/new-api_ajax/#ignoreerror","text":"Defaults to false . Any failing request will invoke the failure -callback to check if an error message should be displayed. Enabling this option will suppress the general error overlay that reports a failed request. You can achieve the same result by returning false in the failure -callback.","title":"ignoreError"},{"location":"javascript/new-api_ajax/#silent","text":"Defaults to false . Enabling this option will suppress the loading indicator overlay for this request, other non-\"silent\" requests will still trigger the loading indicator.","title":"silent"},{"location":"javascript/new-api_ajax/#includerequestedwith","text":"Enabling this parameter for any domain other than the current will trigger a CORS preflight request. Defaults to true . Sets the custom HTTP header X-Requested-With: XMLHttpRequest for the request, it is automatically set to true when url is pointing at the WSC API endpoint.","title":"includeRequestedWith"},{"location":"javascript/new-api_ajax/#failure","text":"Defaults to null . Optional callback function that will be invoked for requests that have failed for one of these reasons: 1. The request timed out. 2. The HTTP status is not 2xx or 304 . 3. A responseType was set, but the response HTTP header Content-Type did not match the expected value. 4. The responseType was set to application/json , but the response body was not valid JSON. The callback function receives the parameter xhr (the XMLHttpRequest object) and options (deep clone of the request parameters). If the callback returns false , the general error overlay for failed requests will be suppressed. There will be no error overlay if ignoreError is set to true or if the request failed while attempting to evaluate the response body as JSON.","title":"failure"},{"location":"javascript/new-api_ajax/#finalize","text":"Defaults to null . Optional callback function that will be invoked once the request has completed, regardless if it succeeded or failed. The only parameter it receives is options (the request parameters object), but it does not receive the request's XMLHttpRequest .","title":"finalize"},{"location":"javascript/new-api_ajax/#success","text":"Defaults to null . This semi-optional callback function will always be set to _ajaxSuccess() when invoking Ajax.api() . It receives four parameters: 1. data - The request's response body as a string, or a JavaScript object if contentType was set to application/json . 2. responseText - The unmodified response body, it equals the value for data for non-JSON requests. 3. xhr - The underlying XMLHttpRequest object. 4. requestData - The request parameters that were supplied when the request was issued.","title":"success"},{"location":"javascript/new-api_ajax/#_ajaxsuccess","text":"This callback method is automatically called for successful AJAX requests, it receives four parameters, with the first one containing either the response body as a string, or a JavaScript object for JSON requests.","title":"_ajaxSuccess()"},{"location":"javascript/new-api_ajax/#_ajaxfailure","text":"Optional callback function that is invoked for failed requests, it will be automatically called if the callee implements it, otherwise the global error handler will be executed.","title":"_ajaxFailure()"},{"location":"javascript/new-api_ajax/#single-requests-without-a-module-legacy-api","text":"The Ajax.api() method expects an object that is used to extract the request configuration as well as providing the callback functions when the request state changes. You can issue a simple Ajax request without object binding through Ajax.apiOnce() that will destroy the instance after the request was finalized. This method is significantly more expensive for repeated requests and does not offer deriving modules from altering the behavior. It is strongly recommended to always use Ajax.api() for requests to the WSC API endpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 < script data-relocate = \"true\" > require ([ \"Ajax\" ], function ( Ajax ) { Ajax . apiOnce ({ data : { actionName : \"makeSnafucated\" , className : \"app\\\\data\\\\foo\\\\FooAction\" , parameters : { value : 3 } }, success : function ( data ) { elBySel ( \".some-element\" ). textContent = data . bar ; } }) }); </ script >","title":"Single Requests Without a Module (Legacy API)"},{"location":"javascript/new-api_browser/","text":"Browser and Screen Sizes - JavaScript API # Ui/Screen # CSS offers powerful media queries that alter the layout depending on the screen sizes, including but not limited to changes between landscape and portrait mode on mobile devices. The Ui/Screen module exposes a consistent interface to execute JavaScript code based on the same media queries that are available in the CSS code already. It features support for unmatching and executing code when a rule matches for the first time during the page lifecycle. Supported Aliases # You can pass in custom media queries, but it is strongly recommended to use the built-in media queries that match the same dimensions as your CSS. Alias Media Query screen-xs (max-width: 544px) screen-sm (min-width: 545px) and (max-width: 768px) screen-sm-down (max-width: 768px) screen-sm-up (min-width: 545px) screen-sm-md (min-width: 545px) and (max-width: 1024px) screen-md (min-width: 769px) and (max-width: 1024px) screen-md-down (max-width: 1024px) screen-md-up (min-width: 769px) screen-lg (min-width: 1025px) on(query: string, callbacks: Object): string # Registers a set of callback functions for the provided media query, the possible keys are match , unmatch and setup . The method returns a randomly generated UUIDv4 that is used to identify these callbacks and allows them to be removed via .remove() . remove(query: string, uuid: string) # Removes all callbacks for a media query that match the UUIDv4 that was previously obtained from the call to .on() . is(query: string): boolean # Tests if the provided media query currently matches and returns true on match. scrollDisable() # Temporarily prevents the page from being scrolled, until .scrollEnable() is called. scrollEnable() # Enables page scrolling again, unless another pending action has also prevented the page scrolling. Environment # The Environment module uses a mixture of feature detection and user agent sniffing to determine the browser and platform. In general, its results have proven to be very accurate, but it should be taken with a grain of salt regardless. Especially the browser checks are designed to be your last resort, please use feature detection instead whenever it is possible! Sometimes it may be necessary to alter the behavior of your code depending on the browser platform (e. g. mobile devices) or based on a specific browser in order to work-around some quirks. browser(): string # Attempts to detect browsers based on their technology and supported CSS vendor prefixes, and although somewhat reliable for major browsers, it is highly recommended to use feature detection instead. Possible values: - chrome (includes Opera 15+ and Vivaldi) - firefox - safari - microsoft (Internet Explorer and Edge) - other (default) platform(): string # Attempts to detect the browser platform using user agent sniffing. Possible values: - ios - android - windows (IE Mobile) - mobile (generic mobile device) - desktop (default)","title":"Browser and Screen Sizes"},{"location":"javascript/new-api_browser/#browser-and-screen-sizes-javascript-api","text":"","title":"Browser and Screen Sizes - JavaScript API"},{"location":"javascript/new-api_browser/#uiscreen","text":"CSS offers powerful media queries that alter the layout depending on the screen sizes, including but not limited to changes between landscape and portrait mode on mobile devices. The Ui/Screen module exposes a consistent interface to execute JavaScript code based on the same media queries that are available in the CSS code already. It features support for unmatching and executing code when a rule matches for the first time during the page lifecycle.","title":"Ui/Screen"},{"location":"javascript/new-api_browser/#supported-aliases","text":"You can pass in custom media queries, but it is strongly recommended to use the built-in media queries that match the same dimensions as your CSS. Alias Media Query screen-xs (max-width: 544px) screen-sm (min-width: 545px) and (max-width: 768px) screen-sm-down (max-width: 768px) screen-sm-up (min-width: 545px) screen-sm-md (min-width: 545px) and (max-width: 1024px) screen-md (min-width: 769px) and (max-width: 1024px) screen-md-down (max-width: 1024px) screen-md-up (min-width: 769px) screen-lg (min-width: 1025px)","title":"Supported Aliases"},{"location":"javascript/new-api_browser/#onquery-string-callbacks-object-string","text":"Registers a set of callback functions for the provided media query, the possible keys are match , unmatch and setup . The method returns a randomly generated UUIDv4 that is used to identify these callbacks and allows them to be removed via .remove() .","title":"on(query: string, callbacks: Object): string"},{"location":"javascript/new-api_browser/#removequery-string-uuid-string","text":"Removes all callbacks for a media query that match the UUIDv4 that was previously obtained from the call to .on() .","title":"remove(query: string, uuid: string)"},{"location":"javascript/new-api_browser/#isquery-string-boolean","text":"Tests if the provided media query currently matches and returns true on match.","title":"is(query: string): boolean"},{"location":"javascript/new-api_browser/#scrolldisable","text":"Temporarily prevents the page from being scrolled, until .scrollEnable() is called.","title":"scrollDisable()"},{"location":"javascript/new-api_browser/#scrollenable","text":"Enables page scrolling again, unless another pending action has also prevented the page scrolling.","title":"scrollEnable()"},{"location":"javascript/new-api_browser/#environment","text":"The Environment module uses a mixture of feature detection and user agent sniffing to determine the browser and platform. In general, its results have proven to be very accurate, but it should be taken with a grain of salt regardless. Especially the browser checks are designed to be your last resort, please use feature detection instead whenever it is possible! Sometimes it may be necessary to alter the behavior of your code depending on the browser platform (e. g. mobile devices) or based on a specific browser in order to work-around some quirks.","title":"Environment"},{"location":"javascript/new-api_browser/#browser-string","text":"Attempts to detect browsers based on their technology and supported CSS vendor prefixes, and although somewhat reliable for major browsers, it is highly recommended to use feature detection instead. Possible values: - chrome (includes Opera 15+ and Vivaldi) - firefox - safari - microsoft (Internet Explorer and Edge) - other (default)","title":"browser(): string"},{"location":"javascript/new-api_browser/#platform-string","text":"Attempts to detect the browser platform using user agent sniffing. Possible values: - ios - android - windows (IE Mobile) - mobile (generic mobile device) - desktop (default)","title":"platform(): string"},{"location":"javascript/new-api_core/","text":"Core Modules and Functions - JavaScript API # A brief overview of common methods that may be useful when writing any module. Core # clone(object: Object): Object # Creates a deep-clone of the provided object by value, removing any references on the original element, including arrays. However, this does not clone references to non-plain objects, these instances will be copied by reference. 1 2 3 4 5 6 7 require ([ \"Core\" ], function ( Core ) { var obj1 = { a : 1 }; var obj2 = Core . clone ( obj1 ); console . log ( obj1 === obj2 ); // output: false console . log ( obj2 . hasOwnProperty ( \"a\" ) && obj2 . a === 1 ); // output: true }); extend(base: Object, ...merge: Object[]): Object # Accepts an infinite amount of plain objects as parameters, values will be copied from the 2nd...nth object into the first object. The first parameter will be cloned and the resulting object is returned. 1 2 3 4 5 6 7 8 9 10 require ([ \"Core\" ], function ( Core ) { var obj1 = { a : 2 }; var obj2 = { a : 1 , b : 2 }; var obj = Core . extend ({ b : 1 }, obj1 , obj2 ); console . log ( obj . b === 2 ); // output: true console . log ( obj . hasOwnProperty ( \"a\" ) && obj . a === 2 ); // output: false }); inherit(base: Object, target: Object, merge?: Object) # Derives the second object's prototype from the first object, afterwards the derived class will pass the instanceof check against the original class. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); App . Baz = App . Foo . extend ({ makeSnafucated : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); // App/Baz.js define ([ \"Core\" , \"./Foo\" ], function ( Core , Foo ) { \"use strict\" ; function Baz () {}; Core . inherit ( Baz , Foo , { makeSnafucated : function () {} }); return Baz ; }); isPlainObject(object: Object): boolean # Verifies if an object is a plain JavaScript object and not an object instance. 1 2 3 4 5 6 7 8 9 10 11 12 13 require ([ \"Core\" ], function ( Core ) { function Foo () {} Foo . prototype = { hello : \"world\" ; }; var obj1 = { hello : \"world\" }; var obj2 = new Foo (); console . log ( Core . isPlainObject ( obj1 )); // output: true console . log ( obj1 . hello === obj2 . hello ); // output: true console . log ( Core . isPlainObject ( obj2 )); // output: false }); triggerEvent(element: Element, eventName: string) # Creates and dispatches a synthetic JavaScript event on an element. 1 2 3 4 require ([ \"Core\" ], function ( Core ) { var element = elBySel ( \".some-element\" ); Core . triggerEvent ( element , \"click\" ); }); Language # add(key: string, value: string) # Registers a new phrase. 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . add ( 'app.foo.bar' , '{jslang}app.foo.bar{/jslang}' ); }); </ script > addObject(object: Object) # Registers a list of phrases using a plain object. 1 2 3 4 5 6 7 < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . addObject ({ 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' }); }); </ script > get(key: string, parameters?: Object): string # Retrieves a phrase by its key, optionally supporting basic template scripting with dynamic variables passed using the parameters object. 1 2 3 4 5 6 require ([ \"Language\" ], function ( Language ) { var title = Language . get ( \"app.foo.title\" ); var content = Language . get ( \"app.foo.content\" , { some : \"value\" }); }); StringUtil # escapeHTML(str: string): string # Escapes special HTML characters by converting them into an HTML entity. Character Replacement & & \" " < < > > escapeRegExp(str: string): string # Escapes a list of characters that have a special meaning in regular expressions and could alter the behavior when embedded into regular expressions. lcfirst(str: string): string # Makes a string's first character lowercase. ucfirst(str: string): string # Makes a string's first character uppercase. unescapeHTML(str: string): string # Converts some HTML entities into their original character. This is the reverse function of escapeHTML() .","title":"Core Functions"},{"location":"javascript/new-api_core/#core-modules-and-functions-javascript-api","text":"A brief overview of common methods that may be useful when writing any module.","title":"Core Modules and Functions - JavaScript API"},{"location":"javascript/new-api_core/#core","text":"","title":"Core"},{"location":"javascript/new-api_core/#cloneobject-object-object","text":"Creates a deep-clone of the provided object by value, removing any references on the original element, including arrays. However, this does not clone references to non-plain objects, these instances will be copied by reference. 1 2 3 4 5 6 7 require ([ \"Core\" ], function ( Core ) { var obj1 = { a : 1 }; var obj2 = Core . clone ( obj1 ); console . log ( obj1 === obj2 ); // output: false console . log ( obj2 . hasOwnProperty ( \"a\" ) && obj2 . a === 1 ); // output: true });","title":"clone(object: Object): Object"},{"location":"javascript/new-api_core/#extendbase-object-merge-object-object","text":"Accepts an infinite amount of plain objects as parameters, values will be copied from the 2nd...nth object into the first object. The first parameter will be cloned and the resulting object is returned. 1 2 3 4 5 6 7 8 9 10 require ([ \"Core\" ], function ( Core ) { var obj1 = { a : 2 }; var obj2 = { a : 1 , b : 2 }; var obj = Core . extend ({ b : 1 }, obj1 , obj2 ); console . log ( obj . b === 2 ); // output: true console . log ( obj . hasOwnProperty ( \"a\" ) && obj . a === 2 ); // output: false });","title":"extend(base: Object, ...merge: Object[]): Object"},{"location":"javascript/new-api_core/#inheritbase-object-target-object-merge-object","text":"Derives the second object's prototype from the first object, afterwards the derived class will pass the instanceof check against the original class. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); App . Baz = App . Foo . extend ({ makeSnafucated : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); // App/Baz.js define ([ \"Core\" , \"./Foo\" ], function ( Core , Foo ) { \"use strict\" ; function Baz () {}; Core . inherit ( Baz , Foo , { makeSnafucated : function () {} }); return Baz ; });","title":"inherit(base: Object, target: Object, merge?: Object)"},{"location":"javascript/new-api_core/#isplainobjectobject-object-boolean","text":"Verifies if an object is a plain JavaScript object and not an object instance. 1 2 3 4 5 6 7 8 9 10 11 12 13 require ([ \"Core\" ], function ( Core ) { function Foo () {} Foo . prototype = { hello : \"world\" ; }; var obj1 = { hello : \"world\" }; var obj2 = new Foo (); console . log ( Core . isPlainObject ( obj1 )); // output: true console . log ( obj1 . hello === obj2 . hello ); // output: true console . log ( Core . isPlainObject ( obj2 )); // output: false });","title":"isPlainObject(object: Object): boolean"},{"location":"javascript/new-api_core/#triggereventelement-element-eventname-string","text":"Creates and dispatches a synthetic JavaScript event on an element. 1 2 3 4 require ([ \"Core\" ], function ( Core ) { var element = elBySel ( \".some-element\" ); Core . triggerEvent ( element , \"click\" ); });","title":"triggerEvent(element: Element, eventName: string)"},{"location":"javascript/new-api_core/#language","text":"","title":"Language"},{"location":"javascript/new-api_core/#addkey-string-value-string","text":"Registers a new phrase. 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . add ( 'app.foo.bar' , '{jslang}app.foo.bar{/jslang}' ); }); </ script >","title":"add(key: string, value: string)"},{"location":"javascript/new-api_core/#addobjectobject-object","text":"Registers a list of phrases using a plain object. 1 2 3 4 5 6 7 < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . addObject ({ 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' }); }); </ script >","title":"addObject(object: Object)"},{"location":"javascript/new-api_core/#getkey-string-parameters-object-string","text":"Retrieves a phrase by its key, optionally supporting basic template scripting with dynamic variables passed using the parameters object. 1 2 3 4 5 6 require ([ \"Language\" ], function ( Language ) { var title = Language . get ( \"app.foo.title\" ); var content = Language . get ( \"app.foo.content\" , { some : \"value\" }); });","title":"get(key: string, parameters?: Object): string"},{"location":"javascript/new-api_core/#stringutil","text":"","title":"StringUtil"},{"location":"javascript/new-api_core/#escapehtmlstr-string-string","text":"Escapes special HTML characters by converting them into an HTML entity. Character Replacement & & \" " < < > >","title":"escapeHTML(str: string): string"},{"location":"javascript/new-api_core/#escaperegexpstr-string-string","text":"Escapes a list of characters that have a special meaning in regular expressions and could alter the behavior when embedded into regular expressions.","title":"escapeRegExp(str: string): string"},{"location":"javascript/new-api_core/#lcfirststr-string-string","text":"Makes a string's first character lowercase.","title":"lcfirst(str: string): string"},{"location":"javascript/new-api_core/#ucfirststr-string-string","text":"Makes a string's first character uppercase.","title":"ucfirst(str: string): string"},{"location":"javascript/new-api_core/#unescapehtmlstr-string-string","text":"Converts some HTML entities into their original character. This is the reverse function of escapeHTML() .","title":"unescapeHTML(str: string): string"},{"location":"javascript/new-api_data-structures/","text":"Data Structures - JavaScript API # These data structures are deprecated since version 5.4. Refer to our migration guide on how to replace them. Introduction # JavaScript offers only limited types of collections to hold and iterate over data. Despite the ongoing efforts in ES6 and newer, these new data structures and access methods, such as for \u2026 of , are not available in the still supported Internet Explorer 11. Dictionary # Represents a simple key-value map, but unlike the use of plain objects, will always to guarantee to iterate over directly set values only. In supported browsers this will use a native Map internally, otherwise a plain object. set(key: string, value: any) # Adds or updates an item using the provided key. Numeric keys will be converted into strings. delete(key: string) # Removes an item from the collection. has(key: string): boolean # Returns true if the key is contained in the collection. get(key: string): any # Returns the value for the provided key, or undefined if the key was not found. Use .has() to check for key existence. forEach(callback: (value: any, key: string) => void) # Iterates over all items in the collection in an arbitrary order and invokes the supplied callback with the value and the key. size: number # This read-only property counts the number of items in the collection. List # Represents a list of unique values. In supported browsers this will use a native Set internally, otherwise an array. add(value: any) # Adds a value to the list. If the value is already part of the list, this method will silently abort. clear() # Resets the collection. delete(value: any): boolean # Attempts to remove a value from the list, it returns true if the value has been part of the list. forEach(callback: (value: any) => void) # Iterates over all values in the list in an arbitrary order and invokes the supplied callback for each value. has(value: any): boolean # Returns true if the provided value is part of this list. size: number # This read-only property counts the number of items in the list. ObjectMap # This class uses a WeakMap internally, the keys are only weakly referenced and do not prevent garbage collection. Represents a collection where any kind of objects, such as class instances or DOM elements, can be used as key. These keys are weakly referenced and will not prevent garbage collection from happening, but this also means that it is not possible to enumerate or iterate over the stored keys and values. This class is especially useful when you want to store additional data for objects that may get disposed on runtime, such as DOM elements. Using any regular data collections will cause the object to be referenced indefinitely, preventing the garbage collection from removing orphaned objects. set(key: Object, value: Object) # Adds the key with the provided value to the map, if the key was already part of the collection, its value is overwritten. delete(key: Object) # Attempts to remove a key from the collection. The method will abort silently if the key is not part of the collection. has(key: Object): boolean # Returns true if there is a value for the provided key in this collection. get(key: Object): Object | undefined # Retrieves the value of the provided key, or undefined if the key was not found.","title":"Data Structures"},{"location":"javascript/new-api_data-structures/#data-structures-javascript-api","text":"These data structures are deprecated since version 5.4. Refer to our migration guide on how to replace them.","title":"Data Structures - JavaScript API"},{"location":"javascript/new-api_data-structures/#introduction","text":"JavaScript offers only limited types of collections to hold and iterate over data. Despite the ongoing efforts in ES6 and newer, these new data structures and access methods, such as for \u2026 of , are not available in the still supported Internet Explorer 11.","title":"Introduction"},{"location":"javascript/new-api_data-structures/#dictionary","text":"Represents a simple key-value map, but unlike the use of plain objects, will always to guarantee to iterate over directly set values only. In supported browsers this will use a native Map internally, otherwise a plain object.","title":"Dictionary"},{"location":"javascript/new-api_data-structures/#setkey-string-value-any","text":"Adds or updates an item using the provided key. Numeric keys will be converted into strings.","title":"set(key: string, value: any)"},{"location":"javascript/new-api_data-structures/#deletekey-string","text":"Removes an item from the collection.","title":"delete(key: string)"},{"location":"javascript/new-api_data-structures/#haskey-string-boolean","text":"Returns true if the key is contained in the collection.","title":"has(key: string): boolean"},{"location":"javascript/new-api_data-structures/#getkey-string-any","text":"Returns the value for the provided key, or undefined if the key was not found. Use .has() to check for key existence.","title":"get(key: string): any"},{"location":"javascript/new-api_data-structures/#foreachcallback-value-any-key-string-void","text":"Iterates over all items in the collection in an arbitrary order and invokes the supplied callback with the value and the key.","title":"forEach(callback: (value: any, key: string) => void)"},{"location":"javascript/new-api_data-structures/#size-number","text":"This read-only property counts the number of items in the collection.","title":"size: number"},{"location":"javascript/new-api_data-structures/#list","text":"Represents a list of unique values. In supported browsers this will use a native Set internally, otherwise an array.","title":"List"},{"location":"javascript/new-api_data-structures/#addvalue-any","text":"Adds a value to the list. If the value is already part of the list, this method will silently abort.","title":"add(value: any)"},{"location":"javascript/new-api_data-structures/#clear","text":"Resets the collection.","title":"clear()"},{"location":"javascript/new-api_data-structures/#deletevalue-any-boolean","text":"Attempts to remove a value from the list, it returns true if the value has been part of the list.","title":"delete(value: any): boolean"},{"location":"javascript/new-api_data-structures/#foreachcallback-value-any-void","text":"Iterates over all values in the list in an arbitrary order and invokes the supplied callback for each value.","title":"forEach(callback: (value: any) => void)"},{"location":"javascript/new-api_data-structures/#hasvalue-any-boolean","text":"Returns true if the provided value is part of this list.","title":"has(value: any): boolean"},{"location":"javascript/new-api_data-structures/#size-number_1","text":"This read-only property counts the number of items in the list.","title":"size: number"},{"location":"javascript/new-api_data-structures/#objectmap","text":"This class uses a WeakMap internally, the keys are only weakly referenced and do not prevent garbage collection. Represents a collection where any kind of objects, such as class instances or DOM elements, can be used as key. These keys are weakly referenced and will not prevent garbage collection from happening, but this also means that it is not possible to enumerate or iterate over the stored keys and values. This class is especially useful when you want to store additional data for objects that may get disposed on runtime, such as DOM elements. Using any regular data collections will cause the object to be referenced indefinitely, preventing the garbage collection from removing orphaned objects.","title":"ObjectMap"},{"location":"javascript/new-api_data-structures/#setkey-object-value-object","text":"Adds the key with the provided value to the map, if the key was already part of the collection, its value is overwritten.","title":"set(key: Object, value: Object)"},{"location":"javascript/new-api_data-structures/#deletekey-object","text":"Attempts to remove a key from the collection. The method will abort silently if the key is not part of the collection.","title":"delete(key: Object)"},{"location":"javascript/new-api_data-structures/#haskey-object-boolean","text":"Returns true if there is a value for the provided key in this collection.","title":"has(key: Object): boolean"},{"location":"javascript/new-api_data-structures/#getkey-object-object-undefined","text":"Retrieves the value of the provided key, or undefined if the key was not found.","title":"get(key: Object): Object | undefined"},{"location":"javascript/new-api_dialogs/","text":"Dialogs - JavaScript API # Introduction # Dialogs are full screen overlays that cover the currently visible window area using a semi-opague backdrop and a prominently placed dialog window in the foreground. They shift the attention away from the original content towards the dialog and usually contain additional details and/or dedicated form inputs. _dialogSetup() # The lazy initialization is performed upon the first invocation from the callee, using the magic _dialogSetup() method to retrieve the basic configuration for the dialog construction and any event callbacks. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // App/Foo.js define ([ \"Ui/Dialog\" ], function ( UiDialog ) { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () { // this will open the dialog constructed by _dialogSetup UiDialog . open ( this ); }, _dialogSetup : function () { return { id : \"myDialog\" , source : \"<p>Hello World!</p>\" , options : { onClose : function () { // the fancy dialog was closed! } } } } }; return Foo ; }); id: string # The id is used to identify a dialog on runtime, but is also part of the first- time setup when the dialog has not been opened before. If source is undefined , the module attempts to construct the dialog using an element with the same id. source: any # There are six different types of value that source does allow and each of them changes how the initial dialog is constructed: undefined The dialog exists already and the value of id should be used to identify the element. null The HTML is provided using the second argument of .open() . () => void If the source is a function, it is executed and is expected to start the dialog initialization itself. Object Plain objects are interpreted as parameters for an Ajax request, in particular source.data will be used to issue the request. It is possible to specify the key source.after as a callback (content: Element, responseData: Object) => void that is executed after the dialog was opened. string The string is expected to be plain HTML that should be used to construct the dialog. DocumentFragment A new container <div> with the provided id is created and the contents of the DocumentFragment is appended to it. This container is then used for the dialog. options: Object # All configuration options and callbacks are handled through this object. options.backdropCloseOnClick: boolean # Defaults to true . Clicks on the dialog backdrop will close the top-most dialog. This option will be force-disabled if the option closeable is set to false . options.closable: boolean # Defaults to true . Enables the close button in the dialog title, when disabled the dialog can be closed through the .close() API call only. options.closeButtonLabel: string # Defaults to Language.get(\"wcf.global.button.close\") . The phrase that is displayed in the tooltip for the close button. options.closeConfirmMessage: string # Defaults to \"\" . Shows a confirmation dialog using the configured message before closing the dialog. The dialog will not be closed if the dialog is rejected by the user. options.title: string # Defaults to \"\" . The phrase that is displayed in the dialog title. options.onBeforeClose: (id: string) => void # Defaults to null . The callback is executed when the user clicks on the close button or, if enabled, on the backdrop. The callback is responsible to close the dialog by itself, the default close behavior is automatically prevented. options.onClose: (id: string) => void # Defaults to null . The callback is notified once the dialog is about to be closed, but is still visible at this point. It is not possible to abort the close operation at this point. options.onShow: (content: Element) => void # Defaults to null . Receives the dialog content element as its only argument, allowing the callback to modify the DOM or to register event listeners before the dialog is presented to the user. The dialog is already visible at call time, but the dialog has not been finalized yet. setTitle(id: string | Object, title: string) # Sets the title of a dialog. setCallback(id: string | Object, key: string, value: (data: any) => void | null) # Sets a callback function after the dialog initialization, the special value null will remove a previously set callback. Valid values for key are onBeforeClose , onClose and onShow . rebuild(id: string | Object) # Rebuilds a dialog by performing various calculations on the maximum dialog height in regards to the overflow handling and adjustments for embedded forms. This method is automatically invoked whenever a dialog is shown, after invoking the options.onShow callback. close(id: string | Object) # Closes an open dialog, this will neither trigger a confirmation dialog, nor does it invoke the options.onBeforeClose callback. The options.onClose callback will always be invoked, but it cannot abort the close operation. getDialog(id: string | Object): Object # This method returns an internal data object by reference, any modifications made do have an effect on the dialogs behavior and in particular no validation is performed on the modification. It is strongly recommended to use the .set*() methods only. Returns the internal dialog data that is attached to a dialog. The most important key is .content which holds a reference to the dialog's inner content element. isOpen(id: string | Object): boolean # Returns true if the dialog exists and is open.","title":"Dialogs"},{"location":"javascript/new-api_dialogs/#dialogs-javascript-api","text":"","title":"Dialogs - JavaScript API"},{"location":"javascript/new-api_dialogs/#introduction","text":"Dialogs are full screen overlays that cover the currently visible window area using a semi-opague backdrop and a prominently placed dialog window in the foreground. They shift the attention away from the original content towards the dialog and usually contain additional details and/or dedicated form inputs.","title":"Introduction"},{"location":"javascript/new-api_dialogs/#_dialogsetup","text":"The lazy initialization is performed upon the first invocation from the callee, using the magic _dialogSetup() method to retrieve the basic configuration for the dialog construction and any event callbacks. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // App/Foo.js define ([ \"Ui/Dialog\" ], function ( UiDialog ) { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () { // this will open the dialog constructed by _dialogSetup UiDialog . open ( this ); }, _dialogSetup : function () { return { id : \"myDialog\" , source : \"<p>Hello World!</p>\" , options : { onClose : function () { // the fancy dialog was closed! } } } } }; return Foo ; });","title":"_dialogSetup()"},{"location":"javascript/new-api_dialogs/#id-string","text":"The id is used to identify a dialog on runtime, but is also part of the first- time setup when the dialog has not been opened before. If source is undefined , the module attempts to construct the dialog using an element with the same id.","title":"id: string"},{"location":"javascript/new-api_dialogs/#source-any","text":"There are six different types of value that source does allow and each of them changes how the initial dialog is constructed: undefined The dialog exists already and the value of id should be used to identify the element. null The HTML is provided using the second argument of .open() . () => void If the source is a function, it is executed and is expected to start the dialog initialization itself. Object Plain objects are interpreted as parameters for an Ajax request, in particular source.data will be used to issue the request. It is possible to specify the key source.after as a callback (content: Element, responseData: Object) => void that is executed after the dialog was opened. string The string is expected to be plain HTML that should be used to construct the dialog. DocumentFragment A new container <div> with the provided id is created and the contents of the DocumentFragment is appended to it. This container is then used for the dialog.","title":"source: any"},{"location":"javascript/new-api_dialogs/#options-object","text":"All configuration options and callbacks are handled through this object.","title":"options: Object"},{"location":"javascript/new-api_dialogs/#optionsbackdropcloseonclick-boolean","text":"Defaults to true . Clicks on the dialog backdrop will close the top-most dialog. This option will be force-disabled if the option closeable is set to false .","title":"options.backdropCloseOnClick: boolean"},{"location":"javascript/new-api_dialogs/#optionsclosable-boolean","text":"Defaults to true . Enables the close button in the dialog title, when disabled the dialog can be closed through the .close() API call only.","title":"options.closable: boolean"},{"location":"javascript/new-api_dialogs/#optionsclosebuttonlabel-string","text":"Defaults to Language.get(\"wcf.global.button.close\") . The phrase that is displayed in the tooltip for the close button.","title":"options.closeButtonLabel: string"},{"location":"javascript/new-api_dialogs/#optionscloseconfirmmessage-string","text":"Defaults to \"\" . Shows a confirmation dialog using the configured message before closing the dialog. The dialog will not be closed if the dialog is rejected by the user.","title":"options.closeConfirmMessage: string"},{"location":"javascript/new-api_dialogs/#optionstitle-string","text":"Defaults to \"\" . The phrase that is displayed in the dialog title.","title":"options.title: string"},{"location":"javascript/new-api_dialogs/#optionsonbeforeclose-id-string-void","text":"Defaults to null . The callback is executed when the user clicks on the close button or, if enabled, on the backdrop. The callback is responsible to close the dialog by itself, the default close behavior is automatically prevented.","title":"options.onBeforeClose: (id: string) => void"},{"location":"javascript/new-api_dialogs/#optionsonclose-id-string-void","text":"Defaults to null . The callback is notified once the dialog is about to be closed, but is still visible at this point. It is not possible to abort the close operation at this point.","title":"options.onClose: (id: string) => void"},{"location":"javascript/new-api_dialogs/#optionsonshow-content-element-void","text":"Defaults to null . Receives the dialog content element as its only argument, allowing the callback to modify the DOM or to register event listeners before the dialog is presented to the user. The dialog is already visible at call time, but the dialog has not been finalized yet.","title":"options.onShow: (content: Element) => void"},{"location":"javascript/new-api_dialogs/#settitleid-string-object-title-string","text":"Sets the title of a dialog.","title":"setTitle(id: string | Object, title: string)"},{"location":"javascript/new-api_dialogs/#setcallbackid-string-object-key-string-value-data-any-void-null","text":"Sets a callback function after the dialog initialization, the special value null will remove a previously set callback. Valid values for key are onBeforeClose , onClose and onShow .","title":"setCallback(id: string | Object, key: string, value: (data: any) => void | null)"},{"location":"javascript/new-api_dialogs/#rebuildid-string-object","text":"Rebuilds a dialog by performing various calculations on the maximum dialog height in regards to the overflow handling and adjustments for embedded forms. This method is automatically invoked whenever a dialog is shown, after invoking the options.onShow callback.","title":"rebuild(id: string | Object)"},{"location":"javascript/new-api_dialogs/#closeid-string-object","text":"Closes an open dialog, this will neither trigger a confirmation dialog, nor does it invoke the options.onBeforeClose callback. The options.onClose callback will always be invoked, but it cannot abort the close operation.","title":"close(id: string | Object)"},{"location":"javascript/new-api_dialogs/#getdialogid-string-object-object","text":"This method returns an internal data object by reference, any modifications made do have an effect on the dialogs behavior and in particular no validation is performed on the modification. It is strongly recommended to use the .set*() methods only. Returns the internal dialog data that is attached to a dialog. The most important key is .content which holds a reference to the dialog's inner content element.","title":"getDialog(id: string | Object): Object"},{"location":"javascript/new-api_dialogs/#isopenid-string-object-boolean","text":"Returns true if the dialog exists and is open.","title":"isOpen(id: string | Object): boolean"},{"location":"javascript/new-api_dom/","text":"Working with the DOM - JavaScript API # Helper Functions # There is large set of helper functions that assist you when working with the DOM tree and its elements. These functions are globally available and do not require explicit module imports. Dom/Util # createFragmentFromHtml(html: string): DocumentFragment # Parses a HTML string and creates a DocumentFragment object that holds the resulting nodes. identify(element: Element): string # Retrieves the unique identifier ( id ) of an element. If it does not currently have an id assigned, a generic identifier is used instead. outerHeight(element: Element, styles?: CSSStyleDeclaration): number # Computes the outer height of an element using the element's offsetHeight and the sum of the rounded down values for margin-top and margin-bottom . outerWidth(element: Element, styles?: CSSStyleDeclaration): number # Computes the outer width of an element using the element's offsetWidth and the sum of the rounded down values for margin-left and margin-right . outerDimensions(element: Element): { height: number, width: number } # Computes the outer dimensions of an element including its margins. offset(element: Element): { top: number, left: number } # Computes the element's offset relative to the top left corner of the document. setInnerHtml(element: Element, innerHtml: string) # Sets the inner HTML of an element via element.innerHTML = innerHtml . Browsers do not evaluate any embedded <script> tags, therefore this method extracts each of them, creates new <script> tags and inserts them in their original order of appearance. contains(element: Element, child: Element): boolean # Evaluates if element is a direct or indirect parent element of child . unwrapChildNodes(element: Element) # Moves all child nodes out of element while maintaining their order, then removes element from the document. Dom/ChangeListener # This class is used to observe specific changes to the DOM, for example after an Ajax request has completed. For performance reasons this is a manually-invoked listener that does not rely on a MutationObserver . 1 2 3 4 5 6 7 8 require ([ \"Dom/ChangeListener\" ], function ( DomChangeListener ) { DomChangeListener . add ( \"App/Foo\" , function () { // the DOM may have been altered significantly }); // propagate changes to the DOM DomChangeListener . trigger (); });","title":"DOM"},{"location":"javascript/new-api_dom/#working-with-the-dom-javascript-api","text":"","title":"Working with the DOM - JavaScript API"},{"location":"javascript/new-api_dom/#helper-functions","text":"There is large set of helper functions that assist you when working with the DOM tree and its elements. These functions are globally available and do not require explicit module imports.","title":"Helper Functions"},{"location":"javascript/new-api_dom/#domutil","text":"","title":"Dom/Util"},{"location":"javascript/new-api_dom/#createfragmentfromhtmlhtml-string-documentfragment","text":"Parses a HTML string and creates a DocumentFragment object that holds the resulting nodes.","title":"createFragmentFromHtml(html: string): DocumentFragment"},{"location":"javascript/new-api_dom/#identifyelement-element-string","text":"Retrieves the unique identifier ( id ) of an element. If it does not currently have an id assigned, a generic identifier is used instead.","title":"identify(element: Element): string"},{"location":"javascript/new-api_dom/#outerheightelement-element-styles-cssstyledeclaration-number","text":"Computes the outer height of an element using the element's offsetHeight and the sum of the rounded down values for margin-top and margin-bottom .","title":"outerHeight(element: Element, styles?: CSSStyleDeclaration): number"},{"location":"javascript/new-api_dom/#outerwidthelement-element-styles-cssstyledeclaration-number","text":"Computes the outer width of an element using the element's offsetWidth and the sum of the rounded down values for margin-left and margin-right .","title":"outerWidth(element: Element, styles?: CSSStyleDeclaration): number"},{"location":"javascript/new-api_dom/#outerdimensionselement-element-height-number-width-number","text":"Computes the outer dimensions of an element including its margins.","title":"outerDimensions(element: Element): { height: number, width: number }"},{"location":"javascript/new-api_dom/#offsetelement-element-top-number-left-number","text":"Computes the element's offset relative to the top left corner of the document.","title":"offset(element: Element): { top: number, left: number }"},{"location":"javascript/new-api_dom/#setinnerhtmlelement-element-innerhtml-string","text":"Sets the inner HTML of an element via element.innerHTML = innerHtml . Browsers do not evaluate any embedded <script> tags, therefore this method extracts each of them, creates new <script> tags and inserts them in their original order of appearance.","title":"setInnerHtml(element: Element, innerHtml: string)"},{"location":"javascript/new-api_dom/#containselement-element-child-element-boolean","text":"Evaluates if element is a direct or indirect parent element of child .","title":"contains(element: Element, child: Element): boolean"},{"location":"javascript/new-api_dom/#unwrapchildnodeselement-element","text":"Moves all child nodes out of element while maintaining their order, then removes element from the document.","title":"unwrapChildNodes(element: Element)"},{"location":"javascript/new-api_dom/#domchangelistener","text":"This class is used to observe specific changes to the DOM, for example after an Ajax request has completed. For performance reasons this is a manually-invoked listener that does not rely on a MutationObserver . 1 2 3 4 5 6 7 8 require ([ \"Dom/ChangeListener\" ], function ( DomChangeListener ) { DomChangeListener . add ( \"App/Foo\" , function () { // the DOM may have been altered significantly }); // propagate changes to the DOM DomChangeListener . trigger (); });","title":"Dom/ChangeListener"},{"location":"javascript/new-api_events/","text":"Event Handling - JavaScript API # EventKey # This class offers a set of static methods that can be used to determine if some common keys are being pressed. Internally it compares either the .key property if it is supported or the value of .which . 1 2 3 4 5 6 7 require ([ \"EventKey\" ], function ( EventKey ) { elBySel ( \".some-input\" ). addEventListener ( \"keydown\" , function ( event ) { if ( EventKey . Enter ( event )) { // the `Enter` key was pressed } }); }); ArrowDown(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u2193 key. ArrowLeft(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u2190 key. ArrowRight(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u2192 key. ArrowUp(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u2191 key. Comma(event: KeyboardEvent): boolean # Returns true if the user has pressed the , key. Enter(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u21b2 key. Escape(event: KeyboardEvent): boolean # Returns true if the user has pressed the Esc key. Tab(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u21b9 key. EventHandler # A synchronous event system based on string identifiers rather than DOM elements, similar to the PHP event system in WoltLab Suite. Any components can listen to events or trigger events itself at any time. Identifiying Events with the Developer Tools # The Developer Tools offer an easy option to identify existing events that are fired while code is being executed. You can enable this watch mode through your browser's console using Devtools.toggleEventLogging() : 1 2 3 4 > Devtools.toggleEventLogging(); < Event logging enabled < [Devtools.EventLogging] Firing event: bar @ com.example.app.foo < [Devtools.EventLogging] Firing event: baz @ com.example.app.foo add(identifier: string, action: string, callback: (data: Object) => void): string # Adding an event listeners returns a randomly generated UUIDv4 that is used to identify the listener. This UUID is required to remove a specific listener through the remove() method. fire(identifier: string, action: string, data?: Object) # Triggers an event using an optional data object that is passed to each listener by reference. remove(identifier: string, action: string, uuid: string) # Removes a previously registered event listener using the UUID returned by add() . removeAll(identifier: string, action: string) # Removes all event listeners registered for the provided identifier and action . removeAllBySuffix(identifier: string, suffix: string) # Removes all event listeners for an identifier whose action ends with the value of suffix .","title":"Event Handling"},{"location":"javascript/new-api_events/#event-handling-javascript-api","text":"","title":"Event Handling - JavaScript API"},{"location":"javascript/new-api_events/#eventkey","text":"This class offers a set of static methods that can be used to determine if some common keys are being pressed. Internally it compares either the .key property if it is supported or the value of .which . 1 2 3 4 5 6 7 require ([ \"EventKey\" ], function ( EventKey ) { elBySel ( \".some-input\" ). addEventListener ( \"keydown\" , function ( event ) { if ( EventKey . Enter ( event )) { // the `Enter` key was pressed } }); });","title":"EventKey"},{"location":"javascript/new-api_events/#arrowdownevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u2193 key.","title":"ArrowDown(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#arrowleftevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u2190 key.","title":"ArrowLeft(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#arrowrightevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u2192 key.","title":"ArrowRight(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#arrowupevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u2191 key.","title":"ArrowUp(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#commaevent-keyboardevent-boolean","text":"Returns true if the user has pressed the , key.","title":"Comma(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#enterevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u21b2 key.","title":"Enter(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#escapeevent-keyboardevent-boolean","text":"Returns true if the user has pressed the Esc key.","title":"Escape(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#tabevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u21b9 key.","title":"Tab(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#eventhandler","text":"A synchronous event system based on string identifiers rather than DOM elements, similar to the PHP event system in WoltLab Suite. Any components can listen to events or trigger events itself at any time.","title":"EventHandler"},{"location":"javascript/new-api_events/#identifiying-events-with-the-developer-tools","text":"The Developer Tools offer an easy option to identify existing events that are fired while code is being executed. You can enable this watch mode through your browser's console using Devtools.toggleEventLogging() : 1 2 3 4 > Devtools.toggleEventLogging(); < Event logging enabled < [Devtools.EventLogging] Firing event: bar @ com.example.app.foo < [Devtools.EventLogging] Firing event: baz @ com.example.app.foo","title":"Identifiying Events with the Developer Tools"},{"location":"javascript/new-api_events/#addidentifier-string-action-string-callback-data-object-void-string","text":"Adding an event listeners returns a randomly generated UUIDv4 that is used to identify the listener. This UUID is required to remove a specific listener through the remove() method.","title":"add(identifier: string, action: string, callback: (data: Object) => void): string"},{"location":"javascript/new-api_events/#fireidentifier-string-action-string-data-object","text":"Triggers an event using an optional data object that is passed to each listener by reference.","title":"fire(identifier: string, action: string, data?: Object)"},{"location":"javascript/new-api_events/#removeidentifier-string-action-string-uuid-string","text":"Removes a previously registered event listener using the UUID returned by add() .","title":"remove(identifier: string, action: string, uuid: string)"},{"location":"javascript/new-api_events/#removeallidentifier-string-action-string","text":"Removes all event listeners registered for the provided identifier and action .","title":"removeAll(identifier: string, action: string)"},{"location":"javascript/new-api_events/#removeallbysuffixidentifier-string-suffix-string","text":"Removes all event listeners for an identifier whose action ends with the value of suffix .","title":"removeAllBySuffix(identifier: string, suffix: string)"},{"location":"javascript/new-api_ui/","text":"User Interface - JavaScript API # Ui/Alignment # Calculates the alignment of one element relative to another element, with support for boundary constraints, alignment restrictions and additional pointer elements. set(element: Element, referenceElement: Element, options: Object) # Calculates and sets the alignment of the element element . verticalOffset: number # Defaults to 0 . Creates a gap between the element and the reference element, in pixels. pointer: boolean # Defaults to false . Sets the position of the pointer element, requires an existing child of the element with the CSS class .elementPointer . pointerOffset: number # Defaults to 4 . The margin from the left/right edge of the element and is used to avoid the arrow from being placed right at the edge. Does not apply when aligning the element to the reference elemnent's center. pointerClassNames: string[] # Defaults to [] . If your element uses CSS-only pointers, such as using the ::before or ::after pseudo selectors, you can specifiy two separate CSS class names that control the alignment: pointerClassNames[0] is applied to the element when the pointer is displayed at the bottom. pointerClassNames[1] is used to align the pointer to the right side of the element. refDimensionsElement: Element # Defaults to null . An alternative element that will be used to determine the position and dimensions of the reference element. This can be useful if you reference element is contained in a wrapper element with alternating dimensions. horizontal: string # This value is automatically flipped for RTL (right-to-left) languages, left is changed into right and vice versa. Defaults to \"left\" . Sets the prefered alignment, accepts either left or right . The value left instructs the module to align the element with the left boundary of the reference element. The horizontal alignment is used as the default and a flip only occurs, if there is not enough space in the desired direction. If the element exceeds the boundaries in both directions, the value of horizontal is used. vertical: string # Defaults to \"bottom\" . Sets the prefered alignment, accepts either bottom or top . The value bottom instructs the module to align the element below the reference element. The vertical alignment is used as the default and a flip only occurs, if there is not enough space in the desired direction. If the element exceeds the boundaries in both directions, the value of vertical is used. allowFlip: string # The value for horizontal is automatically flipped for RTL (right-to-left) languages, left is changed into right and vice versa. This setting only controls the behavior when violating space constraints, therefore the aforementioned transformation is always applied. Defaults to \"both\" . Restricts the automatic alignment flipping if the element exceeds the window boundaries in the instructed direction. both - No restrictions. horizontal - Element can be aligned with the left or the right boundary of the reference element, but the vertical position is fixed. vertical - Element can be aligned below or above the reference element, but the vertical position is fixed. none - No flipping can occur, the element will be aligned regardless of any space constraints. Ui/CloseOverlay # Register elements that should be closed when the user clicks anywhere else, such as drop-down menus or tooltips. 1 2 3 4 5 require ([ \"Ui/CloseOverlay\" ], function ( UiCloseOverlay ) { UiCloseOverlay . add ( \"App/Foo\" , function () { // invoked, close something }); }); add(identifier: string, callback: () => void) # Adds a callback that will be invoked when the user clicks anywhere else. Ui/Confirmation # Prompt the user to make a decision before carrying out an action, such as a safety warning before permanently deleting content. 1 2 3 4 5 6 7 8 require ([ \"Ui/Confirmation\" ], function ( UiConfirmation ) { UiConfirmation . show ({ confirm : function () { // the user has confirmed the dialog }, message : \"Do you really want to continue?\" }); }); show(options: Object) # Displays a dialog overlay with actions buttons to confirm or reject the dialog. cancel: (parameters: Object) => void # Defaults to null . Callback that is invoked when the dialog was rejected. confirm: (parameters: Object) => void # Defaults to null . Callback that is invoked when the user has confirmed the dialog. message: string # Defaults to '\"\"'. Text that is displayed in the content area of the dialog, optionally this can be HTML, but this requires messageIsHtml to be enabled. messageIsHtml # Defaults to false . The message option is interpreted as text-only, setting this option to true will cause the message to be evaluated as HTML. parameters: Object # Optional list of parameter options that will be passed to the cancel() and confirm() callbacks. template: string # An optional HTML template that will be inserted into the dialog content area, but after the message section. Ui/Notification # Displays a simple notification at the very top of the window, such as a success message for Ajax based actions. 1 2 3 4 5 6 7 8 9 require ([ \"Ui/Notification\" ], function ( UiNotification ) { UiNotification . show ( \"Your changes have been saved.\" , function () { // this callback will be invoked after 2 seconds }, \"success\" ); }); show(message: string, callback?: () => void, cssClassName?: string) # Shows the notification and executes the callback after 2 seconds.","title":"User Interface"},{"location":"javascript/new-api_ui/#user-interface-javascript-api","text":"","title":"User Interface - JavaScript API"},{"location":"javascript/new-api_ui/#uialignment","text":"Calculates the alignment of one element relative to another element, with support for boundary constraints, alignment restrictions and additional pointer elements.","title":"Ui/Alignment"},{"location":"javascript/new-api_ui/#setelement-element-referenceelement-element-options-object","text":"Calculates and sets the alignment of the element element .","title":"set(element: Element, referenceElement: Element, options: Object)"},{"location":"javascript/new-api_ui/#verticaloffset-number","text":"Defaults to 0 . Creates a gap between the element and the reference element, in pixels.","title":"verticalOffset: number"},{"location":"javascript/new-api_ui/#pointer-boolean","text":"Defaults to false . Sets the position of the pointer element, requires an existing child of the element with the CSS class .elementPointer .","title":"pointer: boolean"},{"location":"javascript/new-api_ui/#pointeroffset-number","text":"Defaults to 4 . The margin from the left/right edge of the element and is used to avoid the arrow from being placed right at the edge. Does not apply when aligning the element to the reference elemnent's center.","title":"pointerOffset: number"},{"location":"javascript/new-api_ui/#pointerclassnames-string","text":"Defaults to [] . If your element uses CSS-only pointers, such as using the ::before or ::after pseudo selectors, you can specifiy two separate CSS class names that control the alignment: pointerClassNames[0] is applied to the element when the pointer is displayed at the bottom. pointerClassNames[1] is used to align the pointer to the right side of the element.","title":"pointerClassNames: string[]"},{"location":"javascript/new-api_ui/#refdimensionselement-element","text":"Defaults to null . An alternative element that will be used to determine the position and dimensions of the reference element. This can be useful if you reference element is contained in a wrapper element with alternating dimensions.","title":"refDimensionsElement: Element"},{"location":"javascript/new-api_ui/#horizontal-string","text":"This value is automatically flipped for RTL (right-to-left) languages, left is changed into right and vice versa. Defaults to \"left\" . Sets the prefered alignment, accepts either left or right . The value left instructs the module to align the element with the left boundary of the reference element. The horizontal alignment is used as the default and a flip only occurs, if there is not enough space in the desired direction. If the element exceeds the boundaries in both directions, the value of horizontal is used.","title":"horizontal: string"},{"location":"javascript/new-api_ui/#vertical-string","text":"Defaults to \"bottom\" . Sets the prefered alignment, accepts either bottom or top . The value bottom instructs the module to align the element below the reference element. The vertical alignment is used as the default and a flip only occurs, if there is not enough space in the desired direction. If the element exceeds the boundaries in both directions, the value of vertical is used.","title":"vertical: string"},{"location":"javascript/new-api_ui/#allowflip-string","text":"The value for horizontal is automatically flipped for RTL (right-to-left) languages, left is changed into right and vice versa. This setting only controls the behavior when violating space constraints, therefore the aforementioned transformation is always applied. Defaults to \"both\" . Restricts the automatic alignment flipping if the element exceeds the window boundaries in the instructed direction. both - No restrictions. horizontal - Element can be aligned with the left or the right boundary of the reference element, but the vertical position is fixed. vertical - Element can be aligned below or above the reference element, but the vertical position is fixed. none - No flipping can occur, the element will be aligned regardless of any space constraints.","title":"allowFlip: string"},{"location":"javascript/new-api_ui/#uicloseoverlay","text":"Register elements that should be closed when the user clicks anywhere else, such as drop-down menus or tooltips. 1 2 3 4 5 require ([ \"Ui/CloseOverlay\" ], function ( UiCloseOverlay ) { UiCloseOverlay . add ( \"App/Foo\" , function () { // invoked, close something }); });","title":"Ui/CloseOverlay"},{"location":"javascript/new-api_ui/#addidentifier-string-callback-void","text":"Adds a callback that will be invoked when the user clicks anywhere else.","title":"add(identifier: string, callback: () => void)"},{"location":"javascript/new-api_ui/#uiconfirmation","text":"Prompt the user to make a decision before carrying out an action, such as a safety warning before permanently deleting content. 1 2 3 4 5 6 7 8 require ([ \"Ui/Confirmation\" ], function ( UiConfirmation ) { UiConfirmation . show ({ confirm : function () { // the user has confirmed the dialog }, message : \"Do you really want to continue?\" }); });","title":"Ui/Confirmation"},{"location":"javascript/new-api_ui/#showoptions-object","text":"Displays a dialog overlay with actions buttons to confirm or reject the dialog.","title":"show(options: Object)"},{"location":"javascript/new-api_ui/#cancel-parameters-object-void","text":"Defaults to null . Callback that is invoked when the dialog was rejected.","title":"cancel: (parameters: Object) => void"},{"location":"javascript/new-api_ui/#confirm-parameters-object-void","text":"Defaults to null . Callback that is invoked when the user has confirmed the dialog.","title":"confirm: (parameters: Object) => void"},{"location":"javascript/new-api_ui/#message-string","text":"Defaults to '\"\"'. Text that is displayed in the content area of the dialog, optionally this can be HTML, but this requires messageIsHtml to be enabled.","title":"message: string"},{"location":"javascript/new-api_ui/#messageishtml","text":"Defaults to false . The message option is interpreted as text-only, setting this option to true will cause the message to be evaluated as HTML.","title":"messageIsHtml"},{"location":"javascript/new-api_ui/#parameters-object","text":"Optional list of parameter options that will be passed to the cancel() and confirm() callbacks.","title":"parameters: Object"},{"location":"javascript/new-api_ui/#template-string","text":"An optional HTML template that will be inserted into the dialog content area, but after the message section.","title":"template: string"},{"location":"javascript/new-api_ui/#uinotification","text":"Displays a simple notification at the very top of the window, such as a success message for Ajax based actions. 1 2 3 4 5 6 7 8 9 require ([ \"Ui/Notification\" ], function ( UiNotification ) { UiNotification . show ( \"Your changes have been saved.\" , function () { // this callback will be invoked after 2 seconds }, \"success\" ); });","title":"Ui/Notification"},{"location":"javascript/new-api_ui/#showmessage-string-callback-void-cssclassname-string","text":"Shows the notification and executes the callback after 2 seconds.","title":"show(message: string, callback?: () => void, cssClassName?: string)"},{"location":"javascript/new-api_writing-a-module/","text":"Writing a Module - JavaScript API # Introduction # The new JavaScript-API was introduced with WoltLab Suite 3.0 and was a major change in all regards. The previously used API heavily relied on larger JavaScript files that contained a lot of different components with hidden dependencies and suffered from extensive jQuery usage for historic reasons. Eventually a new API was designed that solves the issues with the legacy API by following a few basic principles: 1. Vanilla ES5-JavaScript. It allows us to achieve the best performance across all platforms, there is simply no reason to use jQuery today and the performance penalty on mobile devices is a real issue. 2. Strict usage of modules. Each component is placed in an own file and all dependencies are explicitly declared and injected at the top.Eventually we settled with AMD-style modules using require.js which offers both lazy loading and \"ahead of time\"-compilatio with r.js . 3. No jQuery-based components on page init. Nothing is more annoying than loading a page and then wait for JavaScript to modify the page before it becomes usable, forcing the user to sit and wait. Heavily optimized vanilla JavaScript components offered the speed we wanted. 4. Limited backwards-compatibility. The new API should make it easy to update existing components by providing similar interfaces, while still allowing legacy code to run side-by-side for best compatibility and to avoid rewritting everything from the start. Defining a Module # The default location for modules is js/ in the Core's app dir, but every app and plugin can register their own lookup path by providing the path using a template-listener on requirePaths@headIncludeJavaScript . For this example we'll assume the file is placed at js/WoltLabSuite/Core/Ui/Foo.js , the module name is therefore WoltLabSuite/Core/Ui/Foo , it is automatically derived from the file path and name. For further instructions on how to define and require modules head over to the RequireJS API . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 define ([ \"Ajax\" , \"WoltLabSuite/Core/Ui/Bar\" ], function ( Ajax , UiBar ) { \"use strict\" ; function Foo () { this . init (); } Foo . prototype = { init : function () { elBySel ( \".myButton\" ). addEventListener ( WCF_CLICK_EVENT , this . _click . bind ( this )); }, _click : function ( event ) { event . preventDefault (); if ( UiBar . isSnafucated ()) { Ajax . api ( this ); } }, _ajaxSuccess : function ( data ) { console . log ( \"Received response\" , data ); }, _ajaxSetup : function () { return { data : { actionName : \"makeSnafucated\" , className : \"wcf\\\\data\\\\foo\\\\FooAction\" } }; } } return Foo ; }); Loading a Module # Modules can then be loaded through their derived name: 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"WoltLabSuite/Core/Ui/Foo\" ], function ( UiFoo ) { new UiFoo (); }); </ script > Module Aliases # Some common modules have short-hand aliases that can be used to include them without writing out their full name. You can still use their original path, but it is strongly recommended to use the aliases for consistency. Alias Full Path Ajax WoltLabSuite/Core/Ajax AjaxJsonp WoltLabSuite/Core/Ajax/Jsonp AjaxRequest WoltLabSuite/Core/Ajax/Request CallbackList WoltLabSuite/Core/CallbackList ColorUtil WoltLabSuite/Core/ColorUtil Core WoltLabSuite/Core/Core DateUtil WoltLabSuite/Core/Date/Util Devtools WoltLabSuite/Core/Devtools Dictionary WoltLabSuite/Core/Dictionary Dom/ChangeListener WoltLabSuite/Core/Dom/Change/Listener Dom/Traverse WoltLabSuite/Core/Dom/Traverse Dom/Util WoltLabSuite/Core/Dom/Util Environment WoltLabSuite/Core/Environment EventHandler WoltLabSuite/Core/Event/Handler EventKey WoltLabSuite/Core/Event/Key Language WoltLabSuite/Core/Language List WoltLabSuite/Core/List ObjectMap WoltLabSuite/Core/ObjectMap Permission WoltLabSuite/Core/Permission StringUtil WoltLabSuite/Core/StringUtil Ui/Alignment WoltLabSuite/Core/Ui/Alignment Ui/CloseOverlay WoltLabSuite/Core/Ui/CloseOverlay Ui/Confirmation WoltLabSuite/Core/Ui/Confirmation Ui/Dialog WoltLabSuite/Core/Ui/Dialog Ui/Notification WoltLabSuite/Core/Ui/Notification Ui/ReusableDropdown WoltLabSuite/Core/Ui/Dropdown/Reusable Ui/Screen WoltLabSuite/Core/Ui/Screen Ui/Scroll WoltLabSuite/Core/Ui/Scroll Ui/SimpleDropdown WoltLabSuite/Core/Ui/Dropdown/Simple Ui/TabMenu WoltLabSuite/Core/Ui/TabMenu Upload WoltLabSuite/Core/Upload User WoltLabSuite/Core/User","title":"Writing a module"},{"location":"javascript/new-api_writing-a-module/#writing-a-module-javascript-api","text":"","title":"Writing a Module - JavaScript API"},{"location":"javascript/new-api_writing-a-module/#introduction","text":"The new JavaScript-API was introduced with WoltLab Suite 3.0 and was a major change in all regards. The previously used API heavily relied on larger JavaScript files that contained a lot of different components with hidden dependencies and suffered from extensive jQuery usage for historic reasons. Eventually a new API was designed that solves the issues with the legacy API by following a few basic principles: 1. Vanilla ES5-JavaScript. It allows us to achieve the best performance across all platforms, there is simply no reason to use jQuery today and the performance penalty on mobile devices is a real issue. 2. Strict usage of modules. Each component is placed in an own file and all dependencies are explicitly declared and injected at the top.Eventually we settled with AMD-style modules using require.js which offers both lazy loading and \"ahead of time\"-compilatio with r.js . 3. No jQuery-based components on page init. Nothing is more annoying than loading a page and then wait for JavaScript to modify the page before it becomes usable, forcing the user to sit and wait. Heavily optimized vanilla JavaScript components offered the speed we wanted. 4. Limited backwards-compatibility. The new API should make it easy to update existing components by providing similar interfaces, while still allowing legacy code to run side-by-side for best compatibility and to avoid rewritting everything from the start.","title":"Introduction"},{"location":"javascript/new-api_writing-a-module/#defining-a-module","text":"The default location for modules is js/ in the Core's app dir, but every app and plugin can register their own lookup path by providing the path using a template-listener on requirePaths@headIncludeJavaScript . For this example we'll assume the file is placed at js/WoltLabSuite/Core/Ui/Foo.js , the module name is therefore WoltLabSuite/Core/Ui/Foo , it is automatically derived from the file path and name. For further instructions on how to define and require modules head over to the RequireJS API . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 define ([ \"Ajax\" , \"WoltLabSuite/Core/Ui/Bar\" ], function ( Ajax , UiBar ) { \"use strict\" ; function Foo () { this . init (); } Foo . prototype = { init : function () { elBySel ( \".myButton\" ). addEventListener ( WCF_CLICK_EVENT , this . _click . bind ( this )); }, _click : function ( event ) { event . preventDefault (); if ( UiBar . isSnafucated ()) { Ajax . api ( this ); } }, _ajaxSuccess : function ( data ) { console . log ( \"Received response\" , data ); }, _ajaxSetup : function () { return { data : { actionName : \"makeSnafucated\" , className : \"wcf\\\\data\\\\foo\\\\FooAction\" } }; } } return Foo ; });","title":"Defining a Module"},{"location":"javascript/new-api_writing-a-module/#loading-a-module","text":"Modules can then be loaded through their derived name: 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"WoltLabSuite/Core/Ui/Foo\" ], function ( UiFoo ) { new UiFoo (); }); </ script >","title":"Loading a Module"},{"location":"javascript/new-api_writing-a-module/#module-aliases","text":"Some common modules have short-hand aliases that can be used to include them without writing out their full name. You can still use their original path, but it is strongly recommended to use the aliases for consistency. Alias Full Path Ajax WoltLabSuite/Core/Ajax AjaxJsonp WoltLabSuite/Core/Ajax/Jsonp AjaxRequest WoltLabSuite/Core/Ajax/Request CallbackList WoltLabSuite/Core/CallbackList ColorUtil WoltLabSuite/Core/ColorUtil Core WoltLabSuite/Core/Core DateUtil WoltLabSuite/Core/Date/Util Devtools WoltLabSuite/Core/Devtools Dictionary WoltLabSuite/Core/Dictionary Dom/ChangeListener WoltLabSuite/Core/Dom/Change/Listener Dom/Traverse WoltLabSuite/Core/Dom/Traverse Dom/Util WoltLabSuite/Core/Dom/Util Environment WoltLabSuite/Core/Environment EventHandler WoltLabSuite/Core/Event/Handler EventKey WoltLabSuite/Core/Event/Key Language WoltLabSuite/Core/Language List WoltLabSuite/Core/List ObjectMap WoltLabSuite/Core/ObjectMap Permission WoltLabSuite/Core/Permission StringUtil WoltLabSuite/Core/StringUtil Ui/Alignment WoltLabSuite/Core/Ui/Alignment Ui/CloseOverlay WoltLabSuite/Core/Ui/CloseOverlay Ui/Confirmation WoltLabSuite/Core/Ui/Confirmation Ui/Dialog WoltLabSuite/Core/Ui/Dialog Ui/Notification WoltLabSuite/Core/Ui/Notification Ui/ReusableDropdown WoltLabSuite/Core/Ui/Dropdown/Reusable Ui/Screen WoltLabSuite/Core/Ui/Screen Ui/Scroll WoltLabSuite/Core/Ui/Scroll Ui/SimpleDropdown WoltLabSuite/Core/Ui/Dropdown/Simple Ui/TabMenu WoltLabSuite/Core/Ui/TabMenu Upload WoltLabSuite/Core/Upload User WoltLabSuite/Core/User","title":"Module Aliases"},{"location":"javascript/typescript/","text":"TypeScript # Consuming WoltLab Suite\u2019s Types # To consume the types of WoltLab Suite, you will need to install the @woltlab/wcf npm package using a git URL that refers to the appropriate branch of WoltLab/WCF . A full package.json that includes WoltLab Suite, TypeScript, eslint and Prettier could look like the following. package.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 { \"devDependencies\" : { \"@typescript-eslint/eslint-plugin\" : \"^4.6.1\" , \"@typescript-eslint/parser\" : \"^4.6.1\" , \"eslint\" : \"^7.12.1\" , \"eslint-config-prettier\" : \"^6.15.0\" , \"prettier\" : \"^2.1.2\" , \"tslib\" : \"^2.0.3\" , \"typescript\" : \"^4.1.3\" }, \"dependencies\" : { \"@woltlab/wcf\" : \"https://github.com/WoltLab/WCF.git#master\" } } After installing the types using npm, you will also need to configure tsconfig.json to take the types into account. To do so, you will need to add them to the compilerOptions.paths option. A complete tsconfig.json file that matches the configuration of WoltLab Suite could look like the following. tsconfig.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 { \"include\" : [ \"node_modules/@woltlab/wcf/global.d.ts\" , \"ts/**/*\" ], \"compilerOptions\" : { \"target\" : \"es2017\" , \"module\" : \"amd\" , \"rootDir\" : \"ts/\" , \"outDir\" : \"files/js/\" , \"lib\" : [ \"dom\" , \"es2017\" ], \"strictNullChecks\" : true , \"moduleResolution\" : \"node\" , \"esModuleInterop\" : true , \"noImplicitThis\" : true , \"strictBindCallApply\" : true , \"baseUrl\" : \".\" , \"paths\" : { \"*\" : [ \"node_modules/@woltlab/wcf/ts/*\" ] }, \"importHelpers\" : true } } After this initial set-up, you would place your TypeScript source files into the ts/ folder of your project. The generated JavaScript target files will be placed into files/js/ and thus will be installed by the file PIP . Additional Tools # WoltLab Suite uses additional tools to ensure the high quality and a consistent code style of the TypeScript modules. The current configuration of these tools is as follows. It is recommended to re-use this configuration as is. .prettierrc 1 2 trailingComma: all printWidth: 120 .eslintrc.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 module . exports = { root : true , parser : \"@typescript-eslint/parser\" , parserOptions : { tsconfigRootDir : __dirname , project : [ \"./tsconfig.json\" ] }, plugins : [ \"@typescript-eslint\" ], extends : [ \"eslint:recommended\" , \"plugin:@typescript-eslint/recommended\" , \"plugin:@typescript-eslint/recommended-requiring-type-checking\" , \"prettier\" , \"prettier/@typescript-eslint\" ], rules : { \"@typescript-eslint/ban-types\" : [ \"error\" , { types : { \"object\" : false }, extendDefaults : true } ], \"@typescript-eslint/no-explicit-any\" : 0 , \"@typescript-eslint/no-non-null-assertion\" : 0 , \"@typescript-eslint/no-unsafe-assignment\" : 0 , \"@typescript-eslint/no-unsafe-call\" : 0 , \"@typescript-eslint/no-unsafe-member-access\" : 0 , \"@typescript-eslint/no-unsafe-return\" : 0 , \"@typescript-eslint/no-unused-vars\" : [ \"error\" , { \"argsIgnorePattern\" : \"^_\" } ] } }; .eslintignore 1 **/*.js This .gitattributes configuration will automatically collapse the generated JavaScript target files in GitHub\u2019s Diff view. You will not need it if you do not use git or GitHub. .gitattributes 1 files/js/**/*.js linguist-generated Writing a simple module # After completing this initial set-up you can start writing your first TypeScript module. The TypeScript compiler can be launched in Watch Mode by running npx tsc -w . WoltLab Suite\u2019s modules can be imported using the standard ECMAScript module import syntax by specifying the full module name. The public API of the module can also be exported using the standard ECMAScript module export syntax. ts/Example.ts 1 2 3 4 5 import * as Language from \"WoltLabSuite/Core/Language\" ; export function run () { alert ( Language . get ( \"wcf.foo.bar\" )); } This simple example module will compile to plain JavaScript that is compatible with the AMD loader that is used by WoltLab Suite. files/js/Example.js 1 2 3 4 5 6 7 8 9 10 define ([ \"require\" , \"exports\" , \"tslib\" , \"WoltLabSuite/Core/Language\" ], function ( require , exports , tslib_1 , Language ) { \"use strict\" ; Object . defineProperty ( exports , \"__esModule\" , { value : true }); exports . run = void 0 ; Language = tslib_1 . __importStar ( Language ); function run () { alert ( Language . get ( \"wcf.foo.bar\" )); } exports . run = run ; }); Within templates it can be consumed as follows. 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"Example\" ], ( Example ) => { Example . run (); // Alerts the contents of the `wcf.foo.bar` phrase. }); </ script >","title":"TypeScript"},{"location":"javascript/typescript/#typescript","text":"","title":"TypeScript"},{"location":"javascript/typescript/#consuming-woltlab-suites-types","text":"To consume the types of WoltLab Suite, you will need to install the @woltlab/wcf npm package using a git URL that refers to the appropriate branch of WoltLab/WCF . A full package.json that includes WoltLab Suite, TypeScript, eslint and Prettier could look like the following. package.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 { \"devDependencies\" : { \"@typescript-eslint/eslint-plugin\" : \"^4.6.1\" , \"@typescript-eslint/parser\" : \"^4.6.1\" , \"eslint\" : \"^7.12.1\" , \"eslint-config-prettier\" : \"^6.15.0\" , \"prettier\" : \"^2.1.2\" , \"tslib\" : \"^2.0.3\" , \"typescript\" : \"^4.1.3\" }, \"dependencies\" : { \"@woltlab/wcf\" : \"https://github.com/WoltLab/WCF.git#master\" } } After installing the types using npm, you will also need to configure tsconfig.json to take the types into account. To do so, you will need to add them to the compilerOptions.paths option. A complete tsconfig.json file that matches the configuration of WoltLab Suite could look like the following. tsconfig.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 { \"include\" : [ \"node_modules/@woltlab/wcf/global.d.ts\" , \"ts/**/*\" ], \"compilerOptions\" : { \"target\" : \"es2017\" , \"module\" : \"amd\" , \"rootDir\" : \"ts/\" , \"outDir\" : \"files/js/\" , \"lib\" : [ \"dom\" , \"es2017\" ], \"strictNullChecks\" : true , \"moduleResolution\" : \"node\" , \"esModuleInterop\" : true , \"noImplicitThis\" : true , \"strictBindCallApply\" : true , \"baseUrl\" : \".\" , \"paths\" : { \"*\" : [ \"node_modules/@woltlab/wcf/ts/*\" ] }, \"importHelpers\" : true } } After this initial set-up, you would place your TypeScript source files into the ts/ folder of your project. The generated JavaScript target files will be placed into files/js/ and thus will be installed by the file PIP .","title":"Consuming WoltLab Suite\u2019s Types"},{"location":"javascript/typescript/#additional-tools","text":"WoltLab Suite uses additional tools to ensure the high quality and a consistent code style of the TypeScript modules. The current configuration of these tools is as follows. It is recommended to re-use this configuration as is. .prettierrc 1 2 trailingComma: all printWidth: 120 .eslintrc.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 module . exports = { root : true , parser : \"@typescript-eslint/parser\" , parserOptions : { tsconfigRootDir : __dirname , project : [ \"./tsconfig.json\" ] }, plugins : [ \"@typescript-eslint\" ], extends : [ \"eslint:recommended\" , \"plugin:@typescript-eslint/recommended\" , \"plugin:@typescript-eslint/recommended-requiring-type-checking\" , \"prettier\" , \"prettier/@typescript-eslint\" ], rules : { \"@typescript-eslint/ban-types\" : [ \"error\" , { types : { \"object\" : false }, extendDefaults : true } ], \"@typescript-eslint/no-explicit-any\" : 0 , \"@typescript-eslint/no-non-null-assertion\" : 0 , \"@typescript-eslint/no-unsafe-assignment\" : 0 , \"@typescript-eslint/no-unsafe-call\" : 0 , \"@typescript-eslint/no-unsafe-member-access\" : 0 , \"@typescript-eslint/no-unsafe-return\" : 0 , \"@typescript-eslint/no-unused-vars\" : [ \"error\" , { \"argsIgnorePattern\" : \"^_\" } ] } }; .eslintignore 1 **/*.js This .gitattributes configuration will automatically collapse the generated JavaScript target files in GitHub\u2019s Diff view. You will not need it if you do not use git or GitHub. .gitattributes 1 files/js/**/*.js linguist-generated","title":"Additional Tools"},{"location":"javascript/typescript/#writing-a-simple-module","text":"After completing this initial set-up you can start writing your first TypeScript module. The TypeScript compiler can be launched in Watch Mode by running npx tsc -w . WoltLab Suite\u2019s modules can be imported using the standard ECMAScript module import syntax by specifying the full module name. The public API of the module can also be exported using the standard ECMAScript module export syntax. ts/Example.ts 1 2 3 4 5 import * as Language from \"WoltLabSuite/Core/Language\" ; export function run () { alert ( Language . get ( \"wcf.foo.bar\" )); } This simple example module will compile to plain JavaScript that is compatible with the AMD loader that is used by WoltLab Suite. files/js/Example.js 1 2 3 4 5 6 7 8 9 10 define ([ \"require\" , \"exports\" , \"tslib\" , \"WoltLabSuite/Core/Language\" ], function ( require , exports , tslib_1 , Language ) { \"use strict\" ; Object . defineProperty ( exports , \"__esModule\" , { value : true }); exports . run = void 0 ; Language = tslib_1 . __importStar ( Language ); function run () { alert ( Language . get ( \"wcf.foo.bar\" )); } exports . run = run ; }); Within templates it can be consumed as follows. 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"Example\" ], ( Example ) => { Example . run (); // Alerts the contents of the `wcf.foo.bar` phrase. }); </ script >","title":"Writing a simple module"},{"location":"migration/wcf21/css/","text":"WCF 2.1.x - CSS # The LESS compiler has been in use since WoltLab Community Framework 2.0, but was replaced with a SCSS compiler in WoltLab Suite 3.0. This change was motivated by SCSS becoming the de facto standard for CSS pre-processing and some really annoying shortcomings in the old LESS compiler. The entire CSS has been rewritten from scratch, please read the docs on CSS to learn what has changed.","title":"CSS"},{"location":"migration/wcf21/css/#wcf-21x-css","text":"The LESS compiler has been in use since WoltLab Community Framework 2.0, but was replaced with a SCSS compiler in WoltLab Suite 3.0. This change was motivated by SCSS becoming the de facto standard for CSS pre-processing and some really annoying shortcomings in the old LESS compiler. The entire CSS has been rewritten from scratch, please read the docs on CSS to learn what has changed.","title":"WCF 2.1.x - CSS"},{"location":"migration/wcf21/package/","text":"WCF 2.1.x - Package Components # package.xml # Short Instructions # Instructions can now omit the filename, causing them to use the default filename if defined by the package installation plugin (in short: PIP ). Unless overridden it will default to the PIP's class name with the first letter being lower-cased, e.g. EventListenerPackageInstallationPlugin implies the filename eventListener.xml . The file is always assumed to be in the archive's root, files located in subdirectories need to be explicitly stated, just as it worked before. Every PIP can define a custom filename if the default value cannot be properly derived. For example the ACPMenu -pip would default to aCPMenu.xml , requiring the class to explicitly override the default filename with acpMenu.xml for readability. Example # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <instructions type= \"install\" > <!-- assumes `eventListener.xml` --> <instruction type= \"eventListener\" /> <!-- assumes `install.sql` --> <instruction type= \"sql\" /> <!-- assumes `language/*.xml` --> <instruction type= \"language\" /> <!-- exceptions --> <!-- assumes `files.tar` --> <instruction type= \"file\" /> <!-- no default value, requires relative path --> <instruction type= \"script\" > acp/install_com.woltlab.wcf_3.0.php </instruction> </instructions> Exceptions # These exceptions represent the built-in PIPs only, 3rd party plugins and apps may define their own exceptions. PIP Default Value acpTemplate acptemplates.tar file files.tar language language/*.xml script (No default value) sql install.sql template templates.tar acpMenu.xml # Renamed Categories # The following categories have been renamed, menu items need to be adjusted to reflect the new names: Old Value New Value wcf.acp.menu.link.system wcf.acp.menu.link.configuration wcf.acp.menu.link.display wcf.acp.menu.link.customization wcf.acp.menu.link.community wcf.acp.menu.link.application Submenu Items # Menu items can now offer additional actions to be accessed from within the menu using an icon-based navigation. This step avoids filling the menu with dozens of Add \u2026 links, shifting the focus on to actual items. Adding more than one action is not recommended and you should at maximum specify two actions per item. Example # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <!-- category --> <acpmenuitem name= \"wcf.acp.menu.link.group\" > <parent> wcf.acp.menu.link.user </parent> <showorder> 2 </showorder> </acpmenuitem> <!-- menu item --> <acpmenuitem name= \"wcf.acp.menu.link.group.list\" > <controller> wcf\\acp\\page\\UserGroupListPage </controller> <parent> wcf.acp.menu.link.group </parent> <permissions> admin.user.canEditGroup,admin.user.canDeleteGroup </permissions> </acpmenuitem> <!-- menu item action --> <acpmenuitem name= \"wcf.acp.menu.link.group.add\" > <controller> wcf\\acp\\form\\UserGroupAddForm </controller> <!-- actions are defined by menu items of menu items --> <parent> wcf.acp.menu.link.group.list </parent> <permissions> admin.user.canAddGroup </permissions> <!-- required FontAwesome icon name used for display --> <icon> fa-plus </icon> </acpmenuitem> Common Icon Names # You should use the same icon names for the (logically) same task, unifying the meaning of items and making the actions predictable. Meaning Icon Name Result Add or create fa-plus Search fa-search Upload fa-upload box.xml # The box PIP has been added. cronjob.xml # Legacy cronjobs are assigned a non-deterministic generic name, the only way to assign them a name is removing them and then adding them again. Cronjobs can now be assigned a name using the name attribute as in <cronjob name=\"com.woltlab.wcf.refreshPackageUpdates\"> , it will be used to identify cronjobs during an update or delete. eventListener.xml # Legacy event listeners are assigned a non-deterministic generic name, the only way to assign them a name is removing them and then adding them again. Event listeners can now be assigned a name using the name attribute as in <eventlistener name=\"sessionPageAccessLog\"> , it will be used to identify event listeners during an update or delete. menu.xml # The menu PIP has been added. menuItem.xml # The menuItem PIP has been added. objectType.xml # The definition com.woltlab.wcf.user.dashboardContainer has been removed, it was previously used to register pages that qualify for dashboard boxes. Since WoltLab Suite 3.0, all pages registered through the page.xml are valid containers and therefore there is no need for this definition anymore. The definitions com.woltlab.wcf.page and com.woltlab.wcf.user.online.location have been superseded by the page.xml , they're no longer supported. option.xml # The module.display category has been renamed into module.customization . page.xml # The page PIP has been added. pageMenu.xml # The pageMenu.xml has been superseded by the page.xml and is no longer available.","title":"Package Components"},{"location":"migration/wcf21/package/#wcf-21x-package-components","text":"","title":"WCF 2.1.x - Package Components"},{"location":"migration/wcf21/package/#packagexml","text":"","title":"package.xml"},{"location":"migration/wcf21/package/#short-instructions","text":"Instructions can now omit the filename, causing them to use the default filename if defined by the package installation plugin (in short: PIP ). Unless overridden it will default to the PIP's class name with the first letter being lower-cased, e.g. EventListenerPackageInstallationPlugin implies the filename eventListener.xml . The file is always assumed to be in the archive's root, files located in subdirectories need to be explicitly stated, just as it worked before. Every PIP can define a custom filename if the default value cannot be properly derived. For example the ACPMenu -pip would default to aCPMenu.xml , requiring the class to explicitly override the default filename with acpMenu.xml for readability.","title":"Short Instructions"},{"location":"migration/wcf21/package/#example","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <instructions type= \"install\" > <!-- assumes `eventListener.xml` --> <instruction type= \"eventListener\" /> <!-- assumes `install.sql` --> <instruction type= \"sql\" /> <!-- assumes `language/*.xml` --> <instruction type= \"language\" /> <!-- exceptions --> <!-- assumes `files.tar` --> <instruction type= \"file\" /> <!-- no default value, requires relative path --> <instruction type= \"script\" > acp/install_com.woltlab.wcf_3.0.php </instruction> </instructions>","title":"Example"},{"location":"migration/wcf21/package/#exceptions","text":"These exceptions represent the built-in PIPs only, 3rd party plugins and apps may define their own exceptions. PIP Default Value acpTemplate acptemplates.tar file files.tar language language/*.xml script (No default value) sql install.sql template templates.tar","title":"Exceptions"},{"location":"migration/wcf21/package/#acpmenuxml","text":"","title":"acpMenu.xml"},{"location":"migration/wcf21/package/#renamed-categories","text":"The following categories have been renamed, menu items need to be adjusted to reflect the new names: Old Value New Value wcf.acp.menu.link.system wcf.acp.menu.link.configuration wcf.acp.menu.link.display wcf.acp.menu.link.customization wcf.acp.menu.link.community wcf.acp.menu.link.application","title":"Renamed Categories"},{"location":"migration/wcf21/package/#submenu-items","text":"Menu items can now offer additional actions to be accessed from within the menu using an icon-based navigation. This step avoids filling the menu with dozens of Add \u2026 links, shifting the focus on to actual items. Adding more than one action is not recommended and you should at maximum specify two actions per item.","title":"Submenu Items"},{"location":"migration/wcf21/package/#example_1","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <!-- category --> <acpmenuitem name= \"wcf.acp.menu.link.group\" > <parent> wcf.acp.menu.link.user </parent> <showorder> 2 </showorder> </acpmenuitem> <!-- menu item --> <acpmenuitem name= \"wcf.acp.menu.link.group.list\" > <controller> wcf\\acp\\page\\UserGroupListPage </controller> <parent> wcf.acp.menu.link.group </parent> <permissions> admin.user.canEditGroup,admin.user.canDeleteGroup </permissions> </acpmenuitem> <!-- menu item action --> <acpmenuitem name= \"wcf.acp.menu.link.group.add\" > <controller> wcf\\acp\\form\\UserGroupAddForm </controller> <!-- actions are defined by menu items of menu items --> <parent> wcf.acp.menu.link.group.list </parent> <permissions> admin.user.canAddGroup </permissions> <!-- required FontAwesome icon name used for display --> <icon> fa-plus </icon> </acpmenuitem>","title":"Example"},{"location":"migration/wcf21/package/#common-icon-names","text":"You should use the same icon names for the (logically) same task, unifying the meaning of items and making the actions predictable. Meaning Icon Name Result Add or create fa-plus Search fa-search Upload fa-upload","title":"Common Icon Names"},{"location":"migration/wcf21/package/#boxxml","text":"The box PIP has been added.","title":"box.xml"},{"location":"migration/wcf21/package/#cronjobxml","text":"Legacy cronjobs are assigned a non-deterministic generic name, the only way to assign them a name is removing them and then adding them again. Cronjobs can now be assigned a name using the name attribute as in <cronjob name=\"com.woltlab.wcf.refreshPackageUpdates\"> , it will be used to identify cronjobs during an update or delete.","title":"cronjob.xml"},{"location":"migration/wcf21/package/#eventlistenerxml","text":"Legacy event listeners are assigned a non-deterministic generic name, the only way to assign them a name is removing them and then adding them again. Event listeners can now be assigned a name using the name attribute as in <eventlistener name=\"sessionPageAccessLog\"> , it will be used to identify event listeners during an update or delete.","title":"eventListener.xml"},{"location":"migration/wcf21/package/#menuxml","text":"The menu PIP has been added.","title":"menu.xml"},{"location":"migration/wcf21/package/#menuitemxml","text":"The menuItem PIP has been added.","title":"menuItem.xml"},{"location":"migration/wcf21/package/#objecttypexml","text":"The definition com.woltlab.wcf.user.dashboardContainer has been removed, it was previously used to register pages that qualify for dashboard boxes. Since WoltLab Suite 3.0, all pages registered through the page.xml are valid containers and therefore there is no need for this definition anymore. The definitions com.woltlab.wcf.page and com.woltlab.wcf.user.online.location have been superseded by the page.xml , they're no longer supported.","title":"objectType.xml"},{"location":"migration/wcf21/package/#optionxml","text":"The module.display category has been renamed into module.customization .","title":"option.xml"},{"location":"migration/wcf21/package/#pagexml","text":"The page PIP has been added.","title":"page.xml"},{"location":"migration/wcf21/package/#pagemenuxml","text":"The pageMenu.xml has been superseded by the page.xml and is no longer available.","title":"pageMenu.xml"},{"location":"migration/wcf21/php/","text":"WCF 2.1.x - PHP # Message Processing # WoltLab Suite 3.0 finally made the transition from raw bbcode to bbcode-flavored HTML, with many new features related to message processing being added. This change impacts both message validation and storing, requiring slightly different APIs to get the job done. Input Processing for Storage # The returned HTML is an intermediate representation with a maximum of meta data embedded into it, designed to be stored in the database. Some bbcodes are replaced during this process, for example [b]\u2026[/b] becomes <strong>\u2026</strong> , while others are converted into a metacode tag for later processing. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $message , $messageObjectType , $messageObjectID ); $html = $processor -> getHtml (); The $messageObjectID can be zero if the element did not exist before, but it should be non-zero when saving an edited message. Embedded Objects # Embedded objects need to be registered after saving the message, but once again you can use the processor instance to do the job. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $message , $messageObjectType , $messageObjectID ); $html = $processor -> getHtml (); // at this point the message is saved to database and the created object // `$example` is a `DatabaseObject` with the id column `$exampleID` $processor -> setObjectID ( $example -> exampleID ); if ( \\wcf\\system\\message\\embedded\\object\\MessageEmbeddedObjectManager :: getInstance () -> registerObjects ( $processor )) { // there is at least one embedded object, this is also the point at which you // would set `hasEmbeddedObjects` to true (if implemented by your type) ( new \\wcf\\data\\example\\ExampleEditor ( $example )) -> update ([ 'hasEmbeddedObjects' => 1 ]); } Rendering the Message # The output processor will parse the intermediate HTML and finalize the output for display. This step is highly dynamic and allows for bbcode evaluation and contextual output based on the viewer's permissions. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> process ( $html , $messageObjectType , $messageObjectID ); $renderedHtml = $processor -> getHtml (); Simplified Output # At some point there can be the need of a simplified output HTML that includes only basic HTML formatting and reduces more sophisticated bbcodes into a simpler representation. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> setOutputType ( 'text/simplified-html' ); $processor -> process ( \u2026 ); Plaintext Output # The text/plain output type will strip down the simplified HTML into pure text, suitable for text-only output such as the plaintext representation of an email. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> setOutputType ( 'text/plain' ); $processor -> process ( \u2026 ); Rebuilding Data # Converting from BBCode # Enabling message conversion for HTML messages is undefined and yields unexpected results. Legacy message that still use raw bbcodes must be converted to be properly parsed by the html processors. This process is enabled by setting the fourth parameter of process() to true . 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $html , $messageObjectType , $messageObjectID , true ); $renderedHtml = $processor -> getHtml (); Extracting Embedded Objects # The process() method of the input processor is quite expensive, as it runs through the full message validation including the invocation of HTMLPurifier. This is perfectly fine when dealing with single messages, but when you're handling messages in bulk to extract their embedded objects, you're better of with processEmbeddedContent() . This method deconstructs the message, but skips all validation and expects the input to be perfectly valid, that is the output of a previous run of process() saved to storage. 1 2 3 4 5 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> processEmbeddedContent ( $html , $messageObjectType , $messageObjectID ); // invoke `MessageEmbeddedObjectManager::registerObjects` here Breadcrumbs / Page Location # Breadcrumbs used to be added left to right, but parent locations are added from the bottom to the top, starting with the first ancestor and going upwards. In most cases you simply need to reverse the order. Breadcrumbs used to be a lose collection of arbitrary links, but are now represented by actual page objects and the control has shifted over to the PageLocationManager . 1 2 3 4 5 6 <? php // before \\wcf\\system\\WCF :: getBreadcrumbs () -> add ( new \\wcf\\system\\breadcrumb\\Breadcrumb ( 'title' , 'link' )); // after \\wcf\\system\\page\\PageLocationManager :: getInstance () -> addParentLocation ( $pageIdentifier , $pageObjectID , $object ); Pages and Forms # The property $activeMenuItem has been deprecated for the front end and is no longer evaluated at runtime. Recognition of the active item is entirely based around the invoked controller class name and its definition in the page table. You need to properly register your pages for this feature to work. Search # ISearchableObjectType # Added the setLocation() method that is used to set the current page location based on the search result. SearchIndexManager # The methods SearchIndexManager::add() and SearchIndexManager::update() have been deprecated and forward their call to the new method SearchIndexManager::set() .","title":"PHP API"},{"location":"migration/wcf21/php/#wcf-21x-php","text":"","title":"WCF 2.1.x - PHP"},{"location":"migration/wcf21/php/#message-processing","text":"WoltLab Suite 3.0 finally made the transition from raw bbcode to bbcode-flavored HTML, with many new features related to message processing being added. This change impacts both message validation and storing, requiring slightly different APIs to get the job done.","title":"Message Processing"},{"location":"migration/wcf21/php/#input-processing-for-storage","text":"The returned HTML is an intermediate representation with a maximum of meta data embedded into it, designed to be stored in the database. Some bbcodes are replaced during this process, for example [b]\u2026[/b] becomes <strong>\u2026</strong> , while others are converted into a metacode tag for later processing. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $message , $messageObjectType , $messageObjectID ); $html = $processor -> getHtml (); The $messageObjectID can be zero if the element did not exist before, but it should be non-zero when saving an edited message.","title":"Input Processing for Storage"},{"location":"migration/wcf21/php/#embedded-objects","text":"Embedded objects need to be registered after saving the message, but once again you can use the processor instance to do the job. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $message , $messageObjectType , $messageObjectID ); $html = $processor -> getHtml (); // at this point the message is saved to database and the created object // `$example` is a `DatabaseObject` with the id column `$exampleID` $processor -> setObjectID ( $example -> exampleID ); if ( \\wcf\\system\\message\\embedded\\object\\MessageEmbeddedObjectManager :: getInstance () -> registerObjects ( $processor )) { // there is at least one embedded object, this is also the point at which you // would set `hasEmbeddedObjects` to true (if implemented by your type) ( new \\wcf\\data\\example\\ExampleEditor ( $example )) -> update ([ 'hasEmbeddedObjects' => 1 ]); }","title":"Embedded Objects"},{"location":"migration/wcf21/php/#rendering-the-message","text":"The output processor will parse the intermediate HTML and finalize the output for display. This step is highly dynamic and allows for bbcode evaluation and contextual output based on the viewer's permissions. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> process ( $html , $messageObjectType , $messageObjectID ); $renderedHtml = $processor -> getHtml ();","title":"Rendering the Message"},{"location":"migration/wcf21/php/#simplified-output","text":"At some point there can be the need of a simplified output HTML that includes only basic HTML formatting and reduces more sophisticated bbcodes into a simpler representation. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> setOutputType ( 'text/simplified-html' ); $processor -> process ( \u2026 );","title":"Simplified Output"},{"location":"migration/wcf21/php/#plaintext-output","text":"The text/plain output type will strip down the simplified HTML into pure text, suitable for text-only output such as the plaintext representation of an email. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> setOutputType ( 'text/plain' ); $processor -> process ( \u2026 );","title":"Plaintext Output"},{"location":"migration/wcf21/php/#rebuilding-data","text":"","title":"Rebuilding Data"},{"location":"migration/wcf21/php/#converting-from-bbcode","text":"Enabling message conversion for HTML messages is undefined and yields unexpected results. Legacy message that still use raw bbcodes must be converted to be properly parsed by the html processors. This process is enabled by setting the fourth parameter of process() to true . 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $html , $messageObjectType , $messageObjectID , true ); $renderedHtml = $processor -> getHtml ();","title":"Converting from BBCode"},{"location":"migration/wcf21/php/#extracting-embedded-objects","text":"The process() method of the input processor is quite expensive, as it runs through the full message validation including the invocation of HTMLPurifier. This is perfectly fine when dealing with single messages, but when you're handling messages in bulk to extract their embedded objects, you're better of with processEmbeddedContent() . This method deconstructs the message, but skips all validation and expects the input to be perfectly valid, that is the output of a previous run of process() saved to storage. 1 2 3 4 5 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> processEmbeddedContent ( $html , $messageObjectType , $messageObjectID ); // invoke `MessageEmbeddedObjectManager::registerObjects` here","title":"Extracting Embedded Objects"},{"location":"migration/wcf21/php/#breadcrumbs-page-location","text":"Breadcrumbs used to be added left to right, but parent locations are added from the bottom to the top, starting with the first ancestor and going upwards. In most cases you simply need to reverse the order. Breadcrumbs used to be a lose collection of arbitrary links, but are now represented by actual page objects and the control has shifted over to the PageLocationManager . 1 2 3 4 5 6 <? php // before \\wcf\\system\\WCF :: getBreadcrumbs () -> add ( new \\wcf\\system\\breadcrumb\\Breadcrumb ( 'title' , 'link' )); // after \\wcf\\system\\page\\PageLocationManager :: getInstance () -> addParentLocation ( $pageIdentifier , $pageObjectID , $object );","title":"Breadcrumbs / Page Location"},{"location":"migration/wcf21/php/#pages-and-forms","text":"The property $activeMenuItem has been deprecated for the front end and is no longer evaluated at runtime. Recognition of the active item is entirely based around the invoked controller class name and its definition in the page table. You need to properly register your pages for this feature to work.","title":"Pages and Forms"},{"location":"migration/wcf21/php/#search","text":"","title":"Search"},{"location":"migration/wcf21/php/#isearchableobjecttype","text":"Added the setLocation() method that is used to set the current page location based on the search result.","title":"ISearchableObjectType"},{"location":"migration/wcf21/php/#searchindexmanager","text":"The methods SearchIndexManager::add() and SearchIndexManager::update() have been deprecated and forward their call to the new method SearchIndexManager::set() .","title":"SearchIndexManager"},{"location":"migration/wcf21/templates/","text":"WCF 2.1.x - Templates # Page Layout # The template structure has been overhauled and it is no longer required nor recommended to include internal templates, such as documentHeader , headInclude or userNotice . Instead use a simple {include file='header'} that now takes care of of the entire application frame. Templates must not include a trailing </body></html> after including the footer template. The documentHeader , headInclude and userNotice template should no longer be included manually, the same goes with the <body> element, please use {include file='header'} instead. The sidebarOrientation variable for the header template has been removed and no longer works. header.boxHeadline has been unified and now reads header.contentHeader Please see the full example at the end of this page for more information. Sidebars # Sidebars are now dynamically populated by the box system, this requires a small change to unify the markup. Additionally the usage of <fieldset> has been deprecated due to browser inconsistencies and bugs and should be replaced with section.box . Previous markup used in WoltLab Community Framework 2.1 and earlier: 1 2 3 4 5 6 7 < fieldset > < legend > <!-- Title --> </ legend > < div > <!-- Content --> </ div > </ fieldset > The new markup since WoltLab Suite 3.0: 1 2 3 4 5 6 7 < section class = \"box\" > < h2 class = \"boxTitle\" > <!-- Title --> </ h2 > < div class = \"boxContent\" > <!-- Content --> </ div > </ section > Forms # The input tag for session ids SID_INPUT_TAG has been deprecated and no longer yields any content, it can be safely removed. In previous versions forms have been wrapped in <div class=\"container containerPadding marginTop\">\u2026</div> which no longer has any effect and should be removed. If you're using the preview feature for WYSIWYG-powered input fields, you need to alter the preview button include instruction: 1 { include file = 'messageFormPreviewButton' previewMessageObjectType = 'com.example.foo.bar' previewMessageObjectID = 0 } The message object id should be non-zero when editing. Icons # The old .icon-<iconName> classes have been removed, you are required to use the official .fa-<iconName> class names from FontAwesome. This does not affect the generic classes .icon (indicates an icon) and .icon<size> (e.g. .icon16 that sets the dimensions), these are still required and have not been deprecated. Before: 1 < span class = \"icon icon16 icon-list\" > Now: 1 < span class = \"icon icon16 fa-list\" > Changed Icon Names # Quite a few icon names have been renamed, the official wiki lists the new icon names in FontAwesome 4. Changed Classes # .dataList has been replaced and should now read <ol class=\"inlineList commaSeparated\"> (same applies to <ul> ) .framedIconList has been changed into .userAvatarList Removed Elements and Classes # <nav class=\"jsClipboardEditor\"> and <div class=\"jsClipboardContainer\"> have been replaced with a floating button. The anchors a.toTopLink have been replaced with a floating button. Avatars should no longer receive the class framed The dl.condensed class, as seen in the editor tab menu, is no longer required. Anything related to sidebarCollapsed has been removed as sidebars are no longer collapsible. Simple Example # The code below includes only the absolute minimum required to display a page, the content title is already included in the output. 1 2 3 4 5 6 7 { include file = 'header' } <div class=\"section\"> Hello World! </div> { include file = 'footer' } Full Example # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 { * The page title is automatically set using the page definition, avoid setting it if you can! If you really need to modify the title, you can still reference the original title with: {$__wcf->getActivePage()->getTitle()} * } { capture assign = 'pageTitle' } Custom Page Title { /capture } { * NOTICE: The content header goes here, see the section after this to learn more. * } { * you must not use `headContent` for JavaScript * } { capture assign = 'headContent' } <link rel=\"alternate\" type=\"application/rss+xml\" title=\" { lang } wcf.global.button.rss { /lang } \" href=\"\u2026\"> { /capture } { * optional, content will be added to the top of the left sidebar * } { capture assign = 'sidebarLeft' } \u2026 { event name = 'boxes' } { /capture } { * optional, content will be added to the top of the right sidebar * } { capture assign = 'sidebarRight' } \u2026 { event name = 'boxes' } { /capture } { capture assign = 'headerNavigation' } <li><a href=\"#\" title=\"Custom Button\" class=\"jsTooltip\"><span class=\"icon icon16 fa-check\"></span> <span class=\"invisible\">Custom Button</span></a></li> { /capture } { include file = 'header' } { hascontent } <div class=\"paginationTop\"> { content } { pages \u2026 } { /content } </div> { /hascontent } { * the actual content * } <div class=\"section\"> \u2026 </div> <footer class=\"contentFooter\"> { * skip this if you're not using any pagination * } { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } <nav class=\"contentFooterNavigation\"> <ul> <li><a href=\"\u2026\" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span>Custom Button</span></a></li> { event name = 'contentFooterNavigation' } </ul> </nav> </footer> <script data-relocate=\"true\"> /* any JavaScript code you need */ </script> { * do not include `</body></html>` here, the footer template is the last bit of code! * } { include file = 'footer' } Content Header # There are two different methods to set the content header, one sets only the actual values, but leaves the outer HTML untouched, that is generated by the header template. This is the recommended approach and you should avoid using the alternative method whenever possible. Recommended Approach # 1 2 3 4 5 6 { * This is automatically set using the page data and should not be set manually! * } { capture assign = 'contentTitle' } Custom Content Title { /capture } { capture assign = 'contentDescription' } Optional description that is displayed right after the title. { /capture } { capture assign = 'contentHeaderNavigation' } List of navigation buttons displayed right next to the title. { /capture } Alternative # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { capture assign = 'contentHeader' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\">Custom Content Title</h1> <p class=\"contentHeaderDescription\">Custom Content Description</p> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'CustomController' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span>Custom Button</span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { /capture }","title":"Templates"},{"location":"migration/wcf21/templates/#wcf-21x-templates","text":"","title":"WCF 2.1.x - Templates"},{"location":"migration/wcf21/templates/#page-layout","text":"The template structure has been overhauled and it is no longer required nor recommended to include internal templates, such as documentHeader , headInclude or userNotice . Instead use a simple {include file='header'} that now takes care of of the entire application frame. Templates must not include a trailing </body></html> after including the footer template. The documentHeader , headInclude and userNotice template should no longer be included manually, the same goes with the <body> element, please use {include file='header'} instead. The sidebarOrientation variable for the header template has been removed and no longer works. header.boxHeadline has been unified and now reads header.contentHeader Please see the full example at the end of this page for more information.","title":"Page Layout"},{"location":"migration/wcf21/templates/#sidebars","text":"Sidebars are now dynamically populated by the box system, this requires a small change to unify the markup. Additionally the usage of <fieldset> has been deprecated due to browser inconsistencies and bugs and should be replaced with section.box . Previous markup used in WoltLab Community Framework 2.1 and earlier: 1 2 3 4 5 6 7 < fieldset > < legend > <!-- Title --> </ legend > < div > <!-- Content --> </ div > </ fieldset > The new markup since WoltLab Suite 3.0: 1 2 3 4 5 6 7 < section class = \"box\" > < h2 class = \"boxTitle\" > <!-- Title --> </ h2 > < div class = \"boxContent\" > <!-- Content --> </ div > </ section >","title":"Sidebars"},{"location":"migration/wcf21/templates/#forms","text":"The input tag for session ids SID_INPUT_TAG has been deprecated and no longer yields any content, it can be safely removed. In previous versions forms have been wrapped in <div class=\"container containerPadding marginTop\">\u2026</div> which no longer has any effect and should be removed. If you're using the preview feature for WYSIWYG-powered input fields, you need to alter the preview button include instruction: 1 { include file = 'messageFormPreviewButton' previewMessageObjectType = 'com.example.foo.bar' previewMessageObjectID = 0 } The message object id should be non-zero when editing.","title":"Forms"},{"location":"migration/wcf21/templates/#icons","text":"The old .icon-<iconName> classes have been removed, you are required to use the official .fa-<iconName> class names from FontAwesome. This does not affect the generic classes .icon (indicates an icon) and .icon<size> (e.g. .icon16 that sets the dimensions), these are still required and have not been deprecated. Before: 1 < span class = \"icon icon16 icon-list\" > Now: 1 < span class = \"icon icon16 fa-list\" >","title":"Icons"},{"location":"migration/wcf21/templates/#changed-icon-names","text":"Quite a few icon names have been renamed, the official wiki lists the new icon names in FontAwesome 4.","title":"Changed Icon Names"},{"location":"migration/wcf21/templates/#changed-classes","text":".dataList has been replaced and should now read <ol class=\"inlineList commaSeparated\"> (same applies to <ul> ) .framedIconList has been changed into .userAvatarList","title":"Changed Classes"},{"location":"migration/wcf21/templates/#removed-elements-and-classes","text":"<nav class=\"jsClipboardEditor\"> and <div class=\"jsClipboardContainer\"> have been replaced with a floating button. The anchors a.toTopLink have been replaced with a floating button. Avatars should no longer receive the class framed The dl.condensed class, as seen in the editor tab menu, is no longer required. Anything related to sidebarCollapsed has been removed as sidebars are no longer collapsible.","title":"Removed Elements and Classes"},{"location":"migration/wcf21/templates/#simple-example","text":"The code below includes only the absolute minimum required to display a page, the content title is already included in the output. 1 2 3 4 5 6 7 { include file = 'header' } <div class=\"section\"> Hello World! </div> { include file = 'footer' }","title":"Simple Example"},{"location":"migration/wcf21/templates/#full-example","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 { * The page title is automatically set using the page definition, avoid setting it if you can! If you really need to modify the title, you can still reference the original title with: {$__wcf->getActivePage()->getTitle()} * } { capture assign = 'pageTitle' } Custom Page Title { /capture } { * NOTICE: The content header goes here, see the section after this to learn more. * } { * you must not use `headContent` for JavaScript * } { capture assign = 'headContent' } <link rel=\"alternate\" type=\"application/rss+xml\" title=\" { lang } wcf.global.button.rss { /lang } \" href=\"\u2026\"> { /capture } { * optional, content will be added to the top of the left sidebar * } { capture assign = 'sidebarLeft' } \u2026 { event name = 'boxes' } { /capture } { * optional, content will be added to the top of the right sidebar * } { capture assign = 'sidebarRight' } \u2026 { event name = 'boxes' } { /capture } { capture assign = 'headerNavigation' } <li><a href=\"#\" title=\"Custom Button\" class=\"jsTooltip\"><span class=\"icon icon16 fa-check\"></span> <span class=\"invisible\">Custom Button</span></a></li> { /capture } { include file = 'header' } { hascontent } <div class=\"paginationTop\"> { content } { pages \u2026 } { /content } </div> { /hascontent } { * the actual content * } <div class=\"section\"> \u2026 </div> <footer class=\"contentFooter\"> { * skip this if you're not using any pagination * } { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } <nav class=\"contentFooterNavigation\"> <ul> <li><a href=\"\u2026\" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span>Custom Button</span></a></li> { event name = 'contentFooterNavigation' } </ul> </nav> </footer> <script data-relocate=\"true\"> /* any JavaScript code you need */ </script> { * do not include `</body></html>` here, the footer template is the last bit of code! * } { include file = 'footer' }","title":"Full Example"},{"location":"migration/wcf21/templates/#content-header","text":"There are two different methods to set the content header, one sets only the actual values, but leaves the outer HTML untouched, that is generated by the header template. This is the recommended approach and you should avoid using the alternative method whenever possible.","title":"Content Header"},{"location":"migration/wcf21/templates/#recommended-approach","text":"1 2 3 4 5 6 { * This is automatically set using the page data and should not be set manually! * } { capture assign = 'contentTitle' } Custom Content Title { /capture } { capture assign = 'contentDescription' } Optional description that is displayed right after the title. { /capture } { capture assign = 'contentHeaderNavigation' } List of navigation buttons displayed right next to the title. { /capture }","title":"Recommended Approach"},{"location":"migration/wcf21/templates/#alternative","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { capture assign = 'contentHeader' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\">Custom Content Title</h1> <p class=\"contentHeaderDescription\">Custom Content Description</p> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'CustomController' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span>Custom Button</span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { /capture }","title":"Alternative"},{"location":"migration/wsc30/css/","text":"Migrating from WSC 3.0 - CSS # New Style Variables # The new style variables are only applied to styles that have the compatibility set to WSC 3.1 wcfContentContainer # The page content is encapsulated in a new container that wraps around the inner content, but excludes the sidebars, header and page navigation elements. $wcfContentContainerBackground - background color $wcfContentContainerBorder - border color wcfEditorButton # These variables control the appearance of the editor toolbar and its buttons. $wcfEditorButtonBackground - button and toolbar background color $wcfEditorButtonBackgroundActive - active button background color $wcfEditorButtonText - text color for available buttons $wcfEditorButtonTextActive - text color for active buttons $wcfEditorButtonTextDisabled - text color for disabled buttons Color Variables in alert.scss # The color values for <small class=\"innerError\"> used to be hardcoded values, but have now been changed to use the values for error messages ( wcfStatusError* ) instead.","title":"CSS"},{"location":"migration/wsc30/css/#migrating-from-wsc-30-css","text":"","title":"Migrating from WSC 3.0 - CSS"},{"location":"migration/wsc30/css/#new-style-variables","text":"The new style variables are only applied to styles that have the compatibility set to WSC 3.1","title":"New Style Variables"},{"location":"migration/wsc30/css/#wcfcontentcontainer","text":"The page content is encapsulated in a new container that wraps around the inner content, but excludes the sidebars, header and page navigation elements. $wcfContentContainerBackground - background color $wcfContentContainerBorder - border color","title":"wcfContentContainer"},{"location":"migration/wsc30/css/#wcfeditorbutton","text":"These variables control the appearance of the editor toolbar and its buttons. $wcfEditorButtonBackground - button and toolbar background color $wcfEditorButtonBackgroundActive - active button background color $wcfEditorButtonText - text color for available buttons $wcfEditorButtonTextActive - text color for active buttons $wcfEditorButtonTextDisabled - text color for disabled buttons","title":"wcfEditorButton"},{"location":"migration/wsc30/css/#color-variables-in-alertscss","text":"The color values for <small class=\"innerError\"> used to be hardcoded values, but have now been changed to use the values for error messages ( wcfStatusError* ) instead.","title":"Color Variables in alert.scss"},{"location":"migration/wsc30/javascript/","text":"Migrating from WSC 3.0 - JavaScript # Accelerated Guest View / Tiny Builds # The new tiny builds are highly optimized variants of existing JavaScript files and modules, aiming for significant performance improvements for guests and search engines alike. This is accomplished by heavily restricting page interaction to read-only actions whenever possible, which in return removes the need to provide certain JavaScript modules in general. For example, disallowing guests to write any formatted messages will in return remove the need to provide the WYSIWYG editor at all. But it doesn't stop there, there are a lot of other modules that provide additional features for the editor, and by excluding the editor, we can also exclude these modules too. Long story short, the tiny mode guarantees that certain actions will never be carried out by guests or search engines, therefore some modules are not going to be needed by them ever. Code Templates for Tiny Builds # The following examples assume that you use the virtual constant COMPILER_TARGET_DEFAULT as a switch for the optimized code path. This is also the constant used by the official build scripts for JavaScript files . We recommend that you provide a mock implementation for existing code to ensure 3rd party compatibility. It is enough to provide a bare object or class that exposes the original properties using the same primitive data types. This is intended to provide a soft-fail for implementations that are not aware of the tiny mode yet, but is not required for classes that did not exist until now. Legacy JavaScript # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 if ( COMPILER_TARGET_DEFAULT ) { WCF . Example . Foo = { makeSnafucated : function () { return \"Hello World\" ; } }; WCF . Example . Bar = Class . extend ({ foobar : \"baz\" , foo : function ( $bar ) { return $bar + this . foobar ; } }); } else { WCF . Example . Foo = { makeSnafucated : function () {} }; WCF . Example . Bar = Class . extend ({ foobar : \"\" , foo : function () {} }); } require.js Modules # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 define ([ \"some\" , \"fancy\" , \"dependencies\" ], function ( Some , Fancy , Dependencies ) { \"use strict\" ; if ( ! COMPILER_TARGET_DEFAULT ) { var Fake = function () {}; Fake . prototype = { init : function () {}, makeSnafucated : function () {} }; return Fake ; } function MyAwesomeClass ( niceArgument ) { this . init ( niceArgument ); } MyAwesomeClass . prototype = { init : function ( niceArgument ) { if ( niceArgument ) { this . makeSnafucated (); } }, makeSnafucated : function () { console . log ( \"Hello World\" ); } } return MyAwesomeClass ; }); Including tinified builds through {js} # The {js} template-plugin has been updated to include support for tiny builds controlled through the optional flag hasTiny=true : 1 {js application='wcf' file='WCF.Example' hasTiny=true} This line generates a different output depending on the debug mode and the user login-state. Real Error Messages for AJAX Responses # The errorMessage property in the returned response object for failed AJAX requests contained an exception-specific but still highly generic error message. This issue has been around for quite a long time and countless of implementations are relying on this false behavior, eventually forcing us to leave the value unchanged. This problem is solved by adding the new property realErrorMessage that exposes the message exactly as it was provided and now matches the value that would be displayed to users in traditional forms. Example Code # 1 2 3 4 5 6 7 8 9 define ([ 'Ajax' ], function ( Ajax ) { return { // ... _ajaxFailure : function ( responseData , responseText , xhr , requestData ) { console . log ( responseData . realErrorMessage ); } // ... }; }); Simplified Form Submit in Dialogs # Forms embedded in dialogs often do not contain the HTML <form> -element and instead rely on JavaScript click- and key-handlers to emulate a <form> -like submit behavior. This has spawned a great amount of nearly identical implementations that all aim to handle the form submit through the Enter -key, still leaving some dialogs behind. WoltLab Suite 3.1 offers automatic form submit that is enabled through a set of specific conditions and data attributes: There must be a submit button that matches the selector .formSubmit > input[type=\"submit\"], .formSubmit > button[data-type=\"submit\"] . The dialog object provided to UiDialog.open() implements the method _dialogSubmit() . Input fields require the attribute data-dialog-submit-on-enter=\"true\" to be set, the type must be one of number , password , search , tel , text or url . Clicking on the submit button or pressing the Enter -key in any watched input field will start the submit process. This is done automatically and does not require a manual interaction in your code, therefore you should not bind any click listeners on the submit button yourself. Any input field with the required attribute set will be validated to contain a non-empty string after processing the value with String.prototype.trim() . An empty field will abort the submit process and display a visible error message next to the offending field. Helper Function for Inline Error Messages # Displaying inline error messages on-the-fly required quite a few DOM operations that were quite simple but also super repetitive and thus error-prone when incorrectly copied over. The global helper function elInnerError() was added to provide a simple and consistent behavior of inline error messages. You can display an error message by invoking elInnerError(elementRef, \"Your Error Message\") , it will insert a new <small class=\"innerError\"> and sets the given message. If there is already an inner error present, then the message will be replaced instead. Hiding messages is done by setting the 2nd parameter to false or an empty string: elInnerError(elementRef, false) elInnerError(elementRef, '') The special values null and undefined are supported too, but their usage is discouraged, because they make it harder to understand the intention by reading the code: elInnerError(elementRef, null) elInnerError(elementRef) Example Code # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 require ([ 'Language' ], function ( Language )) { var input = elBySel ( 'input[type=\"text\"]' ); if ( input . value . trim () === '' ) { // displays a new inline error or replaces the message if there is one already elInnerError ( input , Language . get ( 'wcf.global.form.error.empty' )); } else { // removes the inline error if it exists elInnerError ( input , false ); } // the above condition is equivalent to this: elInnerError ( input , ( input . value . trim () === '' ? Language . get ( 'wcf.global.form.error.empty' ) : false )); }","title":"JavaScript API"},{"location":"migration/wsc30/javascript/#migrating-from-wsc-30-javascript","text":"","title":"Migrating from WSC 3.0 - JavaScript"},{"location":"migration/wsc30/javascript/#accelerated-guest-view-tiny-builds","text":"The new tiny builds are highly optimized variants of existing JavaScript files and modules, aiming for significant performance improvements for guests and search engines alike. This is accomplished by heavily restricting page interaction to read-only actions whenever possible, which in return removes the need to provide certain JavaScript modules in general. For example, disallowing guests to write any formatted messages will in return remove the need to provide the WYSIWYG editor at all. But it doesn't stop there, there are a lot of other modules that provide additional features for the editor, and by excluding the editor, we can also exclude these modules too. Long story short, the tiny mode guarantees that certain actions will never be carried out by guests or search engines, therefore some modules are not going to be needed by them ever.","title":"Accelerated Guest View / Tiny Builds"},{"location":"migration/wsc30/javascript/#code-templates-for-tiny-builds","text":"The following examples assume that you use the virtual constant COMPILER_TARGET_DEFAULT as a switch for the optimized code path. This is also the constant used by the official build scripts for JavaScript files . We recommend that you provide a mock implementation for existing code to ensure 3rd party compatibility. It is enough to provide a bare object or class that exposes the original properties using the same primitive data types. This is intended to provide a soft-fail for implementations that are not aware of the tiny mode yet, but is not required for classes that did not exist until now.","title":"Code Templates for Tiny Builds"},{"location":"migration/wsc30/javascript/#legacy-javascript","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 if ( COMPILER_TARGET_DEFAULT ) { WCF . Example . Foo = { makeSnafucated : function () { return \"Hello World\" ; } }; WCF . Example . Bar = Class . extend ({ foobar : \"baz\" , foo : function ( $bar ) { return $bar + this . foobar ; } }); } else { WCF . Example . Foo = { makeSnafucated : function () {} }; WCF . Example . Bar = Class . extend ({ foobar : \"\" , foo : function () {} }); }","title":"Legacy JavaScript"},{"location":"migration/wsc30/javascript/#requirejs-modules","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 define ([ \"some\" , \"fancy\" , \"dependencies\" ], function ( Some , Fancy , Dependencies ) { \"use strict\" ; if ( ! COMPILER_TARGET_DEFAULT ) { var Fake = function () {}; Fake . prototype = { init : function () {}, makeSnafucated : function () {} }; return Fake ; } function MyAwesomeClass ( niceArgument ) { this . init ( niceArgument ); } MyAwesomeClass . prototype = { init : function ( niceArgument ) { if ( niceArgument ) { this . makeSnafucated (); } }, makeSnafucated : function () { console . log ( \"Hello World\" ); } } return MyAwesomeClass ; });","title":"require.js Modules"},{"location":"migration/wsc30/javascript/#including-tinified-builds-through-js","text":"The {js} template-plugin has been updated to include support for tiny builds controlled through the optional flag hasTiny=true : 1 {js application='wcf' file='WCF.Example' hasTiny=true} This line generates a different output depending on the debug mode and the user login-state.","title":"Including tinified builds through {js}"},{"location":"migration/wsc30/javascript/#real-error-messages-for-ajax-responses","text":"The errorMessage property in the returned response object for failed AJAX requests contained an exception-specific but still highly generic error message. This issue has been around for quite a long time and countless of implementations are relying on this false behavior, eventually forcing us to leave the value unchanged. This problem is solved by adding the new property realErrorMessage that exposes the message exactly as it was provided and now matches the value that would be displayed to users in traditional forms.","title":"Real Error Messages for AJAX Responses"},{"location":"migration/wsc30/javascript/#example-code","text":"1 2 3 4 5 6 7 8 9 define ([ 'Ajax' ], function ( Ajax ) { return { // ... _ajaxFailure : function ( responseData , responseText , xhr , requestData ) { console . log ( responseData . realErrorMessage ); } // ... }; });","title":"Example Code"},{"location":"migration/wsc30/javascript/#simplified-form-submit-in-dialogs","text":"Forms embedded in dialogs often do not contain the HTML <form> -element and instead rely on JavaScript click- and key-handlers to emulate a <form> -like submit behavior. This has spawned a great amount of nearly identical implementations that all aim to handle the form submit through the Enter -key, still leaving some dialogs behind. WoltLab Suite 3.1 offers automatic form submit that is enabled through a set of specific conditions and data attributes: There must be a submit button that matches the selector .formSubmit > input[type=\"submit\"], .formSubmit > button[data-type=\"submit\"] . The dialog object provided to UiDialog.open() implements the method _dialogSubmit() . Input fields require the attribute data-dialog-submit-on-enter=\"true\" to be set, the type must be one of number , password , search , tel , text or url . Clicking on the submit button or pressing the Enter -key in any watched input field will start the submit process. This is done automatically and does not require a manual interaction in your code, therefore you should not bind any click listeners on the submit button yourself. Any input field with the required attribute set will be validated to contain a non-empty string after processing the value with String.prototype.trim() . An empty field will abort the submit process and display a visible error message next to the offending field.","title":"Simplified Form Submit in Dialogs"},{"location":"migration/wsc30/javascript/#helper-function-for-inline-error-messages","text":"Displaying inline error messages on-the-fly required quite a few DOM operations that were quite simple but also super repetitive and thus error-prone when incorrectly copied over. The global helper function elInnerError() was added to provide a simple and consistent behavior of inline error messages. You can display an error message by invoking elInnerError(elementRef, \"Your Error Message\") , it will insert a new <small class=\"innerError\"> and sets the given message. If there is already an inner error present, then the message will be replaced instead. Hiding messages is done by setting the 2nd parameter to false or an empty string: elInnerError(elementRef, false) elInnerError(elementRef, '') The special values null and undefined are supported too, but their usage is discouraged, because they make it harder to understand the intention by reading the code: elInnerError(elementRef, null) elInnerError(elementRef)","title":"Helper Function for Inline Error Messages"},{"location":"migration/wsc30/javascript/#example-code_1","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 require ([ 'Language' ], function ( Language )) { var input = elBySel ( 'input[type=\"text\"]' ); if ( input . value . trim () === '' ) { // displays a new inline error or replaces the message if there is one already elInnerError ( input , Language . get ( 'wcf.global.form.error.empty' )); } else { // removes the inline error if it exists elInnerError ( input , false ); } // the above condition is equivalent to this: elInnerError ( input , ( input . value . trim () === '' ? Language . get ( 'wcf.global.form.error.empty' ) : false )); }","title":"Example Code"},{"location":"migration/wsc30/package/","text":"Migrating from WSC 3.0 - Package Components # Cronjob Scheduler uses Server Timezone # The execution time of cronjobs was previously calculated based on the coordinated universal time (UTC). This was changed in WoltLab Suite 3.1 to use the server timezone or, to be precise, the default timezone set in the administration control panel. Exclude Pages from becoming a Landing Page # Some pages do not qualify as landing page, because they're designed around specific expectations that aren't matched in all cases. Examples include the user control panel and its sub-pages that cannot be accessed by guests and will therefore break the landing page for those. While it is somewhat to be expected from control panel pages, there are enough pages that fall under the same restrictions, but aren't easily recognized as such by an administrator. You can exclude these pages by adding <excludeFromLandingPage>1</excludeFromLandingPage> (case-sensitive) to the relevant pages in your page.xml . Example Code # 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/tornado/page.xsd\" > <import> <page identifier= \"com.example.foo.Bar\" > <!-- ... --> <excludeFromLandingPage> 1 </excludeFromLandingPage> <!-- ... --> </page> </import> </data> New Package Installation Plugin for Media Providers # Please refer to the documentation of the mediaProvider.xml to learn more. Limited Forward-Compatibility for Plugins # Please refer to the documentation of the <compatibility> tag in the package.xml .","title":"Package Components"},{"location":"migration/wsc30/package/#migrating-from-wsc-30-package-components","text":"","title":"Migrating from WSC 3.0 - Package Components"},{"location":"migration/wsc30/package/#cronjob-scheduler-uses-server-timezone","text":"The execution time of cronjobs was previously calculated based on the coordinated universal time (UTC). This was changed in WoltLab Suite 3.1 to use the server timezone or, to be precise, the default timezone set in the administration control panel.","title":"Cronjob Scheduler uses Server Timezone"},{"location":"migration/wsc30/package/#exclude-pages-from-becoming-a-landing-page","text":"Some pages do not qualify as landing page, because they're designed around specific expectations that aren't matched in all cases. Examples include the user control panel and its sub-pages that cannot be accessed by guests and will therefore break the landing page for those. While it is somewhat to be expected from control panel pages, there are enough pages that fall under the same restrictions, but aren't easily recognized as such by an administrator. You can exclude these pages by adding <excludeFromLandingPage>1</excludeFromLandingPage> (case-sensitive) to the relevant pages in your page.xml .","title":"Exclude Pages from becoming a Landing Page"},{"location":"migration/wsc30/package/#example-code","text":"1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/tornado/page.xsd\" > <import> <page identifier= \"com.example.foo.Bar\" > <!-- ... --> <excludeFromLandingPage> 1 </excludeFromLandingPage> <!-- ... --> </page> </import> </data>","title":"Example Code"},{"location":"migration/wsc30/package/#new-package-installation-plugin-for-media-providers","text":"Please refer to the documentation of the mediaProvider.xml to learn more.","title":"New Package Installation Plugin for Media Providers"},{"location":"migration/wsc30/package/#limited-forward-compatibility-for-plugins","text":"Please refer to the documentation of the <compatibility> tag in the package.xml .","title":"Limited Forward-Compatibility for Plugins"},{"location":"migration/wsc30/php/","text":"Migrating from WSC 3.0 - PHP # Approval-System for Comments # Comments can now be set to require approval by a moderator before being published. This feature is disabled by default if you do not provide a permission in the manager class, enabling it requires a new permission that has to be provided in a special property of your manage implementation. files/lib/system/comment/manager/ExampleCommentManager.class.php 1 2 3 4 <? php class ExampleCommentManager extends AbstractCommentManager { protected $permissionAddWithoutModeration = 'foo.bar.example.canAddCommentWithoutModeration' ; } Raw HTML in User Activity Events # User activity events were previously encapsulated inside <div class=\"htmlContent\">\u2026</div> , with impacts on native elements such as lists. You can now disable the class usage by defining your event as raw HTML: files/lib/system/user/activity/event/ExampleUserActivityEvent.class.php 1 2 3 4 5 <? php class ExampleUserActivityEvent { // enables raw HTML for output, defaults to `false` protected $isRawHtml = true ; } Permission to View Likes of an Object # Being able to view the like summary of an object was restricted to users that were able to like the object itself. This creates situations where the object type in general is likable, but the particular object cannot be liked by the current users, while also denying them to view the like summary (but it gets partly exposed through the footer note/summary!). Implement the interface \\wcf\\data\\like\\IRestrictedLikeObjectTypeProvider in your object provider to add support for this new permission check. files/lib/data/example/LikeableExampleProvider.class.php 1 2 3 4 5 6 7 <? php class LikeableExampleProvider extends ExampleProvider implements IRestrictedLikeObjectTypeProvider , IViewableLikeProvider { public function canViewLikes ( ILikeObject $object ) { // perform your permission checks here return true ; } } Developer Tools: Sync Feature # The synchronization feature of the newly added developer tools works by invoking a package installation plugin (PIP) outside of a regular installation, while simulating the basic environment that is already exposed by the API. However, not all PIPs qualify for this kind of execution, especially because it could be invoked multiple times in a row by the user. This is solved by requiring a special marking for PIPs that have no side-effects (= idempotent) when invoked any amount of times with the same arguments. There's another feature that allows all matching PIPs to be executed in a row using a single button click. In order to solve dependencies on other PIPs, any implementing PIP must also provide the method getSyncDependencies() that returns the dependent PIPs in an arbitrary order. files/lib/data/package/plugin/ExamplePackageInstallationPlugin.class.php 1 2 3 4 5 6 7 <? php class ExamplePackageInstallationPlugin extends AbstractXMLPackageInstallationPlugin implements IIdempotentPackageInstallationPlugin { public static function getSyncDependencies () { // provide a list of dependent PIPs in arbitrary order return []; } } Media Providers # Media providers were added through regular SQL queries in earlier versions, but this is neither convenient, nor did it offer a reliable method to update an existing provider. WoltLab Suite 3.1 adds a new mediaProvider -PIP that also offers a className parameter to off-load the result evaluation and HTML generation. Example Implementation # mediaProvider.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/tornado/mediaProvider.xsd\" > <import> <provider name= \"example\" > <title> Example Provider </title> <regex> https?://example.com/watch?v=(?P <ID> [a-zA-Z0-9]) </regex> <className> wcf\\system\\bbcode\\media\\provider\\ExampleBBCodeMediaProvider </className> </provider> </import> </data> PHP Callback # The full match is provided for $url , while any capture groups from the regular expression are assigned to $matches . 1 2 3 4 5 6 <? php class ExampleBBCodeMediaProvider implements IBBCodeMediaProvider { public function parse ( $url , array $matches = []) { return \"final HTML output\" ; } } Re-Evaluate HTML Messages # You need to manually set the disallowed bbcodes in order to avoid unintentional bbcode evaluation. Please see this commit for a reference implementation inside worker processes. The HtmlInputProcessor only supported two ways to handle an existing HTML message: Load the string through process() and run it through the validation and sanitation process, both of them are rather expensive operations and do not qualify for rebuild data workers. Detect embedded content using processEmbeddedContent() which bypasses most tasks that are carried out by process() which aren't required, but does not allow a modification of the message. The newly added method reprocess($message, $objectType, $objectID) solves this short-coming by offering a full bbcode and text re-evaluation while bypassing any input filters, assuming that the input HTML was already filtered previously. Example Usage # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php // rebuild data workers tend to contain code similar to this: foreach ( $this -> objectList as $message ) { // ... if ( ! $message -> enableHtml ) { // ... } else { // OLD: $this -> getHtmlInputProcessor () -> processEmbeddedContent ( $message -> message , 'com.example.foo.message' , $message -> messageID ); // REPLACE WITH: $this -> getHtmlInputProcessor () -> reprocess ( $message -> message , 'com.example.foo.message' , $message -> messageID ); $data [ 'message' ] = $this -> getHtmlInputProcessor () -> getHtml (); } // ... }","title":"PHP API"},{"location":"migration/wsc30/php/#migrating-from-wsc-30-php","text":"","title":"Migrating from WSC 3.0 - PHP"},{"location":"migration/wsc30/php/#approval-system-for-comments","text":"Comments can now be set to require approval by a moderator before being published. This feature is disabled by default if you do not provide a permission in the manager class, enabling it requires a new permission that has to be provided in a special property of your manage implementation. files/lib/system/comment/manager/ExampleCommentManager.class.php 1 2 3 4 <? php class ExampleCommentManager extends AbstractCommentManager { protected $permissionAddWithoutModeration = 'foo.bar.example.canAddCommentWithoutModeration' ; }","title":"Approval-System for Comments"},{"location":"migration/wsc30/php/#raw-html-in-user-activity-events","text":"User activity events were previously encapsulated inside <div class=\"htmlContent\">\u2026</div> , with impacts on native elements such as lists. You can now disable the class usage by defining your event as raw HTML: files/lib/system/user/activity/event/ExampleUserActivityEvent.class.php 1 2 3 4 5 <? php class ExampleUserActivityEvent { // enables raw HTML for output, defaults to `false` protected $isRawHtml = true ; }","title":"Raw HTML in User Activity Events"},{"location":"migration/wsc30/php/#permission-to-view-likes-of-an-object","text":"Being able to view the like summary of an object was restricted to users that were able to like the object itself. This creates situations where the object type in general is likable, but the particular object cannot be liked by the current users, while also denying them to view the like summary (but it gets partly exposed through the footer note/summary!). Implement the interface \\wcf\\data\\like\\IRestrictedLikeObjectTypeProvider in your object provider to add support for this new permission check. files/lib/data/example/LikeableExampleProvider.class.php 1 2 3 4 5 6 7 <? php class LikeableExampleProvider extends ExampleProvider implements IRestrictedLikeObjectTypeProvider , IViewableLikeProvider { public function canViewLikes ( ILikeObject $object ) { // perform your permission checks here return true ; } }","title":"Permission to View Likes of an Object"},{"location":"migration/wsc30/php/#developer-tools-sync-feature","text":"The synchronization feature of the newly added developer tools works by invoking a package installation plugin (PIP) outside of a regular installation, while simulating the basic environment that is already exposed by the API. However, not all PIPs qualify for this kind of execution, especially because it could be invoked multiple times in a row by the user. This is solved by requiring a special marking for PIPs that have no side-effects (= idempotent) when invoked any amount of times with the same arguments. There's another feature that allows all matching PIPs to be executed in a row using a single button click. In order to solve dependencies on other PIPs, any implementing PIP must also provide the method getSyncDependencies() that returns the dependent PIPs in an arbitrary order. files/lib/data/package/plugin/ExamplePackageInstallationPlugin.class.php 1 2 3 4 5 6 7 <? php class ExamplePackageInstallationPlugin extends AbstractXMLPackageInstallationPlugin implements IIdempotentPackageInstallationPlugin { public static function getSyncDependencies () { // provide a list of dependent PIPs in arbitrary order return []; } }","title":"Developer Tools: Sync Feature"},{"location":"migration/wsc30/php/#media-providers","text":"Media providers were added through regular SQL queries in earlier versions, but this is neither convenient, nor did it offer a reliable method to update an existing provider. WoltLab Suite 3.1 adds a new mediaProvider -PIP that also offers a className parameter to off-load the result evaluation and HTML generation.","title":"Media Providers"},{"location":"migration/wsc30/php/#example-implementation","text":"mediaProvider.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/tornado/mediaProvider.xsd\" > <import> <provider name= \"example\" > <title> Example Provider </title> <regex> https?://example.com/watch?v=(?P <ID> [a-zA-Z0-9]) </regex> <className> wcf\\system\\bbcode\\media\\provider\\ExampleBBCodeMediaProvider </className> </provider> </import> </data>","title":"Example Implementation"},{"location":"migration/wsc30/php/#php-callback","text":"The full match is provided for $url , while any capture groups from the regular expression are assigned to $matches . 1 2 3 4 5 6 <? php class ExampleBBCodeMediaProvider implements IBBCodeMediaProvider { public function parse ( $url , array $matches = []) { return \"final HTML output\" ; } }","title":"PHP Callback"},{"location":"migration/wsc30/php/#re-evaluate-html-messages","text":"You need to manually set the disallowed bbcodes in order to avoid unintentional bbcode evaluation. Please see this commit for a reference implementation inside worker processes. The HtmlInputProcessor only supported two ways to handle an existing HTML message: Load the string through process() and run it through the validation and sanitation process, both of them are rather expensive operations and do not qualify for rebuild data workers. Detect embedded content using processEmbeddedContent() which bypasses most tasks that are carried out by process() which aren't required, but does not allow a modification of the message. The newly added method reprocess($message, $objectType, $objectID) solves this short-coming by offering a full bbcode and text re-evaluation while bypassing any input filters, assuming that the input HTML was already filtered previously.","title":"Re-Evaluate HTML Messages"},{"location":"migration/wsc30/php/#example-usage","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php // rebuild data workers tend to contain code similar to this: foreach ( $this -> objectList as $message ) { // ... if ( ! $message -> enableHtml ) { // ... } else { // OLD: $this -> getHtmlInputProcessor () -> processEmbeddedContent ( $message -> message , 'com.example.foo.message' , $message -> messageID ); // REPLACE WITH: $this -> getHtmlInputProcessor () -> reprocess ( $message -> message , 'com.example.foo.message' , $message -> messageID ); $data [ 'message' ] = $this -> getHtmlInputProcessor () -> getHtml (); } // ... }","title":"Example Usage"},{"location":"migration/wsc30/templates/","text":"Migrating from WSC 3.0 - Templates # Comment-System Overhaul # Unfortunately, there has been a breaking change related to the creation of comments. You need to apply the changes below before being able to create new comments. Adding Comments # Existing implementations need to include a new template right before including the generic commentList template. 1 2 3 4 < ul id = \"exampleCommentList\" class = \"commentList containerList\" data- ... > {include file='commentListAddComment' wysiwygSelector='exampleCommentListAddComment'} {include file='commentList'} </ ul > Redesigned ACP User List # Custom interaction buttons were previously added through the template event rowButtons and were merely a link-like element with an icon inside. This is still valid and supported for backwards-compatibility, but it is recommend to adapt to the new drop-down-style options using the new template event dropdownItems . 1 2 3 4 5 <!-- button for usage with the `rowButtons` event --> < span class = \"icon icon16 fa-list jsTooltip\" title = \"Button Title\" ></ span > <!-- new drop-down item for the `dropdownItems` event --> < li >< a href = \"#\" class = \"jsMyButton\" > Button Title </ a ></ li > Sidebar Toogle-Buttons on Mobile Device # You cannot override the button label for sidebars containing navigation menus. The page sidebars are automatically collapsed and presented as one or, when both sidebar are present, two condensed buttons. They use generic sidebar-related labels when open or closed, with the exception of embedded menus which will change the button label to read \"Show/Hide Navigation\". You can provide a custom label before including the sidebars by assigning the new labels to a few special variables: 1 2 3 4 {assign var='__sidebarLeftShow' value='Show Left Sidebar'} {assign var='__sidebarLeftHide' value='Hide Left Sidebar'} {assign var='__sidebarRightShow' value='Show Right Sidebar'} {assign var='__sidebarRightHide' value='Hide Right Sidebar'}","title":"Templates"},{"location":"migration/wsc30/templates/#migrating-from-wsc-30-templates","text":"","title":"Migrating from WSC 3.0 - Templates"},{"location":"migration/wsc30/templates/#comment-system-overhaul","text":"Unfortunately, there has been a breaking change related to the creation of comments. You need to apply the changes below before being able to create new comments.","title":"Comment-System Overhaul"},{"location":"migration/wsc30/templates/#adding-comments","text":"Existing implementations need to include a new template right before including the generic commentList template. 1 2 3 4 < ul id = \"exampleCommentList\" class = \"commentList containerList\" data- ... > {include file='commentListAddComment' wysiwygSelector='exampleCommentListAddComment'} {include file='commentList'} </ ul >","title":"Adding Comments"},{"location":"migration/wsc30/templates/#redesigned-acp-user-list","text":"Custom interaction buttons were previously added through the template event rowButtons and were merely a link-like element with an icon inside. This is still valid and supported for backwards-compatibility, but it is recommend to adapt to the new drop-down-style options using the new template event dropdownItems . 1 2 3 4 5 <!-- button for usage with the `rowButtons` event --> < span class = \"icon icon16 fa-list jsTooltip\" title = \"Button Title\" ></ span > <!-- new drop-down item for the `dropdownItems` event --> < li >< a href = \"#\" class = \"jsMyButton\" > Button Title </ a ></ li >","title":"Redesigned ACP User List"},{"location":"migration/wsc30/templates/#sidebar-toogle-buttons-on-mobile-device","text":"You cannot override the button label for sidebars containing navigation menus. The page sidebars are automatically collapsed and presented as one or, when both sidebar are present, two condensed buttons. They use generic sidebar-related labels when open or closed, with the exception of embedded menus which will change the button label to read \"Show/Hide Navigation\". You can provide a custom label before including the sidebars by assigning the new labels to a few special variables: 1 2 3 4 {assign var='__sidebarLeftShow' value='Show Left Sidebar'} {assign var='__sidebarLeftHide' value='Hide Left Sidebar'} {assign var='__sidebarRightShow' value='Show Right Sidebar'} {assign var='__sidebarRightHide' value='Hide Right Sidebar'}","title":"Sidebar Toogle-Buttons on Mobile Device"},{"location":"migration/wsc31/form-builder/","text":"Migrating from WSC 3.1 - Form Builder # Example: Two Text Form Fields # As the first example, the pre-WoltLab Suite Core 5.2 versions of the forms to add and edit persons from the first part of the tutorial series will be updated to the new form builder API. This form is the perfect first examples as it is very simple with only two text fields whose only restriction is that they have to be filled out and that their values may not be longer than 255 characters each. As a reminder, here are the two relevant PHP files and the relevant template file: files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractForm ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\WCF ; use wcf\\util\\StringUtil ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * first name of the person * @var string */ public $firstName = '' ; /** * last name of the person * @var string */ public $lastName = '' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'action' => 'add' , 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]); } /** * @inheritDoc */ public function readFormParameters () { parent :: readFormParameters (); if ( isset ( $_POST [ 'firstName' ])) $this -> firstName = StringUtil :: trim ( $_POST [ 'firstName' ]); if ( isset ( $_POST [ 'lastName' ])) $this -> lastName = StringUtil :: trim ( $_POST [ 'lastName' ]); } /** * @inheritDoc */ public function save () { parent :: save (); $this -> objectAction = new PersonAction ([], 'create' , [ 'data' => array_merge ( $this -> additionalFields , [ 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]) ]); $this -> objectAction -> executeAction (); $this -> saved (); // reset values $this -> firstName = '' ; $this -> lastName = '' ; // show success message WCF :: getTPL () -> assign ( 'success' , true ); } /** * @inheritDoc */ public function validate () { parent :: validate (); // validate first name if ( empty ( $this -> firstName )) { throw new UserInputException ( 'firstName' ); } if ( mb_strlen ( $this -> firstName ) > 255 ) { throw new UserInputException ( 'firstName' , 'tooLong' ); } // validate last name if ( empty ( $this -> lastName )) { throw new UserInputException ( 'lastName' ); } if ( mb_strlen ( $this -> lastName ) > 255 ) { throw new UserInputException ( 'lastName' , 'tooLong' ); } } } files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractForm ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\WCF ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * edited person object * @var Person */ public $person = null ; /** * id of the edited person * @var integer */ public $personID = 0 ; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'action' => 'edit' , 'person' => $this -> person ]); } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( empty ( $_POST )) { $this -> firstName = $this -> person -> firstName ; $this -> lastName = $this -> person -> lastName ; } } /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) $this -> personID = intval ( $_REQUEST [ 'id' ]); $this -> person = new Person ( $this -> personID ); if ( ! $this -> person -> personID ) { throw new IllegalLinkException (); } } /** * @inheritDoc */ public function save () { AbstractForm :: save (); $this -> objectAction = new PersonAction ([ $this -> person ], 'update' , [ 'data' => array_merge ( $this -> additionalFields , [ 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]) ]); $this -> objectAction -> executeAction (); $this -> saved (); // show success message WCF :: getTPL () -> assign ( 'success' , true ); } } acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { include file = 'formError' } { if $success | isset } <p class=\"success\"> { lang } wcf.global.success. { $action }{ /lang } </p> { /if } <form method=\"post\" action=\" { if $action == 'add' }{ link controller = 'PersonAdd' }{ /link }{ else }{ link controller = 'PersonEdit' object = $person }{ /link }{ /if } \"> <div class=\"section\"> <dl { if $errorField == 'firstName' } class=\"formError\" { /if } > <dt><label for=\"firstName\"> { lang } wcf.person.firstName { /lang } </label></dt> <dd> <input type=\"text\" id=\"firstName\" name=\"firstName\" value=\" { $firstName } \" required autofocus maxlength=\"255\" class=\"long\"> { if $errorField == 'firstName' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } wcf.acp.person.firstName.error. { $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> <dl { if $errorField == 'lastName' } class=\"formError\" { /if } > <dt><label for=\"lastName\"> { lang } wcf.person.lastName { /lang } </label></dt> <dd> <input type=\"text\" id=\"lastName\" name=\"lastName\" value=\" { $lastName } \" required maxlength=\"255\" class=\"long\"> { if $errorField == 'lastName' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } wcf.acp.person.lastName.error. { $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> { event name = 'dataFields' } </div> { event name = 'sections' } <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> { @ SECURITY_TOKEN_INPUT_TAG } </div> </form> { include file = 'footer' } Updating the template is easy as the complete form is replace by a single line of code: acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { @ $form -> getHtml () } { include file = 'footer' } PersonEditForm also becomes much simpler: only the edited Person object must be read: files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\system\\exception\\IllegalLinkException ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> formObject = new Person ( intval ( $_REQUEST [ 'id' ])); if ( ! $this -> formObject -> personID ) { throw new IllegalLinkException (); } } } } Most of the work is done in PersonAddForm : files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\TextFormField ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractFormBuilderForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * @inheritDoc */ public $formAction = 'create' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectActionClass = PersonAction :: class ; /** * @inheritDoc */ protected function createForm () { parent :: createForm (); $dataContainer = FormContainer :: create ( 'data' ) -> appendChildren ([ TextFormField :: create ( 'firstName' ) -> label ( 'wcf.person.firstName' ) -> required () -> maximumLength ( 255 ), TextFormField :: create ( 'lastName' ) -> label ( 'wcf.person.lastName' ) -> required () -> maximumLength ( 255 ) ]); $this -> form -> appendChild ( $dataContainer ); } } But, as you can see, the number of lines almost decreased by half. All changes are due to extending AbstractFormBuilderForm : $formAction is added and set to create as the form is used to create a new person. In the edit form, $formAction has not to be set explicitly as it is done automatically if a $formObject is set. $objectActionClass is set to PersonAction::class and is the class name of the used AbstractForm::$objectAction object to create and update the Person object. AbstractFormBuilderForm::createForm() is overridden and the form contents are added: a form container representing the div.section element from the old version and the two form fields with the same ids and labels as before. The contents of the old validate() method is put into two method calls: required() to ensure that the form is filled out and maximumLength(255) to ensure that the names are not longer than 255 characters.","title":"Migrating from WSC 3.1 - Form Builder"},{"location":"migration/wsc31/form-builder/#migrating-from-wsc-31-form-builder","text":"","title":"Migrating from WSC 3.1 - Form Builder"},{"location":"migration/wsc31/form-builder/#example-two-text-form-fields","text":"As the first example, the pre-WoltLab Suite Core 5.2 versions of the forms to add and edit persons from the first part of the tutorial series will be updated to the new form builder API. This form is the perfect first examples as it is very simple with only two text fields whose only restriction is that they have to be filled out and that their values may not be longer than 255 characters each. As a reminder, here are the two relevant PHP files and the relevant template file: files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractForm ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\WCF ; use wcf\\util\\StringUtil ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * first name of the person * @var string */ public $firstName = '' ; /** * last name of the person * @var string */ public $lastName = '' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'action' => 'add' , 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]); } /** * @inheritDoc */ public function readFormParameters () { parent :: readFormParameters (); if ( isset ( $_POST [ 'firstName' ])) $this -> firstName = StringUtil :: trim ( $_POST [ 'firstName' ]); if ( isset ( $_POST [ 'lastName' ])) $this -> lastName = StringUtil :: trim ( $_POST [ 'lastName' ]); } /** * @inheritDoc */ public function save () { parent :: save (); $this -> objectAction = new PersonAction ([], 'create' , [ 'data' => array_merge ( $this -> additionalFields , [ 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]) ]); $this -> objectAction -> executeAction (); $this -> saved (); // reset values $this -> firstName = '' ; $this -> lastName = '' ; // show success message WCF :: getTPL () -> assign ( 'success' , true ); } /** * @inheritDoc */ public function validate () { parent :: validate (); // validate first name if ( empty ( $this -> firstName )) { throw new UserInputException ( 'firstName' ); } if ( mb_strlen ( $this -> firstName ) > 255 ) { throw new UserInputException ( 'firstName' , 'tooLong' ); } // validate last name if ( empty ( $this -> lastName )) { throw new UserInputException ( 'lastName' ); } if ( mb_strlen ( $this -> lastName ) > 255 ) { throw new UserInputException ( 'lastName' , 'tooLong' ); } } } files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractForm ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\WCF ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * edited person object * @var Person */ public $person = null ; /** * id of the edited person * @var integer */ public $personID = 0 ; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'action' => 'edit' , 'person' => $this -> person ]); } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( empty ( $_POST )) { $this -> firstName = $this -> person -> firstName ; $this -> lastName = $this -> person -> lastName ; } } /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) $this -> personID = intval ( $_REQUEST [ 'id' ]); $this -> person = new Person ( $this -> personID ); if ( ! $this -> person -> personID ) { throw new IllegalLinkException (); } } /** * @inheritDoc */ public function save () { AbstractForm :: save (); $this -> objectAction = new PersonAction ([ $this -> person ], 'update' , [ 'data' => array_merge ( $this -> additionalFields , [ 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]) ]); $this -> objectAction -> executeAction (); $this -> saved (); // show success message WCF :: getTPL () -> assign ( 'success' , true ); } } acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { include file = 'formError' } { if $success | isset } <p class=\"success\"> { lang } wcf.global.success. { $action }{ /lang } </p> { /if } <form method=\"post\" action=\" { if $action == 'add' }{ link controller = 'PersonAdd' }{ /link }{ else }{ link controller = 'PersonEdit' object = $person }{ /link }{ /if } \"> <div class=\"section\"> <dl { if $errorField == 'firstName' } class=\"formError\" { /if } > <dt><label for=\"firstName\"> { lang } wcf.person.firstName { /lang } </label></dt> <dd> <input type=\"text\" id=\"firstName\" name=\"firstName\" value=\" { $firstName } \" required autofocus maxlength=\"255\" class=\"long\"> { if $errorField == 'firstName' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } wcf.acp.person.firstName.error. { $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> <dl { if $errorField == 'lastName' } class=\"formError\" { /if } > <dt><label for=\"lastName\"> { lang } wcf.person.lastName { /lang } </label></dt> <dd> <input type=\"text\" id=\"lastName\" name=\"lastName\" value=\" { $lastName } \" required maxlength=\"255\" class=\"long\"> { if $errorField == 'lastName' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } wcf.acp.person.lastName.error. { $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> { event name = 'dataFields' } </div> { event name = 'sections' } <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> { @ SECURITY_TOKEN_INPUT_TAG } </div> </form> { include file = 'footer' } Updating the template is easy as the complete form is replace by a single line of code: acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { @ $form -> getHtml () } { include file = 'footer' } PersonEditForm also becomes much simpler: only the edited Person object must be read: files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\system\\exception\\IllegalLinkException ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> formObject = new Person ( intval ( $_REQUEST [ 'id' ])); if ( ! $this -> formObject -> personID ) { throw new IllegalLinkException (); } } } } Most of the work is done in PersonAddForm : files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\TextFormField ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractFormBuilderForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * @inheritDoc */ public $formAction = 'create' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectActionClass = PersonAction :: class ; /** * @inheritDoc */ protected function createForm () { parent :: createForm (); $dataContainer = FormContainer :: create ( 'data' ) -> appendChildren ([ TextFormField :: create ( 'firstName' ) -> label ( 'wcf.person.firstName' ) -> required () -> maximumLength ( 255 ), TextFormField :: create ( 'lastName' ) -> label ( 'wcf.person.lastName' ) -> required () -> maximumLength ( 255 ) ]); $this -> form -> appendChild ( $dataContainer ); } } But, as you can see, the number of lines almost decreased by half. All changes are due to extending AbstractFormBuilderForm : $formAction is added and set to create as the form is used to create a new person. In the edit form, $formAction has not to be set explicitly as it is done automatically if a $formObject is set. $objectActionClass is set to PersonAction::class and is the class name of the used AbstractForm::$objectAction object to create and update the Person object. AbstractFormBuilderForm::createForm() is overridden and the form contents are added: a form container representing the div.section element from the old version and the two form fields with the same ids and labels as before. The contents of the old validate() method is put into two method calls: required() to ensure that the form is filled out and maximumLength(255) to ensure that the names are not longer than 255 characters.","title":"Example: Two Text Form Fields"},{"location":"migration/wsc31/like/","text":"Migrating from WSC 3.1 - Like System # Introduction # With version 5.2 of WoltLab Suite Core the like system was completely replaced by the new reactions system. This makes it necessary to make some adjustments to existing code so that your plugin integrates completely into the new system. However, we have kept these adjustments as small as possible so that it is possible to use the reaction system with slight restrictions even without adjustments. Limitations if no adjustments are made to the existing code # If no adjustments are made to the existing code, the following functions are not available: * Notifications about reactions/likes * Recent Activity Events for reactions/likes Migration # Notifications # Mark notification as compatible # Since there are no more likes with the new version, it makes no sense to send notifications about it. Instead of notifications about likes, notifications about reactions are now sent. However, this only changes the notification text and not the notification itself. To update the notification, we first add the interface \\wcf\\data\\reaction\\object\\IReactionObject to the \\wcf\\data\\like\\object\\ILikeObject object (e.g. in WoltLab Suite Forum we added the interface to the class \\wbb\\data\\post\\LikeablePost ). After that the object is marked as \"compatible with WoltLab Suite Core 5.2\" and notifications about reactions are sent again. Language Variables # Next, to display all reactions for the current notification in the notification text, we include the trait \\wcf\\system\\user\\notification\\event\\TReactionUserNotificationEvent in the user notification event class (typically named like *LikeUserNotificationEvent ). These trait provides a new function that reads out and groups the reactions. The result of this function must now only be passed to the language variable. The name \"reactions\" is typically used as the variable name for the language variable. As a final step, we only need to change the language variables themselves. To ensure a consistent usability, the same formulations should be used as in the WoltLab Suite Core. English # {prefix}.like.title 1 Reaction to a {objectName} {prefix}.like.title.stacked 1 {#$count} users reacted to your {objectName} {prefix}.like.message 1 {@$author->getAnchorTag()} reacted to your {objectName} ({implode from=$reactions key=reactionID item=count}{@$__wcf->getReactionHandler()->getReactionTypeByID($reactionID)->renderIcon()}\u00d7{#$count}{/implode}). {prefix}.like.message.stacked 1 {if $count < 4}{@$authors[0]->getAnchorTag()}{if $count == 2} and {else}, {/if}{@$authors[1]->getAnchorTag()}{if $count == 3} and {@$authors[2]->getAnchorTag()}{/if}{else}{@$authors[0]->getAnchorTag()} and {#$others} others{/if} reacted to your {objectName} ({implode from=$reactions key=reactionID item=count}{@$__wcf->getReactionHandler()->getReactionTypeByID($reactionID)->renderIcon()}\u00d7{#$count}{/implode}). wcf.user.notification.{objectTypeName}.like.notification.like 1 Notify me when someone reacted to my {objectName} German # {prefix}.like.title 1 Reaktion auf einen {objectName} {prefix}.like.title.stacked 1 {#$count} Benutzern haben auf {if LANGUAGE_USE_INFORMAL_VARIANT}dein(en){else}Ihr(en){/if} {objectName} reagiert {prefix}.like.message 1 {@$author->getAnchorTag()} hat auf {if LANGUAGE_USE_INFORMAL_VARIANT}dein(en){else}Ihr(en){/if} {objectName} reagiert ({implode from=$reactions key=reactionID item=count}{@$__wcf->getReactionHandler()->getReactionTypeByID($reactionID)->renderIcon()}\u00d7{#$count}{/implode}). {prefix}.like.message.stacked 1 {if $count < 4}{@$authors[0]->getAnchorTag()}{if $count == 2} und {else}, {/if}{@$authors[1]->getAnchorTag()}{if $count == 3} und {@$authors[2]->getAnchorTag()}{/if}{else}{@$authors[0]->getAnchorTag()} und {#$others} weitere{/if} haben auf {if LANGUAGE_USE_INFORMAL_VARIANT}dein(en){else}Ihr(en){/if} {objectName} reagiert ({implode from=$reactions key=reactionID item=count}{@$__wcf->getReactionHandler()->getReactionTypeByID($reactionID)->renderIcon()}\u00d7{#$count}{/implode}). wcf.user.notification.{object_type_name}.like.notification.like 1 Jemandem hat auf {if LANGUAGE_USE_INFORMAL_VARIANT}dein(en){else}Ihr(en){/if} {objectName} reagiert Recent Activity # To adjust entries in the Recent Activity, only three small steps are necessary. First we pass the concrete reaction to the language variable, so that we can use the reaction object there. To do this, we add the following variable to the text of the \\wcf\\system\\user\\activity\\event\\IUserActivityEvent object: $event->reactionType . Typically we name the variable reactionType . In the second step, we mark the event as compatible. Therefore we set the parameter supportsReactions in the objectType.xml to 1 . So for example the entry looks like this: objectType.xml 1 2 3 4 5 6 <type> <name> com.woltlab.example.likeableObject.recentActivityEvent </name> <definitionname> com.woltlab.wcf.user.recentActivityEvent </definitionname> <classname> wcf\\system\\user\\activity\\event\\LikeableObjectUserActivityEvent </classname> <supportsReactions> 1 </supportsReactions> </type> Finally we modify our language variable. To ensure a consistent usability, the same formulations should be used as in the WoltLab Suite Core. English # wcf.user.recentActivity.{object_type_name}.recentActivityEvent 1 Reaction ({objectName}) Your language variable for the recent activity text 1 Reacted with <span title=\"{$reactionType->getTitle()}\" class=\"jsTooltip\">{@$reactionType->renderIcon()}</span> to the {objectName}. German # wcf.user.recentActivity.{objectTypeName}.recentActivityEvent 1 Reaktion ({objectName}) Your language variable for the recent activity text 1 Hat mit <span title=\"{$reactionType->getTitle()}\" class=\"jsTooltip\">{@$reactionType->renderIcon()}</span> auf {objectName} reagiert. Comments # If comments send notifications, they must also be updated. The language variables are changed in the same way as described in the section Notifications / Language . After that comment must be marked as compatible. Therefore we set the parameter supportsReactions in the objectType.xml to 1 . So for example the entry looks like this: objectType.xml 1 2 3 4 5 6 7 <type> <name> com.woltlab.wcf.objectComment.response.like.notification </name> <definitionname> com.woltlab.wcf.notification.objectType </definitionname> <classname> wcf\\system\\user\\notification\\object\\type\\LikeUserNotificationObjectType </classname> <category> com.woltlab.example </category> <supportsReactions> 1 </supportsReactions> </type> Forward Compatibility # So that these changes also work in older versions of WoltLab Suite Core, the used classes and traits were backported with WoltLab Suite Core 3.0.22 and WoltLab Suite Core 3.1.10.","title":"Migrating from WSC 3.1 - Like System"},{"location":"migration/wsc31/like/#migrating-from-wsc-31-like-system","text":"","title":"Migrating from WSC 3.1 - Like System"},{"location":"migration/wsc31/like/#introduction","text":"With version 5.2 of WoltLab Suite Core the like system was completely replaced by the new reactions system. This makes it necessary to make some adjustments to existing code so that your plugin integrates completely into the new system. However, we have kept these adjustments as small as possible so that it is possible to use the reaction system with slight restrictions even without adjustments.","title":"Introduction"},{"location":"migration/wsc31/like/#limitations-if-no-adjustments-are-made-to-the-existing-code","text":"If no adjustments are made to the existing code, the following functions are not available: * Notifications about reactions/likes * Recent Activity Events for reactions/likes","title":"Limitations if no adjustments are made to the existing code"},{"location":"migration/wsc31/like/#migration","text":"","title":"Migration"},{"location":"migration/wsc31/like/#notifications","text":"","title":"Notifications"},{"location":"migration/wsc31/like/#mark-notification-as-compatible","text":"Since there are no more likes with the new version, it makes no sense to send notifications about it. Instead of notifications about likes, notifications about reactions are now sent. However, this only changes the notification text and not the notification itself. To update the notification, we first add the interface \\wcf\\data\\reaction\\object\\IReactionObject to the \\wcf\\data\\like\\object\\ILikeObject object (e.g. in WoltLab Suite Forum we added the interface to the class \\wbb\\data\\post\\LikeablePost ). After that the object is marked as \"compatible with WoltLab Suite Core 5.2\" and notifications about reactions are sent again.","title":"Mark notification as compatible"},{"location":"migration/wsc31/like/#language-variables","text":"Next, to display all reactions for the current notification in the notification text, we include the trait \\wcf\\system\\user\\notification\\event\\TReactionUserNotificationEvent in the user notification event class (typically named like *LikeUserNotificationEvent ). These trait provides a new function that reads out and groups the reactions. The result of this function must now only be passed to the language variable. The name \"reactions\" is typically used as the variable name for the language variable. As a final step, we only need to change the language variables themselves. To ensure a consistent usability, the same formulations should be used as in the WoltLab Suite Core.","title":"Language Variables"},{"location":"migration/wsc31/like/#recent-activity","text":"To adjust entries in the Recent Activity, only three small steps are necessary. First we pass the concrete reaction to the language variable, so that we can use the reaction object there. To do this, we add the following variable to the text of the \\wcf\\system\\user\\activity\\event\\IUserActivityEvent object: $event->reactionType . Typically we name the variable reactionType . In the second step, we mark the event as compatible. Therefore we set the parameter supportsReactions in the objectType.xml to 1 . So for example the entry looks like this: objectType.xml 1 2 3 4 5 6 <type> <name> com.woltlab.example.likeableObject.recentActivityEvent </name> <definitionname> com.woltlab.wcf.user.recentActivityEvent </definitionname> <classname> wcf\\system\\user\\activity\\event\\LikeableObjectUserActivityEvent </classname> <supportsReactions> 1 </supportsReactions> </type> Finally we modify our language variable. To ensure a consistent usability, the same formulations should be used as in the WoltLab Suite Core.","title":"Recent Activity"},{"location":"migration/wsc31/like/#english_1","text":"wcf.user.recentActivity.{object_type_name}.recentActivityEvent 1 Reaction ({objectName}) Your language variable for the recent activity text 1 Reacted with <span title=\"{$reactionType->getTitle()}\" class=\"jsTooltip\">{@$reactionType->renderIcon()}</span> to the {objectName}.","title":"English"},{"location":"migration/wsc31/like/#german_1","text":"wcf.user.recentActivity.{objectTypeName}.recentActivityEvent 1 Reaktion ({objectName}) Your language variable for the recent activity text 1 Hat mit <span title=\"{$reactionType->getTitle()}\" class=\"jsTooltip\">{@$reactionType->renderIcon()}</span> auf {objectName} reagiert.","title":"German"},{"location":"migration/wsc31/like/#comments","text":"If comments send notifications, they must also be updated. The language variables are changed in the same way as described in the section Notifications / Language . After that comment must be marked as compatible. Therefore we set the parameter supportsReactions in the objectType.xml to 1 . So for example the entry looks like this: objectType.xml 1 2 3 4 5 6 7 <type> <name> com.woltlab.wcf.objectComment.response.like.notification </name> <definitionname> com.woltlab.wcf.notification.objectType </definitionname> <classname> wcf\\system\\user\\notification\\object\\type\\LikeUserNotificationObjectType </classname> <category> com.woltlab.example </category> <supportsReactions> 1 </supportsReactions> </type>","title":"Comments"},{"location":"migration/wsc31/like/#forward-compatibility","text":"So that these changes also work in older versions of WoltLab Suite Core, the used classes and traits were backported with WoltLab Suite Core 3.0.22 and WoltLab Suite Core 3.1.10.","title":"Forward Compatibility"},{"location":"migration/wsc31/php/","text":"Migrating from WSC 3.1 - PHP # Form Builder # WoltLab Suite Core 5.2 introduces a new, simpler and quicker way of creating forms: form builder . You can find examples of how to migrate existing forms to form builder here . In the near future, to ensure backwards compatibility within WoltLab packages, we will only use form builder for new forms or for major rewrites of existing forms that would break backwards compatibility anyway. Like System # WoltLab Suite Core 5.2 replaced the like system with the reaction system. You can find the migration guide here . User Content Providers # User content providers help the WoltLab Suite to find user generated content. They provide a class with which you can find content from a particular user and delete objects. PHP Class # First, we create the PHP class that provides our interface to provide the data. The class must implement interface wcf\\system\\user\\content\\provider\\IUserContentProvider in any case. Mostly we process data which is based on wcf\\data\\DatabaseObject . In this case, the WoltLab Suite provides an abstract class wcf\\system\\user\\content\\provider\\AbstractDatabaseUserContentProvider that can be used to automatically generates the standardized classes to generate the list and deletes objects via the DatabaseObjectAction. For example, if we would create a content provider for comments, the class would look like this: files/lib/system/user/content/provider/CommentUserContentProvider.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\user\\content\\provider ; use wcf\\data\\comment\\Comment ; /** * User content provider for comments. * * @author Joshua Ruesweg * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\User\\Content\\Provider * @since 5.2 */ class CommentUserContentProvider extends AbstractDatabaseUserContentProvider { /** * @inheritdoc */ public static function getDatabaseObjectClass () { return Comment :: class ; } } Object Type # Now the appropriate object type must be created for the class. This object type must be from the definition com.woltlab.wcf.content.userContentProvider and include the previous created class as FQN in the parameter classname . Also the following parameters can be used in the object type: nicevalue # Optional The nice value is used to determine the order in which the remove content worker are execute the provider. Content provider with lower nice values are executed first. hidden # Optional Specifies whether or not this content provider can be actively selected in the Content Remove Worker. If it cannot be selected, it will not be executed automatically! requiredobjecttype # Optional The specified list of comma-separated object types are automatically removed during content removal when this object type is being removed. Attention : The order of removal is undefined by default, specify a nicevalue if the order is important. PHP Database API # WoltLab Suite 5.2 introduces a new way to update the database scheme: database PHP API .","title":"PHP API"},{"location":"migration/wsc31/php/#migrating-from-wsc-31-php","text":"","title":"Migrating from WSC 3.1 - PHP"},{"location":"migration/wsc31/php/#form-builder","text":"WoltLab Suite Core 5.2 introduces a new, simpler and quicker way of creating forms: form builder . You can find examples of how to migrate existing forms to form builder here . In the near future, to ensure backwards compatibility within WoltLab packages, we will only use form builder for new forms or for major rewrites of existing forms that would break backwards compatibility anyway.","title":"Form Builder"},{"location":"migration/wsc31/php/#like-system","text":"WoltLab Suite Core 5.2 replaced the like system with the reaction system. You can find the migration guide here .","title":"Like System"},{"location":"migration/wsc31/php/#user-content-providers","text":"User content providers help the WoltLab Suite to find user generated content. They provide a class with which you can find content from a particular user and delete objects.","title":"User Content Providers"},{"location":"migration/wsc31/php/#php-class","text":"First, we create the PHP class that provides our interface to provide the data. The class must implement interface wcf\\system\\user\\content\\provider\\IUserContentProvider in any case. Mostly we process data which is based on wcf\\data\\DatabaseObject . In this case, the WoltLab Suite provides an abstract class wcf\\system\\user\\content\\provider\\AbstractDatabaseUserContentProvider that can be used to automatically generates the standardized classes to generate the list and deletes objects via the DatabaseObjectAction. For example, if we would create a content provider for comments, the class would look like this: files/lib/system/user/content/provider/CommentUserContentProvider.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\user\\content\\provider ; use wcf\\data\\comment\\Comment ; /** * User content provider for comments. * * @author Joshua Ruesweg * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\User\\Content\\Provider * @since 5.2 */ class CommentUserContentProvider extends AbstractDatabaseUserContentProvider { /** * @inheritdoc */ public static function getDatabaseObjectClass () { return Comment :: class ; } }","title":"PHP Class"},{"location":"migration/wsc31/php/#object-type","text":"Now the appropriate object type must be created for the class. This object type must be from the definition com.woltlab.wcf.content.userContentProvider and include the previous created class as FQN in the parameter classname . Also the following parameters can be used in the object type:","title":"Object Type"},{"location":"migration/wsc31/php/#nicevalue","text":"Optional The nice value is used to determine the order in which the remove content worker are execute the provider. Content provider with lower nice values are executed first.","title":"nicevalue"},{"location":"migration/wsc31/php/#hidden","text":"Optional Specifies whether or not this content provider can be actively selected in the Content Remove Worker. If it cannot be selected, it will not be executed automatically!","title":"hidden"},{"location":"migration/wsc31/php/#requiredobjecttype","text":"Optional The specified list of comma-separated object types are automatically removed during content removal when this object type is being removed. Attention : The order of removal is undefined by default, specify a nicevalue if the order is important.","title":"requiredobjecttype"},{"location":"migration/wsc31/php/#php-database-api","text":"WoltLab Suite 5.2 introduces a new way to update the database scheme: database PHP API .","title":"PHP Database API"},{"location":"migration/wsc52/libraries/","text":"Migrating from WSC 5.2 - Third Party Libraries # SCSS Compiler # WoltLab Suite Core 5.3 upgrades the bundled SCSS compiler from leafo/scssphp 0.7.x to scssphp/scssphp 1.1.x. With the updated composer package name the SCSS compiler also received updated namespaces. WoltLab Suite Core adds a compatibility layer that maps the old namespace to the new namespace. The classes themselves appear to be drop-in compatible. Exceptions cannot be mapped using this compatibility layer, any catch blocks catching a specific Exception within the Leafo namespace will need to be adjusted. More details can be found in the Pull Request WoltLab/WCF#3415 . Guzzle # WoltLab Suite Core 5.3 ships with a bundled version of Guzzle 6 . Going forward using Guzzle is the recommended way to perform HTTP requests. The \\wcf\\util\\HTTPRequest class should no longer be used and transparently uses Guzzle under the hood. Use \\wcf\\system\\io\\HttpFactory to retrieve a correctly configured GuzzleHttp\\ClientInterface . Please note that it is recommended to explicitely specify a sink when making requests, due to a PHP / Guzzle bug. Have a look at the implementation in WoltLab/WCF for an example.","title":"Third Party Libraries"},{"location":"migration/wsc52/libraries/#migrating-from-wsc-52-third-party-libraries","text":"","title":"Migrating from WSC 5.2 - Third Party Libraries"},{"location":"migration/wsc52/libraries/#scss-compiler","text":"WoltLab Suite Core 5.3 upgrades the bundled SCSS compiler from leafo/scssphp 0.7.x to scssphp/scssphp 1.1.x. With the updated composer package name the SCSS compiler also received updated namespaces. WoltLab Suite Core adds a compatibility layer that maps the old namespace to the new namespace. The classes themselves appear to be drop-in compatible. Exceptions cannot be mapped using this compatibility layer, any catch blocks catching a specific Exception within the Leafo namespace will need to be adjusted. More details can be found in the Pull Request WoltLab/WCF#3415 .","title":"SCSS Compiler"},{"location":"migration/wsc52/libraries/#guzzle","text":"WoltLab Suite Core 5.3 ships with a bundled version of Guzzle 6 . Going forward using Guzzle is the recommended way to perform HTTP requests. The \\wcf\\util\\HTTPRequest class should no longer be used and transparently uses Guzzle under the hood. Use \\wcf\\system\\io\\HttpFactory to retrieve a correctly configured GuzzleHttp\\ClientInterface . Please note that it is recommended to explicitely specify a sink when making requests, due to a PHP / Guzzle bug. Have a look at the implementation in WoltLab/WCF for an example.","title":"Guzzle"},{"location":"migration/wsc52/php/","text":"Migrating from WSC 5.2 - PHP # Comments # The ICommentManager::isContentAuthor(Comment|CommentResponse): bool method was added. A default implementation that always returns false is available when inheriting from AbstractCommentManager . It is strongly recommended to implement isContentAuthor within your custom comment manager. An example implementation can be found in ArticleCommentManager . Event Listeners # The AbstractEventListener class was added. AbstractEventListener contains an implementation of execute() that will dispatch the event handling to dedicated methods based on the $eventName and, in case of the event object being an AbstractDatabaseObjectAction , the action name. Find the details of the dispatch behavior within the class comment of AbstractEventListener . Email Activation # Starting with WoltLab Suite 5.3 the user activation status is independent of the email activation status. A user can be activated even though their email address has not been confirmed, preventing emails being sent to these users. Going forward the new User::isEmailConfirmed() method should be used to check whether sending automated emails to this user is acceptable. If you need to check the user's activation status you should use the new method User::pendingActivation() instead of relying on activationCode . To check, which type of activation is missing, you can use the new methods User::requiresEmailActivation() and User::requiresAdminActivation() . *AddForm # WoltLab Suite 5.3 provides a new framework to allow the administrator to easily edit newly created objects by adding an edit link to the success message. To support this edit link two small changes are required within your *AddForm . Update the template. Replace: 1 2 3 4 5 { include file = 'formError' } { if $success | isset } <p class=\"success\"> { lang } wcf.global.success. { $action }{ /lang } </p> { /if } With: 1 { include file = 'formNotice' } Expose objectEditLink to the template. Example ( $object being the newly created object): 1 2 3 4 WCF :: getTPL () -> assign ([ 'success' => true , 'objectEditLink' => LinkHandler :: getInstance () -> getControllerLink ( ObjectEditForm :: class , [ 'id' => $object -> objectID ]), ]); User Generated Links # It is recommended by search engines to mark up links within user generated content using the rel=\"ugc\" attribute to indicate that they might be less trustworthy or spammy. WoltLab Suite 5.3 will automatically sets that attribute on external links during message output processing. Set the new HtmlOutputProcessor::$enableUgc property to false if the type of message is not user-generated content, but restricted to a set of trustworthy users. An example of such a type of message would be official news articles. If you manually generate links based off user input you need to specify the attribute yourself. The $isUgc attribute was added to StringUtil::getAnchorTag(string, string, bool, bool): string , allowing you to easily generate a correct anchor tag. If you need to specify additional HTML attributes for the anchor tag you can use the new StringUtil::getAnchorTagAttributes(string, bool): string method to generate the anchor attributes that are dependent on the target URL. Specifically the attributes returned are the class=\"externalURL\" attribute, the rel=\"\u2026\" attribute and the target=\"\u2026\" attribute. Within the template the {anchorAttributes} template plugin is newly available. Resource Management When Scaling Images # It was discovered that the code holds references to scaled image resources for an unnecessarily long time, taking up memory. This becomes especially apparent when multiple images are scaled within a loop, reusing the same variable name for consecutive images. Unless the destination variable is explicitely cleared before processing the next image up to two images will be stored in memory concurrently. This possibly causes the request to exceed the memory limit or ImageMagick's internal resource limits, even if sufficient resources would have been available to scale the current image. Starting with WoltLab Suite 5.3 it is recommended to clear image handles as early as possible. The usual pattern of creating a thumbnail for an existing image would then look like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php foreach ([ 200 , 500 ] as $size ) { $adapter = ImageHandler :: getInstance () -> getAdapter (); $adapter -> loadFile ( $src ); $thumbnail = $adapter -> createThumbnail ( $size , $size , true ); $adapter -> writeImage ( $thumbnail , $destination ); // New: Clear thumbnail as soon as possible to free up the memory. $thumbnail = null ; } Refer to WoltLab/WCF#3505 for additional details. Toggle for Accelerated Mobile Pages (AMP) # Controllers delivering AMP versions of pages have to check for the new option MODULE_AMP and the templates of the non-AMP versions have to also check if the option is enabled before outputting the <link rel=\"amphtml\" /> element.","title":"PHP API"},{"location":"migration/wsc52/php/#migrating-from-wsc-52-php","text":"","title":"Migrating from WSC 5.2 - PHP"},{"location":"migration/wsc52/php/#comments","text":"The ICommentManager::isContentAuthor(Comment|CommentResponse): bool method was added. A default implementation that always returns false is available when inheriting from AbstractCommentManager . It is strongly recommended to implement isContentAuthor within your custom comment manager. An example implementation can be found in ArticleCommentManager .","title":"Comments"},{"location":"migration/wsc52/php/#event-listeners","text":"The AbstractEventListener class was added. AbstractEventListener contains an implementation of execute() that will dispatch the event handling to dedicated methods based on the $eventName and, in case of the event object being an AbstractDatabaseObjectAction , the action name. Find the details of the dispatch behavior within the class comment of AbstractEventListener .","title":"Event Listeners"},{"location":"migration/wsc52/php/#email-activation","text":"Starting with WoltLab Suite 5.3 the user activation status is independent of the email activation status. A user can be activated even though their email address has not been confirmed, preventing emails being sent to these users. Going forward the new User::isEmailConfirmed() method should be used to check whether sending automated emails to this user is acceptable. If you need to check the user's activation status you should use the new method User::pendingActivation() instead of relying on activationCode . To check, which type of activation is missing, you can use the new methods User::requiresEmailActivation() and User::requiresAdminActivation() .","title":"Email Activation"},{"location":"migration/wsc52/php/#addform","text":"WoltLab Suite 5.3 provides a new framework to allow the administrator to easily edit newly created objects by adding an edit link to the success message. To support this edit link two small changes are required within your *AddForm . Update the template. Replace: 1 2 3 4 5 { include file = 'formError' } { if $success | isset } <p class=\"success\"> { lang } wcf.global.success. { $action }{ /lang } </p> { /if } With: 1 { include file = 'formNotice' } Expose objectEditLink to the template. Example ( $object being the newly created object): 1 2 3 4 WCF :: getTPL () -> assign ([ 'success' => true , 'objectEditLink' => LinkHandler :: getInstance () -> getControllerLink ( ObjectEditForm :: class , [ 'id' => $object -> objectID ]), ]);","title":"*AddForm"},{"location":"migration/wsc52/php/#user-generated-links","text":"It is recommended by search engines to mark up links within user generated content using the rel=\"ugc\" attribute to indicate that they might be less trustworthy or spammy. WoltLab Suite 5.3 will automatically sets that attribute on external links during message output processing. Set the new HtmlOutputProcessor::$enableUgc property to false if the type of message is not user-generated content, but restricted to a set of trustworthy users. An example of such a type of message would be official news articles. If you manually generate links based off user input you need to specify the attribute yourself. The $isUgc attribute was added to StringUtil::getAnchorTag(string, string, bool, bool): string , allowing you to easily generate a correct anchor tag. If you need to specify additional HTML attributes for the anchor tag you can use the new StringUtil::getAnchorTagAttributes(string, bool): string method to generate the anchor attributes that are dependent on the target URL. Specifically the attributes returned are the class=\"externalURL\" attribute, the rel=\"\u2026\" attribute and the target=\"\u2026\" attribute. Within the template the {anchorAttributes} template plugin is newly available.","title":"User Generated Links"},{"location":"migration/wsc52/php/#resource-management-when-scaling-images","text":"It was discovered that the code holds references to scaled image resources for an unnecessarily long time, taking up memory. This becomes especially apparent when multiple images are scaled within a loop, reusing the same variable name for consecutive images. Unless the destination variable is explicitely cleared before processing the next image up to two images will be stored in memory concurrently. This possibly causes the request to exceed the memory limit or ImageMagick's internal resource limits, even if sufficient resources would have been available to scale the current image. Starting with WoltLab Suite 5.3 it is recommended to clear image handles as early as possible. The usual pattern of creating a thumbnail for an existing image would then look like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php foreach ([ 200 , 500 ] as $size ) { $adapter = ImageHandler :: getInstance () -> getAdapter (); $adapter -> loadFile ( $src ); $thumbnail = $adapter -> createThumbnail ( $size , $size , true ); $adapter -> writeImage ( $thumbnail , $destination ); // New: Clear thumbnail as soon as possible to free up the memory. $thumbnail = null ; } Refer to WoltLab/WCF#3505 for additional details.","title":"Resource Management When Scaling Images"},{"location":"migration/wsc52/php/#toggle-for-accelerated-mobile-pages-amp","text":"Controllers delivering AMP versions of pages have to check for the new option MODULE_AMP and the templates of the non-AMP versions have to also check if the option is enabled before outputting the <link rel=\"amphtml\" /> element.","title":"Toggle for Accelerated Mobile Pages (AMP)"},{"location":"migration/wsc52/templates/","text":"Migrating from WSC 5.2 - Templates and Languages # {jslang} # Starting with WoltLab Suite 5.3 the {jslang} template plugin is available. {jslang} works like {lang} , with the difference that the result is automatically encoded for use within a single quoted JavaScript string. Before: 1 2 3 4 5 6 7 8 9 <script> require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{lang}app.foo.bar{/lang}' , } ); // \u2026 } ); </script> After: 1 2 3 4 5 6 7 8 9 <script> require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' , } ); // \u2026 } ); </script> Template Plugins # The {anchor} , {plural} , and {user} template plugins have been added. Notification Language Items # In addition to using the new template plugins mentioned above, language items for notifications have been further simplified. As the whole notification is clickable now, all a elements have been replaced with strong elements in notification messages. The template code to output reactions has been simplified by introducing helper methods: 1 2 3 4 5 6 7 8 9 { * old * } { implode from = $reactions key = reactionID item = count }{ @ $__wcf -> getReactionHandler ()-> getReactionTypeByID ( $reactionID )-> renderIcon () } \u00d7 { # $count }{ /implode } { * new * } { @ $__wcf -> getReactionHandler ()-> renderInlineList ( $reactions ) } { * old * } <span title=\" { $like -> getReactionType ()-> getTitle () } \" class=\"jsTooltip\"> { @ $like -> getReactionType ()-> renderIcon () } </span> { * new * } { @ $like -> render () } Similarly, showing labels is now also easier due to the new render method: 1 2 3 4 { * old * } <span class=\"label badge { if $label -> getClassNames () } { $label -> getClassNames () }{ /if } \"> { $label -> getTitle () } </span> { * new * } { @ $label -> render () } The commonly used template code 1 { if $count < 4 }{ @ $authors [ 0 ]-> getAnchorTag () }{ if $count != 1 }{ if $count == 2 && ! $guestTimesTriggered } and { else } , { /if }{ @ $authors [ 1 ]-> getAnchorTag () }{ if $count == 3 }{ if ! $guestTimesTriggered } and { else } , { /if } { @ $authors [ 2 ]-> getAnchorTag () }{ /if }{ /if }{ if $guestTimesTriggered } and { if $guestTimesTriggered == 1 } a guest { else } guests { /if }{ /if }{ else }{ @ $authors [ 0 ]-> getAnchorTag () }{ if $guestTimesTriggered } , { else } and { /if } { # $others } other users { if $guestTimesTriggered } and { if $guestTimesTriggered == 1 } a guest { else } guests { /if }{ /if }{ /if } in stacked notification messages can be replaced with a new language item: 1 { @ 'wcf.user.notification.stacked.authorList' | language } Popovers # Popovers provide additional information of the linked object when a user hovers over a link. We unified the approach for such links: The relevant DBO class implements wcf\\data\\IPopoverObject . The relevant DBO action class implements wcf\\data\\IPopoverAction and the getPopover() method returns an array with popover content. Globally available, WoltLabSuite/Core/Controller/Popover is initialized with the relevant data. Links are created with the anchor template plugin with an additional class attribute whose value is the return value of IPopoverObject::getPopoverLinkClass() . Example: files/lib/data/foo/Foo.class.php 1 2 3 4 5 class Foo extends DatabaseObject implements IPopoverObject { public function getPopoverLinkClass () { return 'fooLink' ; } } files/lib/data/foo/FooAction.class.php 1 2 3 4 5 6 7 8 9 10 11 class FooAction extends AbstractDatabaseObjectAction implements IPopoverAction { public function validateGetPopover () { // \u2026 } public function getPopover () { return [ 'template' => '\u2026' , ]; } } 1 2 3 4 5 6 7 require ([ 'WoltLabSuite/Core/Controller/Popover' ], function ( ControllerPopover ) { ControllerPopover . init ({ className : 'fooLink' , dboAction : 'wcf\\\\data\\\\foo\\\\FooAction' , identifier : 'com.woltlab.wcf.foo' }); }); 1 { anchor object = $foo class = 'fooLink' }","title":"Templates and Languages"},{"location":"migration/wsc52/templates/#migrating-from-wsc-52-templates-and-languages","text":"","title":"Migrating from WSC 5.2 - Templates and Languages"},{"location":"migration/wsc52/templates/#jslang","text":"Starting with WoltLab Suite 5.3 the {jslang} template plugin is available. {jslang} works like {lang} , with the difference that the result is automatically encoded for use within a single quoted JavaScript string. Before: 1 2 3 4 5 6 7 8 9 <script> require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{lang}app.foo.bar{/lang}' , } ); // \u2026 } ); </script> After: 1 2 3 4 5 6 7 8 9 <script> require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' , } ); // \u2026 } ); </script>","title":"{jslang}"},{"location":"migration/wsc52/templates/#template-plugins","text":"The {anchor} , {plural} , and {user} template plugins have been added.","title":"Template Plugins"},{"location":"migration/wsc52/templates/#notification-language-items","text":"In addition to using the new template plugins mentioned above, language items for notifications have been further simplified. As the whole notification is clickable now, all a elements have been replaced with strong elements in notification messages. The template code to output reactions has been simplified by introducing helper methods: 1 2 3 4 5 6 7 8 9 { * old * } { implode from = $reactions key = reactionID item = count }{ @ $__wcf -> getReactionHandler ()-> getReactionTypeByID ( $reactionID )-> renderIcon () } \u00d7 { # $count }{ /implode } { * new * } { @ $__wcf -> getReactionHandler ()-> renderInlineList ( $reactions ) } { * old * } <span title=\" { $like -> getReactionType ()-> getTitle () } \" class=\"jsTooltip\"> { @ $like -> getReactionType ()-> renderIcon () } </span> { * new * } { @ $like -> render () } Similarly, showing labels is now also easier due to the new render method: 1 2 3 4 { * old * } <span class=\"label badge { if $label -> getClassNames () } { $label -> getClassNames () }{ /if } \"> { $label -> getTitle () } </span> { * new * } { @ $label -> render () } The commonly used template code 1 { if $count < 4 }{ @ $authors [ 0 ]-> getAnchorTag () }{ if $count != 1 }{ if $count == 2 && ! $guestTimesTriggered } and { else } , { /if }{ @ $authors [ 1 ]-> getAnchorTag () }{ if $count == 3 }{ if ! $guestTimesTriggered } and { else } , { /if } { @ $authors [ 2 ]-> getAnchorTag () }{ /if }{ /if }{ if $guestTimesTriggered } and { if $guestTimesTriggered == 1 } a guest { else } guests { /if }{ /if }{ else }{ @ $authors [ 0 ]-> getAnchorTag () }{ if $guestTimesTriggered } , { else } and { /if } { # $others } other users { if $guestTimesTriggered } and { if $guestTimesTriggered == 1 } a guest { else } guests { /if }{ /if }{ /if } in stacked notification messages can be replaced with a new language item: 1 { @ 'wcf.user.notification.stacked.authorList' | language }","title":"Notification Language Items"},{"location":"migration/wsc52/templates/#popovers","text":"Popovers provide additional information of the linked object when a user hovers over a link. We unified the approach for such links: The relevant DBO class implements wcf\\data\\IPopoverObject . The relevant DBO action class implements wcf\\data\\IPopoverAction and the getPopover() method returns an array with popover content. Globally available, WoltLabSuite/Core/Controller/Popover is initialized with the relevant data. Links are created with the anchor template plugin with an additional class attribute whose value is the return value of IPopoverObject::getPopoverLinkClass() . Example: files/lib/data/foo/Foo.class.php 1 2 3 4 5 class Foo extends DatabaseObject implements IPopoverObject { public function getPopoverLinkClass () { return 'fooLink' ; } } files/lib/data/foo/FooAction.class.php 1 2 3 4 5 6 7 8 9 10 11 class FooAction extends AbstractDatabaseObjectAction implements IPopoverAction { public function validateGetPopover () { // \u2026 } public function getPopover () { return [ 'template' => '\u2026' , ]; } } 1 2 3 4 5 6 7 require ([ 'WoltLabSuite/Core/Controller/Popover' ], function ( ControllerPopover ) { ControllerPopover . init ({ className : 'fooLink' , dboAction : 'wcf\\\\data\\\\foo\\\\FooAction' , identifier : 'com.woltlab.wcf.foo' }); }); 1 { anchor object = $foo class = 'fooLink' }","title":"Popovers"},{"location":"migration/wsc53/javascript/","text":"Migrating from WSC 5.3 - TypeScript and JavaScript # TypeScript # WoltLab Suite 5.4 introduces TypeScript support. Learn about consuming WoltLab Suite\u2019s types in the TypeScript section of the JavaScript API documentation. The JavaScript API documentation will be updated to properly take into account the changes that came with the new TypeScript support in the future. Existing AMD based modules have been migrated to TypeScript, but will expose the existing and known API. It is recommended that you migrate your custom packages to make use of TypeScript. It will make consuming newly written modules that properly leverage TypeScript\u2019s features much more pleasant and will also ease using existing modules due to proper autocompletion and type checking. Replacements for Deprecated Components # The helper functions in wcf.globalHelper.js should not be used anymore but replaced by their native counterpart: Function Native Replacement elCreate(tag) document.createElement(tag) elRemove(el) el.remove() elShow(el) DomUtil.show(el) elHide(el) DomUtil.hide(el) elIsHidden(el) DomUtil.isHidden(el) elToggle(el) DomUtil.toggle(el) elAttr(el, \"attr\") el.attr or el.getAttribute(\"attr\") elData(el, \"data\") el.dataset.data elDataBool(element, \"data\") Core.stringToBool(el.dataset.data) elById(id) document.getElementById(id) elBySel(sel) document.querySelector(sel) elBySel(sel, el) el.querySelector(sel) elBySelAll(sel) document.querySelectorAll(sel) elBySelAll(sel, el) el.querySelectorAll(sel) elBySelAll(sel, el, callback) el.querySelectorAll(sel).forEach((el) => callback(el)); elClosest(el, sel) el.closest(sel) elByClass(class) document.getElementsByClassName(class) elByClass(class, el) el.getElementsByClassName(class) elByTag(tag) document.getElementsByTagName(tag) elByTag(tag, el) el.getElementsByTagName(tag) elInnerError(el, message, isHtml) DomUtil.innerError(el, message, isHtml) Additionally, the following modules should also be replaced by their native counterpart: Module Native Replacement WoltLabSuite/Core/Dictionary Map WoltLabSuite/Core/List Set WoltLabSuite/Core/ObjectMap WeakMap For event listeners on click events, WCF_CLICK_EVENT is deprecated and should no longer be used. Instead, use click directly: 1 2 3 4 5 // before element . addEventListener ( WCF_CLICK_EVENT , this . _click . bind ( this )); // after element . addEventListener ( 'click' , ( ev ) => this . _click ( ev )); WCF.Action.Delete and WCF.Action.Toggle # WCF.Action.Delete and WCF.Action.Toggle were used for buttons to delete or enable/disable objects via JavaScript. In each template, WCF.Action.Delete or WCF.Action.Toggle instances had to be manually created for each object listing. With version 5.4 of WoltLab Suite, we have added a CSS selector-based global TypeScript module that only requires specific CSS classes to be added to the HTML structure for these buttons to work. Additionally, we have added a new {objectAction} template plugin, which generates these buttons reducing the amount of boilerplate template code. The required base HTML structure is as follows: A .jsObjectActionContainer element with a data-object-action-class-name attribute that contains the name of PHP class that executes the actions. .jsObjectActionObject elements within .jsObjectActionContainer that represent the objects for which actions can be executed. Each .jsObjectActionObject element must have a data-object-id attribute with the id of the object. .jsObjectAction elements within .jsObjectActionObject for each action with a data-object-action attribute with the name of the action. These elements can be generated with the {objectAction} template plugin for the delete and toggle action. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <table class=\"table jsObjectActionContainer\" { * * } data-object-action-class-name=\"wcf\\data\\foo\\FooAction\"> <thead> <tr> { * \u2026 * } </tr> </thead> <tbody> { foreach from = $objects item = foo } <tr class=\"jsObjectActionObject\" data-object-id=\" { @ $foo -> getObjectID () } \"> <td class=\"columnIcon\"> { objectAction action = \"toggle\" isDisabled = $foo -> isDisabled } { objectAction action = \"delete\" objectTitle = $foo -> getTitle () } { * \u2026 * } </td> { * \u2026 * } </tr> { /foreach } </tbody> </table> Please refer to the documentation in ObjectActionFunctionTemplatePlugin for details and examples on how to use this template plugin. The relevant TypeScript module registering the event listeners on the object action buttons is Ui/Object/Action . When an action button is clicked, an AJAX request is sent using the PHP class name and action name. After the successful execution of the action, the page is either reloaded if the action button has a data-object-action-success=\"reload\" attribute or an event using the EventHandler module is fired using WoltLabSuite/Core/Ui/Object/Action as the identifier and the object action name. Ui/Object/Action/Delete and Ui/Object/Action/Toggle listen to these events and update the user interface depending on the execute action by removing the object or updating the toggle button, respectively. Converting from WCF.Action.* to the new approach requires minimal changes per template, as shown in the relevant pull request #4080 . WCF.Table.EmptyTableHandler # When all objects in a table or list are deleted via their delete button or clipboard actions, an empty table or list can remain. Previously, WCF.Table.EmptyTableHandler had to be explicitly used in each template for these tables and lists to reload the page. As a TypeScript-based replacement for WCF.Table.EmptyTableHandler that is only initialized once globally, WoltLabSuite/Core/Ui/Empty was added. To use this new module, you only have to add the CSS class jsReloadPageWhenEmpty to the relevant HTML element. Once this HTML element no longer has child elements, the page is reloaded. To also cover scenarios in which there are fixed child elements that should not be considered when determining if there are no child elements, the data-reload-page-when-empty=\"ignore\" can be set for these elements. Examples: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <table class=\"table\"> <thead> <tr> { * \u2026 * } </tr> </thead> <tbody class=\"jsReloadPageWhenEmpty\"> { foreach from = $objects item = object } <tr> { * \u2026 * } </tr> { /foreach } </tbody> </table> 1 2 3 4 5 6 7 8 9 10 11 12 13 <div class=\"section tabularBox messageGroupList\"> <ol class=\"tabularList jsReloadPageWhenEmpty\"> <li class=\"tabularListRow tabularListRowHead\" data-reload-page-when-empty=\"ignore\"> { * \u2026 * } </li> { foreach from = $objects item = object } <li> { * \u2026 * } </li> { /foreach } </ol> </div>","title":"TypeScript and JavaScript"},{"location":"migration/wsc53/javascript/#migrating-from-wsc-53-typescript-and-javascript","text":"","title":"Migrating from WSC 5.3 - TypeScript and JavaScript"},{"location":"migration/wsc53/javascript/#typescript","text":"WoltLab Suite 5.4 introduces TypeScript support. Learn about consuming WoltLab Suite\u2019s types in the TypeScript section of the JavaScript API documentation. The JavaScript API documentation will be updated to properly take into account the changes that came with the new TypeScript support in the future. Existing AMD based modules have been migrated to TypeScript, but will expose the existing and known API. It is recommended that you migrate your custom packages to make use of TypeScript. It will make consuming newly written modules that properly leverage TypeScript\u2019s features much more pleasant and will also ease using existing modules due to proper autocompletion and type checking.","title":"TypeScript"},{"location":"migration/wsc53/javascript/#replacements-for-deprecated-components","text":"The helper functions in wcf.globalHelper.js should not be used anymore but replaced by their native counterpart: Function Native Replacement elCreate(tag) document.createElement(tag) elRemove(el) el.remove() elShow(el) DomUtil.show(el) elHide(el) DomUtil.hide(el) elIsHidden(el) DomUtil.isHidden(el) elToggle(el) DomUtil.toggle(el) elAttr(el, \"attr\") el.attr or el.getAttribute(\"attr\") elData(el, \"data\") el.dataset.data elDataBool(element, \"data\") Core.stringToBool(el.dataset.data) elById(id) document.getElementById(id) elBySel(sel) document.querySelector(sel) elBySel(sel, el) el.querySelector(sel) elBySelAll(sel) document.querySelectorAll(sel) elBySelAll(sel, el) el.querySelectorAll(sel) elBySelAll(sel, el, callback) el.querySelectorAll(sel).forEach((el) => callback(el)); elClosest(el, sel) el.closest(sel) elByClass(class) document.getElementsByClassName(class) elByClass(class, el) el.getElementsByClassName(class) elByTag(tag) document.getElementsByTagName(tag) elByTag(tag, el) el.getElementsByTagName(tag) elInnerError(el, message, isHtml) DomUtil.innerError(el, message, isHtml) Additionally, the following modules should also be replaced by their native counterpart: Module Native Replacement WoltLabSuite/Core/Dictionary Map WoltLabSuite/Core/List Set WoltLabSuite/Core/ObjectMap WeakMap For event listeners on click events, WCF_CLICK_EVENT is deprecated and should no longer be used. Instead, use click directly: 1 2 3 4 5 // before element . addEventListener ( WCF_CLICK_EVENT , this . _click . bind ( this )); // after element . addEventListener ( 'click' , ( ev ) => this . _click ( ev ));","title":"Replacements for Deprecated Components"},{"location":"migration/wsc53/javascript/#wcfactiondelete-and-wcfactiontoggle","text":"WCF.Action.Delete and WCF.Action.Toggle were used for buttons to delete or enable/disable objects via JavaScript. In each template, WCF.Action.Delete or WCF.Action.Toggle instances had to be manually created for each object listing. With version 5.4 of WoltLab Suite, we have added a CSS selector-based global TypeScript module that only requires specific CSS classes to be added to the HTML structure for these buttons to work. Additionally, we have added a new {objectAction} template plugin, which generates these buttons reducing the amount of boilerplate template code. The required base HTML structure is as follows: A .jsObjectActionContainer element with a data-object-action-class-name attribute that contains the name of PHP class that executes the actions. .jsObjectActionObject elements within .jsObjectActionContainer that represent the objects for which actions can be executed. Each .jsObjectActionObject element must have a data-object-id attribute with the id of the object. .jsObjectAction elements within .jsObjectActionObject for each action with a data-object-action attribute with the name of the action. These elements can be generated with the {objectAction} template plugin for the delete and toggle action. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <table class=\"table jsObjectActionContainer\" { * * } data-object-action-class-name=\"wcf\\data\\foo\\FooAction\"> <thead> <tr> { * \u2026 * } </tr> </thead> <tbody> { foreach from = $objects item = foo } <tr class=\"jsObjectActionObject\" data-object-id=\" { @ $foo -> getObjectID () } \"> <td class=\"columnIcon\"> { objectAction action = \"toggle\" isDisabled = $foo -> isDisabled } { objectAction action = \"delete\" objectTitle = $foo -> getTitle () } { * \u2026 * } </td> { * \u2026 * } </tr> { /foreach } </tbody> </table> Please refer to the documentation in ObjectActionFunctionTemplatePlugin for details and examples on how to use this template plugin. The relevant TypeScript module registering the event listeners on the object action buttons is Ui/Object/Action . When an action button is clicked, an AJAX request is sent using the PHP class name and action name. After the successful execution of the action, the page is either reloaded if the action button has a data-object-action-success=\"reload\" attribute or an event using the EventHandler module is fired using WoltLabSuite/Core/Ui/Object/Action as the identifier and the object action name. Ui/Object/Action/Delete and Ui/Object/Action/Toggle listen to these events and update the user interface depending on the execute action by removing the object or updating the toggle button, respectively. Converting from WCF.Action.* to the new approach requires minimal changes per template, as shown in the relevant pull request #4080 .","title":"WCF.Action.Delete and WCF.Action.Toggle"},{"location":"migration/wsc53/javascript/#wcftableemptytablehandler","text":"When all objects in a table or list are deleted via their delete button or clipboard actions, an empty table or list can remain. Previously, WCF.Table.EmptyTableHandler had to be explicitly used in each template for these tables and lists to reload the page. As a TypeScript-based replacement for WCF.Table.EmptyTableHandler that is only initialized once globally, WoltLabSuite/Core/Ui/Empty was added. To use this new module, you only have to add the CSS class jsReloadPageWhenEmpty to the relevant HTML element. Once this HTML element no longer has child elements, the page is reloaded. To also cover scenarios in which there are fixed child elements that should not be considered when determining if there are no child elements, the data-reload-page-when-empty=\"ignore\" can be set for these elements. Examples: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <table class=\"table\"> <thead> <tr> { * \u2026 * } </tr> </thead> <tbody class=\"jsReloadPageWhenEmpty\"> { foreach from = $objects item = object } <tr> { * \u2026 * } </tr> { /foreach } </tbody> </table> 1 2 3 4 5 6 7 8 9 10 11 12 13 <div class=\"section tabularBox messageGroupList\"> <ol class=\"tabularList jsReloadPageWhenEmpty\"> <li class=\"tabularListRow tabularListRowHead\" data-reload-page-when-empty=\"ignore\"> { * \u2026 * } </li> { foreach from = $objects item = object } <li> { * \u2026 * } </li> { /foreach } </ol> </div>","title":"WCF.Table.EmptyTableHandler"},{"location":"migration/wsc53/libraries/","text":"Migrating from WSC 5.3 - Third Party Libraries # Guzzle # The bundled Guzzle version was updated to Guzzle 7. No breaking changes are expected for simple uses. A detailed Guzzle migration guide can be found in the Guzzle documentation. The explicit sink that was recommended in the migration guide for WSC 5.2 can now be removed, as the Guzzle issue #2735 was fixed in Guzzle 7. Emogrifier / CSS Inliner # The Emogrifier library was updated from version 2.2 to 5.0. This update comes with a breaking change, as the Emogrifier class was removed. With the updated Emogrifier library, the CssInliner class must be used instead. No compatibility layer was added for the Emogrifier class, as the Emogrifier library's purpose was to be used within the email subsystem of WoltLab Suite. In case you use Emogrifier directly within your own code, you will need to adjust the usage. Refer to the Emogrifier CHANGELOG and WoltLab/WCF #3738 if you need help making the necessary adjustments. If you only use Emogrifier indirectly by sending HTML mail via the email subsystem then you might notice unexpected visual changes due to the improved CSS support. Double check your CSS declarations and particularly the specificity of your selectors in these cases. scssphp # scssphp was updated from version 1.1 to 1.4. If you interact with scssphp only by deploying .scss files, then you should not experience any breaking changes, except when the improved SCSS compatibility interprets your SCSS code differently. If you happen to directly use scssphp in your PHP code, you should be aware that scssphp deprecated the use of output formatters in favor of a simple output style enum. Refer to WoltLab/WCF #3851 and the scssphp releases for details. Constant Time Encoder # WoltLab Suite 5.4 ships the paragonie/constant_time_encoding library . It is recommended to use this library to perform encoding and decoding of secrets to prevent leaks via cache timing attacks. Refer to the library author\u2019s blog post for more background detail. For the common case of encoding the bytes taken from a CSPRNG in hexadecimal form, the required change would look like the following: Previously: 1 2 <? php $encoded = hex2bin ( random_bytes ( 16 )); Now: 1 2 3 4 5 6 7 8 <? php use ParagonIE\\ConstantTime\\Hex ; // For security reasons you should add the backslash // to ensure you refer to the `random_bytes` function // within the global namespace and not a function // defined in the current namespace. $encoded = Hex :: encode ( \\random_bytes ( 16 )); Please refer to the documentation and source code of the paragonie/constant_time_encoding library to learn how to use the library with different encodings (e.g. base64).","title":"Third Party Libraries"},{"location":"migration/wsc53/libraries/#migrating-from-wsc-53-third-party-libraries","text":"","title":"Migrating from WSC 5.3 - Third Party Libraries"},{"location":"migration/wsc53/libraries/#guzzle","text":"The bundled Guzzle version was updated to Guzzle 7. No breaking changes are expected for simple uses. A detailed Guzzle migration guide can be found in the Guzzle documentation. The explicit sink that was recommended in the migration guide for WSC 5.2 can now be removed, as the Guzzle issue #2735 was fixed in Guzzle 7.","title":"Guzzle"},{"location":"migration/wsc53/libraries/#emogrifier-css-inliner","text":"The Emogrifier library was updated from version 2.2 to 5.0. This update comes with a breaking change, as the Emogrifier class was removed. With the updated Emogrifier library, the CssInliner class must be used instead. No compatibility layer was added for the Emogrifier class, as the Emogrifier library's purpose was to be used within the email subsystem of WoltLab Suite. In case you use Emogrifier directly within your own code, you will need to adjust the usage. Refer to the Emogrifier CHANGELOG and WoltLab/WCF #3738 if you need help making the necessary adjustments. If you only use Emogrifier indirectly by sending HTML mail via the email subsystem then you might notice unexpected visual changes due to the improved CSS support. Double check your CSS declarations and particularly the specificity of your selectors in these cases.","title":"Emogrifier / CSS Inliner"},{"location":"migration/wsc53/libraries/#scssphp","text":"scssphp was updated from version 1.1 to 1.4. If you interact with scssphp only by deploying .scss files, then you should not experience any breaking changes, except when the improved SCSS compatibility interprets your SCSS code differently. If you happen to directly use scssphp in your PHP code, you should be aware that scssphp deprecated the use of output formatters in favor of a simple output style enum. Refer to WoltLab/WCF #3851 and the scssphp releases for details.","title":"scssphp"},{"location":"migration/wsc53/libraries/#constant-time-encoder","text":"WoltLab Suite 5.4 ships the paragonie/constant_time_encoding library . It is recommended to use this library to perform encoding and decoding of secrets to prevent leaks via cache timing attacks. Refer to the library author\u2019s blog post for more background detail. For the common case of encoding the bytes taken from a CSPRNG in hexadecimal form, the required change would look like the following: Previously: 1 2 <? php $encoded = hex2bin ( random_bytes ( 16 )); Now: 1 2 3 4 5 6 7 8 <? php use ParagonIE\\ConstantTime\\Hex ; // For security reasons you should add the backslash // to ensure you refer to the `random_bytes` function // within the global namespace and not a function // defined in the current namespace. $encoded = Hex :: encode ( \\random_bytes ( 16 )); Please refer to the documentation and source code of the paragonie/constant_time_encoding library to learn how to use the library with different encodings (e.g. base64).","title":"Constant Time Encoder"},{"location":"migration/wsc53/php/","text":"Migrating from WSC 5.3 - PHP # Minimum requirements # The minimum requirements have been increased to the following: PHP: 7.2.24 MySQL: 5.7.31 or 8.0.19 MariaDB: 10.1.44 Most notably PHP 7.2 contains usable support for scalar types by the addition of nullable types in PHP 7.1 and parameter type widening in PHP 7.2. It is recommended to make use of scalar types and other newly introduced features whereever possible. Please refer to the PHP documentation for details. Flood Control # To prevent users from creating massive amounts of contents in short periods of time, i.e., spam, existing systems already use flood control mechanisms to limit the amount of contents created within a certain period of time. With WoltLab Suite 5.4, we have added a general API that manages such rate limiting. Leveraging this API is easily done. Register an object type for the definition com.woltlab.wcf.floodControl : com.example.foo.myContent . Whenever the active user creates content of this type, call 1 FloodControl :: getInstance () -> registerContent ( 'com.example.foo.myContent' ); You should only call this method if the user creates the content themselves. If the content is automatically created by the system, for example when copying / duplicating existing content, no activity should be registered. To check the last time when the active user created content of the relevant type, use 1 FloodControl :: getInstance () -> getLastTime ( 'com.example.foo.myContent' ); If you want to limit the number of content items created within a certain period of time, for example within one day, use 1 2 3 4 5 $data = FloodControl :: getInstance () -> countContent ( 'com.example.foo.myContent' , new \\DateInterval ( 'P1D' )); // number of content items created within the last day $count = $data [ 'count' ]; // timestamp when the earliest content item was created within the last day $earliestTime = $data [ 'earliestTime' ]; The method also returns earliestTime so that you can tell the user in the error message when they are able again to create new content of the relevant type. Flood control entries are only stored for 31 days and older entries are cleaned up daily. The previously mentioned methods of FloodControl use the active user and the current timestamp as reference point. FloodControl also provides methods to register content or check flood control for other registered users or for guests via their IP address. For further details on these methods, please refer to the documentation in the FloodControl class . Do not interact directly with the flood control database table but only via the FloodControl class! DatabasePackageInstallationPlugin # DatabasePackageInstallationPlugin is a new idempotent package installation plugin (thus it is available in the sync function in the devtools) to update the database schema using the PHP-based database API. DatabasePackageInstallationPlugin is similar to ScriptPackageInstallationPlugin by requiring a PHP script that is included during the execution of the script. The script is expected to return an array of DatabaseTable objects representing the schema changes so that in contrast to using ScriptPackageInstallationPlugin , no DatabaseTableChangeProcessor object has to be created. The PHP file must be located in the acp/database/ directory for the devtools sync function to recognize the file. PHP Database API # The PHP API to add and change database tables during package installations and updates in the wcf\\system\\database\\table namespace now also supports renaming existing table columns with the new IDatabaseTableColumn::renameTo() method: 1 2 3 4 5 PartialDatabaseTable :: create ( 'wcf1_test' ) -> columns ([ NotNullInt10DatabaseTableColumn :: create ( 'oldName' ) -> renameTo ( 'newName' ) ]); Like with every change to existing database tables, packages can only rename columns that they installed. Captcha # The reCAPTCHA v1 implementation was completely removed. This includes the \\wcf\\system\\recaptcha\\RecaptchaHandler class (not to be confused with the one in the captcha namespace). The reCAPTCHA v1 endpoints have already been turned off by Google and always return a HTTP 404. Thus the implementation was completely non-functional even before this change. See WoltLab/WCF#3781 for details. Search # The generic implementation in the AbstractSearchEngine::parseSearchQuery() method was dangerous, because it did not have knowledge about the search engine\u2019s specifics. The implementation was completely removed: AbstractSearchEngine::parseSearchQuery() now always throws a \\BadMethodCallException . If you implemented a custom search engine and relied on this method, you can inline the previous implementation to preserve existing behavior. You should take the time to verify the rewritten queries against the manual of the search engine to make sure it cannot generate malformed queries or security issues. See WoltLab/WCF#3815 for details. Styles # The StyleCompiler class is marked final now. The internal SCSS compiler object being stored in the $compiler property was a design issue that leaked compiler state across multiple compiled styles, possibly causing misgenerated stylesheets. As the removal of the $compiler property effectively broke compatibility within the StyleCompiler and as the StyleCompiler never was meant to be extended, it was marked final. See WoltLab/WCF#3929 for details. Tags # Use of the wcf1_tag_to_object.languageID column is deprecated. The languageID column is redundant, because its value can be derived from the tagID . With WoltLab Suite 5.4, it will no longer be part of any indices, allowing more efficient index usage in the general case. If you need to filter the contents of wcf1_tag_to_object by language, you should perform an INNER JOIN wcf1_tag tag ON tag.tagID = tag_to_object.tagID and filter on wcf1_tag.languageID . See WoltLab/WCF#3904 for details. Avatars # The ISafeFormatAvatar interface was added to properly support fallback image types for use in emails. If your custom IUserAvatar implementation supports image types without broad support (i.e. anything other than PNG, JPEG, and GIF), then you should implement the ISafeFormatAvatar interface to return a fallback PNG, JPEG, or GIF image. See WoltLab/WCF#4001 for details. lineBreakSeparatedText Option Type # Currently, several of the (user group) options installed by our packages use the textarea option type and split its value by linebreaks to get a list of items, for example for allowed file extensions. To improve the user interface when setting up the value of such options, we have added the lineBreakSeparatedText option type as a drop-in replacement where the individual items are explicitly represented as distinct items in the user interface. Ignoring of Users # WoltLab Suite 5.4 distinguishes between blocking direct contact only and hiding all contents when ignoring users. To allow for detecting the difference, the UserProfile::getIgnoredUsers() and UserProfile::isIgnoredUser() methods received a new $type parameter. Pass either UserIgnore::TYPE_BLOCK_DIRECT_CONTACT or UserIgnore::TYPE_HIDE_MESSAGES depending on whether the check refers to a non-directed usage or content. See WoltLab/WCF#4064 and WoltLab/WCF#3981 for details. Database::prepare() # Database::prepare(string $statement, int $limit = 0, int $offset = 0): PreparedStatement works the same way as Database::prepareStatement() but additionally also replaces all occurences of app1_ with app{WCF_N}_ for all installed apps. This new method makes it superfluous to use WCF_N when building queries.","title":"PHP API"},{"location":"migration/wsc53/php/#migrating-from-wsc-53-php","text":"","title":"Migrating from WSC 5.3 - PHP"},{"location":"migration/wsc53/php/#minimum-requirements","text":"The minimum requirements have been increased to the following: PHP: 7.2.24 MySQL: 5.7.31 or 8.0.19 MariaDB: 10.1.44 Most notably PHP 7.2 contains usable support for scalar types by the addition of nullable types in PHP 7.1 and parameter type widening in PHP 7.2. It is recommended to make use of scalar types and other newly introduced features whereever possible. Please refer to the PHP documentation for details.","title":"Minimum requirements"},{"location":"migration/wsc53/php/#flood-control","text":"To prevent users from creating massive amounts of contents in short periods of time, i.e., spam, existing systems already use flood control mechanisms to limit the amount of contents created within a certain period of time. With WoltLab Suite 5.4, we have added a general API that manages such rate limiting. Leveraging this API is easily done. Register an object type for the definition com.woltlab.wcf.floodControl : com.example.foo.myContent . Whenever the active user creates content of this type, call 1 FloodControl :: getInstance () -> registerContent ( 'com.example.foo.myContent' ); You should only call this method if the user creates the content themselves. If the content is automatically created by the system, for example when copying / duplicating existing content, no activity should be registered. To check the last time when the active user created content of the relevant type, use 1 FloodControl :: getInstance () -> getLastTime ( 'com.example.foo.myContent' ); If you want to limit the number of content items created within a certain period of time, for example within one day, use 1 2 3 4 5 $data = FloodControl :: getInstance () -> countContent ( 'com.example.foo.myContent' , new \\DateInterval ( 'P1D' )); // number of content items created within the last day $count = $data [ 'count' ]; // timestamp when the earliest content item was created within the last day $earliestTime = $data [ 'earliestTime' ]; The method also returns earliestTime so that you can tell the user in the error message when they are able again to create new content of the relevant type. Flood control entries are only stored for 31 days and older entries are cleaned up daily. The previously mentioned methods of FloodControl use the active user and the current timestamp as reference point. FloodControl also provides methods to register content or check flood control for other registered users or for guests via their IP address. For further details on these methods, please refer to the documentation in the FloodControl class . Do not interact directly with the flood control database table but only via the FloodControl class!","title":"Flood Control"},{"location":"migration/wsc53/php/#databasepackageinstallationplugin","text":"DatabasePackageInstallationPlugin is a new idempotent package installation plugin (thus it is available in the sync function in the devtools) to update the database schema using the PHP-based database API. DatabasePackageInstallationPlugin is similar to ScriptPackageInstallationPlugin by requiring a PHP script that is included during the execution of the script. The script is expected to return an array of DatabaseTable objects representing the schema changes so that in contrast to using ScriptPackageInstallationPlugin , no DatabaseTableChangeProcessor object has to be created. The PHP file must be located in the acp/database/ directory for the devtools sync function to recognize the file.","title":"DatabasePackageInstallationPlugin"},{"location":"migration/wsc53/php/#php-database-api","text":"The PHP API to add and change database tables during package installations and updates in the wcf\\system\\database\\table namespace now also supports renaming existing table columns with the new IDatabaseTableColumn::renameTo() method: 1 2 3 4 5 PartialDatabaseTable :: create ( 'wcf1_test' ) -> columns ([ NotNullInt10DatabaseTableColumn :: create ( 'oldName' ) -> renameTo ( 'newName' ) ]); Like with every change to existing database tables, packages can only rename columns that they installed.","title":"PHP Database API"},{"location":"migration/wsc53/php/#captcha","text":"The reCAPTCHA v1 implementation was completely removed. This includes the \\wcf\\system\\recaptcha\\RecaptchaHandler class (not to be confused with the one in the captcha namespace). The reCAPTCHA v1 endpoints have already been turned off by Google and always return a HTTP 404. Thus the implementation was completely non-functional even before this change. See WoltLab/WCF#3781 for details.","title":"Captcha"},{"location":"migration/wsc53/php/#search","text":"The generic implementation in the AbstractSearchEngine::parseSearchQuery() method was dangerous, because it did not have knowledge about the search engine\u2019s specifics. The implementation was completely removed: AbstractSearchEngine::parseSearchQuery() now always throws a \\BadMethodCallException . If you implemented a custom search engine and relied on this method, you can inline the previous implementation to preserve existing behavior. You should take the time to verify the rewritten queries against the manual of the search engine to make sure it cannot generate malformed queries or security issues. See WoltLab/WCF#3815 for details.","title":"Search"},{"location":"migration/wsc53/php/#styles","text":"The StyleCompiler class is marked final now. The internal SCSS compiler object being stored in the $compiler property was a design issue that leaked compiler state across multiple compiled styles, possibly causing misgenerated stylesheets. As the removal of the $compiler property effectively broke compatibility within the StyleCompiler and as the StyleCompiler never was meant to be extended, it was marked final. See WoltLab/WCF#3929 for details.","title":"Styles"},{"location":"migration/wsc53/php/#tags","text":"Use of the wcf1_tag_to_object.languageID column is deprecated. The languageID column is redundant, because its value can be derived from the tagID . With WoltLab Suite 5.4, it will no longer be part of any indices, allowing more efficient index usage in the general case. If you need to filter the contents of wcf1_tag_to_object by language, you should perform an INNER JOIN wcf1_tag tag ON tag.tagID = tag_to_object.tagID and filter on wcf1_tag.languageID . See WoltLab/WCF#3904 for details.","title":"Tags"},{"location":"migration/wsc53/php/#avatars","text":"The ISafeFormatAvatar interface was added to properly support fallback image types for use in emails. If your custom IUserAvatar implementation supports image types without broad support (i.e. anything other than PNG, JPEG, and GIF), then you should implement the ISafeFormatAvatar interface to return a fallback PNG, JPEG, or GIF image. See WoltLab/WCF#4001 for details.","title":"Avatars"},{"location":"migration/wsc53/php/#linebreakseparatedtext-option-type","text":"Currently, several of the (user group) options installed by our packages use the textarea option type and split its value by linebreaks to get a list of items, for example for allowed file extensions. To improve the user interface when setting up the value of such options, we have added the lineBreakSeparatedText option type as a drop-in replacement where the individual items are explicitly represented as distinct items in the user interface.","title":"lineBreakSeparatedText Option Type"},{"location":"migration/wsc53/php/#ignoring-of-users","text":"WoltLab Suite 5.4 distinguishes between blocking direct contact only and hiding all contents when ignoring users. To allow for detecting the difference, the UserProfile::getIgnoredUsers() and UserProfile::isIgnoredUser() methods received a new $type parameter. Pass either UserIgnore::TYPE_BLOCK_DIRECT_CONTACT or UserIgnore::TYPE_HIDE_MESSAGES depending on whether the check refers to a non-directed usage or content. See WoltLab/WCF#4064 and WoltLab/WCF#3981 for details.","title":"Ignoring of Users"},{"location":"migration/wsc53/php/#databaseprepare","text":"Database::prepare(string $statement, int $limit = 0, int $offset = 0): PreparedStatement works the same way as Database::prepareStatement() but additionally also replaces all occurences of app1_ with app{WCF_N}_ for all installed apps. This new method makes it superfluous to use WCF_N when building queries.","title":"Database::prepare()"},{"location":"migration/wsc53/session/","text":"Migrating from WSC 5.3 - Session Handling and Authentication # WoltLab Suite 5.4 includes a completely refactored session handling. As long as you only interact with sessions via WCF::getSession() , especially when you perform read-only accesses, you should not notice any breaking changes. You might appreciate some of the new session methods if you process security sensitive data. Summary and Concepts # Most of the changes revolve around the removal of the legacy persistent login functionality and the assumption that every user has a single session only. Both aspects are related to each other. Legacy Persistent Login # The legacy persistent login was rather an automated login. Upon bootstrapping a session, it was checked whether the user had a cookie pair storing the user\u2019s userID and (a single BCrypt hash of) the user\u2019s password. If such a cookie pair exists and the BCrypt hash within the cookie matches the user\u2019s password hash when hashed again, the session would immediately changeUser() to the respective user. This legacy persistent login was completely removed. Instead, any sessions that belong to an authenticated user will automatically be long-lived. These long-lived sessions expire no sooner than 14 days after the last activity, ensuring that the user continously stays logged in, provided that they visit the page at least once per fortnight. Multiple Sessions # To allow for a proper separation of these long-lived user sessions, WoltLab Suite now allows for multiple sessions per user. These sessions are completely unrelated to each other. Specifically, they do not share session variables and they expire independently. As the existing wcf1_session table is also used for the online lists and location tracking, it will be maintained on a best effort basis. It no longer stores any private session data. The actual sessions storing security sensitive information are in an unrelated location. They must only be accessed via the PHP API exposed by the SessionHandler . Merged ACP and Frontend Sessions # WoltLab Suite 5.4 shares a single session across both the frontend, as well as the ACP. When a user logs in to the frontend, they will also be logged into the ACP and vice versa. Actual access to the ACP is controlled via the new reauthentication mechanism . The session variable store is scoped: Session variables set within the frontend are not available within the ACP and vice versa. Improved Authentication and Reauthentication # WoltLab Suite 5.4 ships with multi-factor authentication support and a generic re-authentication implementation that can be used to verify the account owner\u2019s presence. Additions and Changes # Password Hashing # WoltLab Suite 5.4 includes a new object-oriented password hashing framework that is modeled after PHP\u2019s password_* API. Check PasswordAlgorithmManager and IPasswordAlgorithm for details. The new default password hash is a standard BCrypt hash. All newly generated hashes in wcf1_user.password will now include a type prefix, instead of just passwords imported from other systems. Session Storage # The wcf1_session table will no longer be used for session storage. Instead, it is maintained for compatibility with existing online lists. The actual session storage is considered an implementation detail and you must not directly interact with the session tables. Future versions might support alternative session backends, such as Redis. Do not interact directly with the session database tables but only via the SessionHandler class! Reauthentication # For security sensitive processing, you might want to ensure that the account owner is actually present instead of a third party accessing a session that was accidentally left logged in. WoltLab Suite 5.4 ships with a generic reauthentication framework. To request reauthentication within your controller you need to: Use the wcf\\system\\user\\authentication\\TReauthenticationCheck trait. Call: 1 2 3 $this -> requestReauthentication ( LinkHandler :: getInstance () -> getControllerLink ( static :: class , [ /* additional parameters */ ])); requestReauthentication() will check if the user has recently authenticated themselves. If they did, the request proceeds as usual. Otherwise, they will be asked to reauthenticate themselves. After the successful authentication, they will be redirected to the URL that was passed as the first parameter (the current controller within the example). Details can be found in WoltLab/WCF#3775 . Multi-factor Authentication # To implement multi-factor authentication securely, WoltLab Suite 5.4 implements the concept of a \u201cpending user change\u201d. The user will not be logged in (i.e. WCF::getUser()->userID returns null ) until they authenticate themselves with their second factor. Requesting multi-factor authentication is done on an opt-in basis for compatibility reasons. If you perform authentication yourself and do not trust the authentication source to perform multi-factor authentication itself, you will need to adjust your logic to request multi-factor authentication from WoltLab Suite: Previously: 1 WCF :: getSession () -> changeUser ( $targetUser ); Now: 1 2 3 4 5 6 7 8 9 10 $isPending = WCF :: getSession () -> changeUserAfterMultifactorAuthentication ( $targetUser ); if ( $isPending ) { // Redirect to the authentication form. The user will not be logged in. // Note: Do not use `getControllerLink` to support both the frontend as well as the ACP. HeaderUtil :: redirect ( LinkHandler :: getInstance () -> getLink ( 'MultifactorAuthentication' , [ 'url' => /* Return To */ , ])); exit ; } // Proceed as usual. The user will be logged in. Adding Multi-factor Methods # Adding your own multi-factor method requires the implementation of a single object type: objectType.xml 1 2 3 4 5 6 7 <type> <name> com.example.multifactor.foobar </name> <definitionname> com.woltlab.wcf.multifactor </definitionname> <icon> <!-- Font Awesome 4 Icon Name goes here. --> </icon> <priority> <!-- Determines the sort order, higher priority will be preferred for authentication. --> </priority> <classname> wcf\\system\\user\\multifactor\\FoobarMultifactorMethod </classname> </type> The given classname must implement the IMultifactorMethod interface. As a self-contained example, you can find the initial implementation of the email multi-factor method in WoltLab/WCF#3729 . Please check the version history of the PHP class to make sure you do not miss important changes that were added later. Multi-factor authentication is security sensitive. Make sure to carefully read the remarks in IMultifactorMethod for possible issues. Also make sure to carefully test your implementation against all sorts of incorrect input and consider attack vectors such as race conditions. It is strongly recommended to generously check the current state by leveraging assertions and exceptions. Enforcing Multi-factor Authentication # To enforce Multi-factor Authentication within your controller you need to: Use the wcf\\system\\user\\multifactor\\TMultifactorRequirementEnforcer trait. Call: $this->enforceMultifactorAuthentication(); enforceMultifactorAuthentication() will check if the user is in a group that requires multi-factor authentication, but does not yet have multi-factor authentication enabled. If they did, the request proceeds as usual. Otherwise, a NamedUserException is thrown. Deprecations and Removals # SessionHandler # Most of the changes with regard to the new session handling happened in SessionHandler . Most notably, SessionHandler now is marked final to ensure proper encapsulation of data. A number of methods in SessionHandler are now deprecated and result in a noop. This change mostly affects methods that have been used to bootstrap the session, such as setHasValidCookie() . Additionally, accessing the following keys on the session is deprecated. They directly map to an existing method in another class and any uses can easily be updated: - ipAddress - userAgent - requestURI - requestMethod - lastActivityTime Refer to the implementation for details. ACP Sessions # The database tables related to ACP sessions have been removed. The PHP classes have been preserved due to being used within the class hierarchy of the legacy sessions. Cookies # The _userID , _password , _cookieHash and _cookieHash_acp cookies will no longer be created nor consumed. Virtual Sessions # The virtual session logic existed to support multiple devices per single session in wcf1_session . Virtual sessions are no longer required with the refactored session handling. Anything related to virtual sessions has been completely removed as they are considered an implementation detail. This removal includes PHP classes and database tables. Security Token Constants # The security token constants are deprecated. Instead, the methods of SessionHandler should be used (e.g. ->getSecurityToken() ). Within templates, you should migrate to the {csrfToken} tag in place of {@SECURITY_TOKEN_INPUT_TAG} . The {csrfToken} tag is a drop-in replacement and was backported to WoltLab Suite 5.2+, allowing you to maintain compatibility across a broad range of versions. PasswordUtil and Double BCrypt Hashes # Most of the methods in PasswordUtil are deprecated in favor of the new password hashing framework.","title":"Session Handling and Authentication"},{"location":"migration/wsc53/session/#migrating-from-wsc-53-session-handling-and-authentication","text":"WoltLab Suite 5.4 includes a completely refactored session handling. As long as you only interact with sessions via WCF::getSession() , especially when you perform read-only accesses, you should not notice any breaking changes. You might appreciate some of the new session methods if you process security sensitive data.","title":"Migrating from WSC 5.3 - Session Handling and Authentication"},{"location":"migration/wsc53/session/#summary-and-concepts","text":"Most of the changes revolve around the removal of the legacy persistent login functionality and the assumption that every user has a single session only. Both aspects are related to each other.","title":"Summary and Concepts"},{"location":"migration/wsc53/session/#legacy-persistent-login","text":"The legacy persistent login was rather an automated login. Upon bootstrapping a session, it was checked whether the user had a cookie pair storing the user\u2019s userID and (a single BCrypt hash of) the user\u2019s password. If such a cookie pair exists and the BCrypt hash within the cookie matches the user\u2019s password hash when hashed again, the session would immediately changeUser() to the respective user. This legacy persistent login was completely removed. Instead, any sessions that belong to an authenticated user will automatically be long-lived. These long-lived sessions expire no sooner than 14 days after the last activity, ensuring that the user continously stays logged in, provided that they visit the page at least once per fortnight.","title":"Legacy Persistent Login"},{"location":"migration/wsc53/session/#multiple-sessions","text":"To allow for a proper separation of these long-lived user sessions, WoltLab Suite now allows for multiple sessions per user. These sessions are completely unrelated to each other. Specifically, they do not share session variables and they expire independently. As the existing wcf1_session table is also used for the online lists and location tracking, it will be maintained on a best effort basis. It no longer stores any private session data. The actual sessions storing security sensitive information are in an unrelated location. They must only be accessed via the PHP API exposed by the SessionHandler .","title":"Multiple Sessions"},{"location":"migration/wsc53/session/#merged-acp-and-frontend-sessions","text":"WoltLab Suite 5.4 shares a single session across both the frontend, as well as the ACP. When a user logs in to the frontend, they will also be logged into the ACP and vice versa. Actual access to the ACP is controlled via the new reauthentication mechanism . The session variable store is scoped: Session variables set within the frontend are not available within the ACP and vice versa.","title":"Merged ACP and Frontend Sessions"},{"location":"migration/wsc53/session/#improved-authentication-and-reauthentication","text":"WoltLab Suite 5.4 ships with multi-factor authentication support and a generic re-authentication implementation that can be used to verify the account owner\u2019s presence.","title":"Improved Authentication and Reauthentication"},{"location":"migration/wsc53/session/#additions-and-changes","text":"","title":"Additions and Changes"},{"location":"migration/wsc53/session/#password-hashing","text":"WoltLab Suite 5.4 includes a new object-oriented password hashing framework that is modeled after PHP\u2019s password_* API. Check PasswordAlgorithmManager and IPasswordAlgorithm for details. The new default password hash is a standard BCrypt hash. All newly generated hashes in wcf1_user.password will now include a type prefix, instead of just passwords imported from other systems.","title":"Password Hashing"},{"location":"migration/wsc53/session/#session-storage","text":"The wcf1_session table will no longer be used for session storage. Instead, it is maintained for compatibility with existing online lists. The actual session storage is considered an implementation detail and you must not directly interact with the session tables. Future versions might support alternative session backends, such as Redis. Do not interact directly with the session database tables but only via the SessionHandler class!","title":"Session Storage"},{"location":"migration/wsc53/session/#reauthentication","text":"For security sensitive processing, you might want to ensure that the account owner is actually present instead of a third party accessing a session that was accidentally left logged in. WoltLab Suite 5.4 ships with a generic reauthentication framework. To request reauthentication within your controller you need to: Use the wcf\\system\\user\\authentication\\TReauthenticationCheck trait. Call: 1 2 3 $this -> requestReauthentication ( LinkHandler :: getInstance () -> getControllerLink ( static :: class , [ /* additional parameters */ ])); requestReauthentication() will check if the user has recently authenticated themselves. If they did, the request proceeds as usual. Otherwise, they will be asked to reauthenticate themselves. After the successful authentication, they will be redirected to the URL that was passed as the first parameter (the current controller within the example). Details can be found in WoltLab/WCF#3775 .","title":"Reauthentication"},{"location":"migration/wsc53/session/#multi-factor-authentication","text":"To implement multi-factor authentication securely, WoltLab Suite 5.4 implements the concept of a \u201cpending user change\u201d. The user will not be logged in (i.e. WCF::getUser()->userID returns null ) until they authenticate themselves with their second factor. Requesting multi-factor authentication is done on an opt-in basis for compatibility reasons. If you perform authentication yourself and do not trust the authentication source to perform multi-factor authentication itself, you will need to adjust your logic to request multi-factor authentication from WoltLab Suite: Previously: 1 WCF :: getSession () -> changeUser ( $targetUser ); Now: 1 2 3 4 5 6 7 8 9 10 $isPending = WCF :: getSession () -> changeUserAfterMultifactorAuthentication ( $targetUser ); if ( $isPending ) { // Redirect to the authentication form. The user will not be logged in. // Note: Do not use `getControllerLink` to support both the frontend as well as the ACP. HeaderUtil :: redirect ( LinkHandler :: getInstance () -> getLink ( 'MultifactorAuthentication' , [ 'url' => /* Return To */ , ])); exit ; } // Proceed as usual. The user will be logged in.","title":"Multi-factor Authentication"},{"location":"migration/wsc53/session/#adding-multi-factor-methods","text":"Adding your own multi-factor method requires the implementation of a single object type: objectType.xml 1 2 3 4 5 6 7 <type> <name> com.example.multifactor.foobar </name> <definitionname> com.woltlab.wcf.multifactor </definitionname> <icon> <!-- Font Awesome 4 Icon Name goes here. --> </icon> <priority> <!-- Determines the sort order, higher priority will be preferred for authentication. --> </priority> <classname> wcf\\system\\user\\multifactor\\FoobarMultifactorMethod </classname> </type> The given classname must implement the IMultifactorMethod interface. As a self-contained example, you can find the initial implementation of the email multi-factor method in WoltLab/WCF#3729 . Please check the version history of the PHP class to make sure you do not miss important changes that were added later. Multi-factor authentication is security sensitive. Make sure to carefully read the remarks in IMultifactorMethod for possible issues. Also make sure to carefully test your implementation against all sorts of incorrect input and consider attack vectors such as race conditions. It is strongly recommended to generously check the current state by leveraging assertions and exceptions.","title":"Adding Multi-factor Methods"},{"location":"migration/wsc53/session/#enforcing-multi-factor-authentication","text":"To enforce Multi-factor Authentication within your controller you need to: Use the wcf\\system\\user\\multifactor\\TMultifactorRequirementEnforcer trait. Call: $this->enforceMultifactorAuthentication(); enforceMultifactorAuthentication() will check if the user is in a group that requires multi-factor authentication, but does not yet have multi-factor authentication enabled. If they did, the request proceeds as usual. Otherwise, a NamedUserException is thrown.","title":"Enforcing Multi-factor Authentication"},{"location":"migration/wsc53/session/#deprecations-and-removals","text":"","title":"Deprecations and Removals"},{"location":"migration/wsc53/session/#sessionhandler","text":"Most of the changes with regard to the new session handling happened in SessionHandler . Most notably, SessionHandler now is marked final to ensure proper encapsulation of data. A number of methods in SessionHandler are now deprecated and result in a noop. This change mostly affects methods that have been used to bootstrap the session, such as setHasValidCookie() . Additionally, accessing the following keys on the session is deprecated. They directly map to an existing method in another class and any uses can easily be updated: - ipAddress - userAgent - requestURI - requestMethod - lastActivityTime Refer to the implementation for details.","title":"SessionHandler"},{"location":"migration/wsc53/session/#acp-sessions","text":"The database tables related to ACP sessions have been removed. The PHP classes have been preserved due to being used within the class hierarchy of the legacy sessions.","title":"ACP Sessions"},{"location":"migration/wsc53/session/#cookies","text":"The _userID , _password , _cookieHash and _cookieHash_acp cookies will no longer be created nor consumed.","title":"Cookies"},{"location":"migration/wsc53/session/#virtual-sessions","text":"The virtual session logic existed to support multiple devices per single session in wcf1_session . Virtual sessions are no longer required with the refactored session handling. Anything related to virtual sessions has been completely removed as they are considered an implementation detail. This removal includes PHP classes and database tables.","title":"Virtual Sessions"},{"location":"migration/wsc53/session/#security-token-constants","text":"The security token constants are deprecated. Instead, the methods of SessionHandler should be used (e.g. ->getSecurityToken() ). Within templates, you should migrate to the {csrfToken} tag in place of {@SECURITY_TOKEN_INPUT_TAG} . The {csrfToken} tag is a drop-in replacement and was backported to WoltLab Suite 5.2+, allowing you to maintain compatibility across a broad range of versions.","title":"Security Token Constants"},{"location":"migration/wsc53/session/#passwordutil-and-double-bcrypt-hashes","text":"Most of the methods in PasswordUtil are deprecated in favor of the new password hashing framework.","title":"PasswordUtil and Double BCrypt Hashes"},{"location":"migration/wsc53/templates/","text":"Migrating from WSC 5.3 - Templates and Languages # {csrfToken} # Going forward, any uses of the SECURITY_TOKEN_* constants should be avoided. To reference the CSRF token (\u201cSecurity Token\u201d) within templates, the {csrfToken} template plugin was added. Before: 1 2 { @ SECURITY_TOKEN_INPUT_TAG } { link controller = \"Foo\" } t= { @ SECURITY_TOKEN }{ /link } After: 1 2 3 { csrfToken } { link controller = \"Foo\" } t= { csrfToken type = url }{ /link } { * The use of the CSRF token in URLs is discouraged. Modifications should happen by means of a POST request. * } The {csrfToken} plugin was backported to WoltLab Suite 5.2 and higher, allowing compatibility with a large range of WoltLab Suite branches. See WoltLab/WCF#3612 for details. RSS Feed Links # Prior to version 5.4 of WoltLab Suite, all RSS feed links contained the access token for logged-in users so that the feed shows all contents the specific user has access to. With version 5.4, links with the CSS class rssFeed will open a dialog when clicked that offers the feed link with the access token for personal use and an anonymous feed link that can be shared with others. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 { * before * } <li> <a rel=\"alternate\" { * * } href=\" { if $__wcf -> getUser ()-> userID }{ link controller = 'ArticleFeed' } at= { @ $__wcf -> getUser ()-> userID } - { @ $__wcf -> getUser ()-> accessToken }{ /link }{ else }{ link controller = 'ArticleFeed' }{ /link }{ /if } \" { * * } title=\" { lang } wcf.global.button.rss { /lang } \" { * * } class=\"jsTooltip\" { * * } > <span class=\"icon icon16 fa-rss\"></span> <span class=\"invisible\"> { lang } wcf.global.button.rss { /lang } </span> </a> </li> { * after * } <li> <a rel=\"alternate\" { * * } href=\" { if $__wcf -> getUser ()-> userID }{ link controller = 'ArticleFeed' } at= { @ $__wcf -> getUser ()-> userID } - { @ $__wcf -> getUser ()-> accessToken }{ /link }{ else }{ link controller = 'ArticleFeed' }{ /link }{ /if } \" { * * } title=\" { lang } wcf.global.button.rss { /lang } \" { * * } class=\"rssFeed jsTooltip\" { * * } > <span class=\"icon icon16 fa-rss\"></span> <span class=\"invisible\"> { lang } wcf.global.button.rss { /lang } </span> </a> </li>","title":"Templates"},{"location":"migration/wsc53/templates/#migrating-from-wsc-53-templates-and-languages","text":"","title":"Migrating from WSC 5.3 - Templates and Languages"},{"location":"migration/wsc53/templates/#csrftoken","text":"Going forward, any uses of the SECURITY_TOKEN_* constants should be avoided. To reference the CSRF token (\u201cSecurity Token\u201d) within templates, the {csrfToken} template plugin was added. Before: 1 2 { @ SECURITY_TOKEN_INPUT_TAG } { link controller = \"Foo\" } t= { @ SECURITY_TOKEN }{ /link } After: 1 2 3 { csrfToken } { link controller = \"Foo\" } t= { csrfToken type = url }{ /link } { * The use of the CSRF token in URLs is discouraged. Modifications should happen by means of a POST request. * } The {csrfToken} plugin was backported to WoltLab Suite 5.2 and higher, allowing compatibility with a large range of WoltLab Suite branches. See WoltLab/WCF#3612 for details.","title":"{csrfToken}"},{"location":"migration/wsc53/templates/#rss-feed-links","text":"Prior to version 5.4 of WoltLab Suite, all RSS feed links contained the access token for logged-in users so that the feed shows all contents the specific user has access to. With version 5.4, links with the CSS class rssFeed will open a dialog when clicked that offers the feed link with the access token for personal use and an anonymous feed link that can be shared with others. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 { * before * } <li> <a rel=\"alternate\" { * * } href=\" { if $__wcf -> getUser ()-> userID }{ link controller = 'ArticleFeed' } at= { @ $__wcf -> getUser ()-> userID } - { @ $__wcf -> getUser ()-> accessToken }{ /link }{ else }{ link controller = 'ArticleFeed' }{ /link }{ /if } \" { * * } title=\" { lang } wcf.global.button.rss { /lang } \" { * * } class=\"jsTooltip\" { * * } > <span class=\"icon icon16 fa-rss\"></span> <span class=\"invisible\"> { lang } wcf.global.button.rss { /lang } </span> </a> </li> { * after * } <li> <a rel=\"alternate\" { * * } href=\" { if $__wcf -> getUser ()-> userID }{ link controller = 'ArticleFeed' } at= { @ $__wcf -> getUser ()-> userID } - { @ $__wcf -> getUser ()-> accessToken }{ /link }{ else }{ link controller = 'ArticleFeed' }{ /link }{ /if } \" { * * } title=\" { lang } wcf.global.button.rss { /lang } \" { * * } class=\"rssFeed jsTooltip\" { * * } > <span class=\"icon icon16 fa-rss\"></span> <span class=\"invisible\"> { lang } wcf.global.button.rss { /lang } </span> </a> </li>","title":"RSS Feed Links"},{"location":"migration/wsc54/deprecations_removals/","text":"Migrating from WSC 5.4 - Deprecations and Removals # With version 5.5, we have deprecated certain components and removed several other components that have been deprecated for many years. Deprecations # PHP # Classes # filebase\\system\\file\\FileDataHandler (use filebase\\system\\cache\\runtime\\FileRuntimeCache ) wcf\\action\\AbstractAjaxAction (use PSR-7 responses, WoltLab/WCF#4437 ) wcf\\data\\IExtendedMessageQuickReplyAction ( WoltLab/WCF#4575 ) wcf\\form\\SearchForm (see WoltLab/WCF#4605 ) wcf\\page\\AbstractSecurePage ( WoltLab/WCF#4515 ) wcf\\page\\SearchResultPage (see WoltLab/WCF#4605 ) wcf\\system\\database\\table\\column\\TUnsupportedDefaultValue (do not implement IDefaultValueDatabaseTableColumn , see WoltLab/WCF#4733 ) wcf\\system\\exception\\ILoggingAwareException ( WoltLab/WCF#4547 ) wcf\\system\\io\\FTP (directly use the FTP extension) wcf\\system\\search\\AbstractSearchableObjectType (use AbstractSearchProvider instead, see WoltLab/WCF#4605 ) wcf\\system\\search\\elasticsearch\\ElasticsearchException wcf\\system\\search\\ISearchableObjectType (use ISearchProvider instead, see WoltLab/WCF#4605 ) wcf\\util\\PasswordUtil Methods # wcf\\action\\MessageQuoteAction::markForRemoval() ( WoltLab/WCF#4452 ) wcf\\data\\user\\avatar\\UserAvatarAction::fetchRemoteAvatar() ( WoltLab/WCF#4744 ) wcf\\data\\user\\notification\\UserNotificationAction::getOutstandingNotifications() ( WoltLab/WCF#4603 ) wcf\\data\\moderation\\queue\\ModerationQueueAction::getOutstandingQueues() ( WoltLab/WCF#4603 ) wcf\\system\\message\\QuickReplyManager::setTmpHash() ( WoltLab/WCF#4575 ) wcf\\system\\request\\Request::isExecuted() ( WoltLab/WCF#4485 ) wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::query() wcf\\system\\session\\Session::getDeviceIcon() ( WoltLab/WCF#4525 ) wcf\\system\\user\\authentication\\password\\algorithm\\TPhpass::hash() ( WoltLab/WCF#4602 ) wcf\\system\\user\\authentication\\password\\algorithm\\TPhpass::needsRehash() ( WoltLab/WCF#4602 ) wcf\\system\\WCF::getAnchor() ( WoltLab/WCF#4580 ) wcf\\util\\MathUtil::getRandomValue() ( WoltLab/WCF#4280 ) wcf\\util\\StringUtil::encodeJSON() ( WoltLab/WCF#4645 ) wcf\\util\\StringUtil::endsWith() ( WoltLab/WCF#4509 ) wcf\\util\\StringUtil::getHash() ( WoltLab/WCF#4279 ) wcf\\util\\StringUtil::split() ( WoltLab/WCF#4513 ) wcf\\util\\StringUtil::startsWith() ( WoltLab/WCF#4509 ) wcf\\util\\UserUtil::isAvailableEmail() ( WoltLab/WCF#4602 ) wcf\\util\\UserUtil::isAvailableUsername() ( WoltLab/WCF#4602 ) Properties # wcf\\acp\\page\\PackagePage::$compatibleVersions ( WoltLab/WCF#4371 ) wcf\\system\\io\\GZipFile::$gzopen64 ( WoltLab/WCF#4381 ) Constants # wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::DELETE wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::GET wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::POST wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::PUT wcf\\system\\visitTracker\\VisitTracker::DEFAULT_LIFETIME ( WoltLab/WCF#4757 ) Functions # The global escapeString helper ( WoltLab/WCF#4506 ) Options # HTTP_SEND_X_FRAME_OPTIONS ( WoltLab/WCF#4474 ) ELASTICSEARCH_ALLOW_LEADING_WILDCARD WBB_MODULE_IGNORE_BOARDS (The option will be always on with WoltLab Suite Forum 5.5 and will be removed with a future version.) ENABLE_DESKTOP_NOTIFICATIONS ( WoltLab/WCF#4806 ) JavaScript # WCF.Message.Quote.Manager.markQuotesForRemoval() ( WoltLab/WCF#4452 ) WCF.Search.Message.KeywordList ( WoltLab/WCF#4402 ) SECURITY_TOKEN (use Core.getXsrfToken() , WoltLab/WCF#4523 ) WCF.Dropdown.Interactive.Handler ( WoltLab/WCF#4603 ) WCF.Dropdown.Interactive.Instance ( WoltLab/WCF#4603 ) WCF.User.Panel.Abstract ( WoltLab/WCF#4603 ) Database Tables # wcf1_package_compatibility ( WoltLab/WCF#4371 ) wcf1_package_update_compatibility ( WoltLab/WCF#4385 ) wcf1_package_update_optional ( WoltLab/WCF#4432 ) Templates # Template Modifiers # |encodeJSON ( WoltLab/WCF#4645 ) Template Events # pageNavbarTop::navigationIcons search::queryOptions search::authorOptions search::periodOptions search::displayOptions search::generalFields Miscellaneous # The global option to set a specific style with a request parameter ( $_REQUEST['styleID'] ) is deprecated ( WoltLab/WCF@0c0111e946 ) Removals # PHP # Classes # gallery\\util\\ExifUtil wbb\\action\\BoardQuickSearchAction wbb\\data\\thread\\NewsList wbb\\data\\thread\\News wcf\\action\\PollAction ( WoltLab/WCF#4662 ) wcf\\form\\RecaptchaForm ( WoltLab/WCF#4289 ) wcf\\system\\background\\job\\ElasticSearchIndexBackgroundJob wcf\\system\\cache\\builder\\TemplateListenerCacheBuilder ( WoltLab/WCF#4297 ) wcf\\system\\log\\modification\\ModificationLogHandler ( WoltLab/WCF#4340 ) wcf\\system\\recaptcha\\RecaptchaHandlerV2 ( WoltLab/WCF#4289 ) wcf\\system\\search\\SearchKeywordManager ( WoltLab/WCF#4313 ) The SCSS compiler\u2019s Leafo class aliases ( WoltLab/WCF#4343 , Migration Guide from 5.2 to 5.3 ) Methods # wbb\\data\\board\\BoardCache::getLabelGroups() wbb\\data\\post\\PostAction::jumpToExtended() (this method always threw a BadMethodCallException ) wbb\\data\\thread\\ThreadAction::countReplies() wbb\\data\\thread\\ThreadAction::validateCountReplies() wcf\\acp\\form\\UserGroupOptionForm::verifyPermissions() ( WoltLab/WCF#4312 ) wcf\\data\\conversation\\message\\ConversationMessageAction::jumpToExtended() ( WoltLab/com.woltlab.wcf.conversation#162 ) wcf\\data\\moderation\\queue\\ModerationQueueEditor::markAsDone() ( WoltLab/WCF#4317 ) wcf\\data\\tag\\TagCloudTag::getSize() ( WoltLab/WCF#4325 ) wcf\\data\\tag\\TagCloudTag::setSize() ( WoltLab/WCF#4325 ) wcf\\data\\user\\User::getSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::getSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::saveSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::validateGetSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::validateSaveSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\avatar\\DefaultAvatar::canCrop() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\DefaultAvatar::getCropImageTag() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\UserAvatar::canCrop() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\UserAvatar::getCropImageTag() ( WoltLab/WCF#4310 ) wcf\\system\\bbcode\\BBCodeHandler::setAllowedBBCodes() ( WoltLab/WCF#4319 ) wcf\\system\\bbcode\\BBCodeParser::validateBBCodes() ( WoltLab/WCF#4319 ) wcf\\system\\breadcrumb\\Breadcrumbs::add() ( WoltLab/WCF#4298 ) wcf\\system\\breadcrumb\\Breadcrumbs::remove() ( WoltLab/WCF#4298 ) wcf\\system\\breadcrumb\\Breadcrumbs::replace() ( WoltLab/WCF#4298 ) wcf\\system\\form\\builder\\IFormNode::create() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateAttribute() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateClass() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateId() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\IAttributeFormField::validateFieldAttribute() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\dependency\\IFormFieldDependency::create() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\validation\\IFormFieldValidator::validateId() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\message\\embedded\\object\\MessageEmbeddedObjectManager::parseTemporaryMessage() ( WoltLab/WCF#4299 ) wcf\\system\\package\\PackageArchive::getPhpRequirements() ( WoltLab/WCF#4311 ) wcf\\system\\search\\ISearchIndexManager::add() (Removal from Interface, see WoltLab/WCF#4508 ) wcf\\system\\search\\ISearchIndexManager::update() (Removal from Interface, see WoltLab/WCF#4508 ) wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::_add() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::_delete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::add() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::bulkAdd() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::bulkDelete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::delete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::update() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::add() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::update() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchEngine::parseSearchQuery() Properties # wcf\\data\\category\\Category::$permissions ( WoltLab/WCF#4303 ) wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::$bulkTypeName Constants # wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::HEAD wcf\\system\\tagging\\TagCloud::MAX_FONT_SIZE ( WoltLab/WCF#4325 ) wcf\\system\\tagging\\TagCloud::MIN_FONT_SIZE ( WoltLab/WCF#4325 ) Options # ENABLE_CENSORSHIP (always call Censorship::test() , see WoltLab/WCF#4567 ) MODULE_SYSTEM_RECAPTCHA ( WoltLab/WCF#4305 ) PROFILE_MAIL_USE_CAPTCHA ( WoltLab/WCF#4399 ) The may value for MAIL_SMTP_STARTTLS ( WoltLab/WCF#4398 ) SEARCH_USE_CAPTCHA (see WoltLab/WCF#4605 ) Files # acp/dereferrer.php JavaScript # Blog.Entry.QuoteHandler (use WoltLabSuite/Blog/Ui/Entry/Quote ) Calendar.Event.QuoteHandler (use WoltLabSuite/Calendar/Ui/Event/Quote ) WBB.Board.IgnoreBoards (use WoltLabSuite/Forum/Ui/Board/Ignore ) WBB.Board.MarkAllAsRead (use WoltLabSuite/Forum/Ui/Board/MarkAllAsRead ) WBB.Board.MarkAsRead (use WoltLabSuite/Forum/Ui/Board/MarkAsRead ) WBB.Post.QuoteHandler (use WoltLabSuite/Forum/Ui/Post/Quote ) WBB.Thread.LastPageHandler (use WoltLabSuite/Forum/Ui/Thread/LastPageHandler ) WBB.Thread.MarkAsRead (use WoltLabSuite/Forum/Ui/Thread/MarkAsRead ) WBB.Thread.SimilarThreads (use WoltLabSuite/Forum/Ui/Thread/SimilarThreads ) WBB.Thread.WatchedThreadList (use WoltLabSuite/Forum/Controller/Thread/WatchedList ) WCF.ACP.Style.ImageUpload ( WoltLab/WCF#4323 ) WCF.ColorPicker (see migration guide for WCF.ColorPicker ) WCF.Conversation.Message.QuoteHandler (use WoltLabSuite/Core/Conversation/Ui/Message/Quote , see WoltLab/com.woltlab.wcf.conversation#155 ) WCF.Like.js ( WoltLab/WCF#4300 ) WCF.Message.UserMention ( WoltLab/WCF#4324 ) WCF.Poll.Manager ( WoltLab/WCF#4662 ) WCF.UserPanel ( WoltLab/WCF#4316 ) WCF.User.Panel.Moderation ( WoltLab/WCF#4603 ) WCF.User.Panel.Notification ( WoltLab/WCF#4603 ) WCF.User.Panel.UserMenu ( WoltLab/WCF#4603 ) Phrases # wbb.search.boards.all wcf.global.form.error.greaterThan.javaScript ( WoltLab/WCF#4306 ) wcf.global.form.error.lessThan.javaScript ( WoltLab/WCF#4306 ) wcf.search.type.keywords wcf.acp.option.search_use_captcha wcf.search.query.description wcf.search.results.change wcf.search.results.description wcf.search.general wcf.search.query wcf.search.error.noMatches wcf.search.error.user.noMatches Templates # Templates # searchResult Template Events # search::tabMenuTabs search::sections tagSearch::tabMenuTabs tagSearch::sections Miscellaneous # Object specific VisitTracker lifetimes ( WoltLab/WCF#4757 )","title":"Deprecations and Removals"},{"location":"migration/wsc54/deprecations_removals/#migrating-from-wsc-54-deprecations-and-removals","text":"With version 5.5, we have deprecated certain components and removed several other components that have been deprecated for many years.","title":"Migrating from WSC 5.4 - Deprecations and Removals"},{"location":"migration/wsc54/deprecations_removals/#deprecations","text":"","title":"Deprecations"},{"location":"migration/wsc54/deprecations_removals/#php","text":"","title":"PHP"},{"location":"migration/wsc54/deprecations_removals/#classes","text":"filebase\\system\\file\\FileDataHandler (use filebase\\system\\cache\\runtime\\FileRuntimeCache ) wcf\\action\\AbstractAjaxAction (use PSR-7 responses, WoltLab/WCF#4437 ) wcf\\data\\IExtendedMessageQuickReplyAction ( WoltLab/WCF#4575 ) wcf\\form\\SearchForm (see WoltLab/WCF#4605 ) wcf\\page\\AbstractSecurePage ( WoltLab/WCF#4515 ) wcf\\page\\SearchResultPage (see WoltLab/WCF#4605 ) wcf\\system\\database\\table\\column\\TUnsupportedDefaultValue (do not implement IDefaultValueDatabaseTableColumn , see WoltLab/WCF#4733 ) wcf\\system\\exception\\ILoggingAwareException ( WoltLab/WCF#4547 ) wcf\\system\\io\\FTP (directly use the FTP extension) wcf\\system\\search\\AbstractSearchableObjectType (use AbstractSearchProvider instead, see WoltLab/WCF#4605 ) wcf\\system\\search\\elasticsearch\\ElasticsearchException wcf\\system\\search\\ISearchableObjectType (use ISearchProvider instead, see WoltLab/WCF#4605 ) wcf\\util\\PasswordUtil","title":"Classes"},{"location":"migration/wsc54/deprecations_removals/#methods","text":"wcf\\action\\MessageQuoteAction::markForRemoval() ( WoltLab/WCF#4452 ) wcf\\data\\user\\avatar\\UserAvatarAction::fetchRemoteAvatar() ( WoltLab/WCF#4744 ) wcf\\data\\user\\notification\\UserNotificationAction::getOutstandingNotifications() ( WoltLab/WCF#4603 ) wcf\\data\\moderation\\queue\\ModerationQueueAction::getOutstandingQueues() ( WoltLab/WCF#4603 ) wcf\\system\\message\\QuickReplyManager::setTmpHash() ( WoltLab/WCF#4575 ) wcf\\system\\request\\Request::isExecuted() ( WoltLab/WCF#4485 ) wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::query() wcf\\system\\session\\Session::getDeviceIcon() ( WoltLab/WCF#4525 ) wcf\\system\\user\\authentication\\password\\algorithm\\TPhpass::hash() ( WoltLab/WCF#4602 ) wcf\\system\\user\\authentication\\password\\algorithm\\TPhpass::needsRehash() ( WoltLab/WCF#4602 ) wcf\\system\\WCF::getAnchor() ( WoltLab/WCF#4580 ) wcf\\util\\MathUtil::getRandomValue() ( WoltLab/WCF#4280 ) wcf\\util\\StringUtil::encodeJSON() ( WoltLab/WCF#4645 ) wcf\\util\\StringUtil::endsWith() ( WoltLab/WCF#4509 ) wcf\\util\\StringUtil::getHash() ( WoltLab/WCF#4279 ) wcf\\util\\StringUtil::split() ( WoltLab/WCF#4513 ) wcf\\util\\StringUtil::startsWith() ( WoltLab/WCF#4509 ) wcf\\util\\UserUtil::isAvailableEmail() ( WoltLab/WCF#4602 ) wcf\\util\\UserUtil::isAvailableUsername() ( WoltLab/WCF#4602 )","title":"Methods"},{"location":"migration/wsc54/deprecations_removals/#properties","text":"wcf\\acp\\page\\PackagePage::$compatibleVersions ( WoltLab/WCF#4371 ) wcf\\system\\io\\GZipFile::$gzopen64 ( WoltLab/WCF#4381 )","title":"Properties"},{"location":"migration/wsc54/deprecations_removals/#constants","text":"wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::DELETE wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::GET wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::POST wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::PUT wcf\\system\\visitTracker\\VisitTracker::DEFAULT_LIFETIME ( WoltLab/WCF#4757 )","title":"Constants"},{"location":"migration/wsc54/deprecations_removals/#functions","text":"The global escapeString helper ( WoltLab/WCF#4506 )","title":"Functions"},{"location":"migration/wsc54/deprecations_removals/#options","text":"HTTP_SEND_X_FRAME_OPTIONS ( WoltLab/WCF#4474 ) ELASTICSEARCH_ALLOW_LEADING_WILDCARD WBB_MODULE_IGNORE_BOARDS (The option will be always on with WoltLab Suite Forum 5.5 and will be removed with a future version.) ENABLE_DESKTOP_NOTIFICATIONS ( WoltLab/WCF#4806 )","title":"Options"},{"location":"migration/wsc54/deprecations_removals/#javascript","text":"WCF.Message.Quote.Manager.markQuotesForRemoval() ( WoltLab/WCF#4452 ) WCF.Search.Message.KeywordList ( WoltLab/WCF#4402 ) SECURITY_TOKEN (use Core.getXsrfToken() , WoltLab/WCF#4523 ) WCF.Dropdown.Interactive.Handler ( WoltLab/WCF#4603 ) WCF.Dropdown.Interactive.Instance ( WoltLab/WCF#4603 ) WCF.User.Panel.Abstract ( WoltLab/WCF#4603 )","title":"JavaScript"},{"location":"migration/wsc54/deprecations_removals/#database-tables","text":"wcf1_package_compatibility ( WoltLab/WCF#4371 ) wcf1_package_update_compatibility ( WoltLab/WCF#4385 ) wcf1_package_update_optional ( WoltLab/WCF#4432 )","title":"Database Tables"},{"location":"migration/wsc54/deprecations_removals/#templates","text":"","title":"Templates"},{"location":"migration/wsc54/deprecations_removals/#template-modifiers","text":"|encodeJSON ( WoltLab/WCF#4645 )","title":"Template Modifiers"},{"location":"migration/wsc54/deprecations_removals/#template-events","text":"pageNavbarTop::navigationIcons search::queryOptions search::authorOptions search::periodOptions search::displayOptions search::generalFields","title":"Template Events"},{"location":"migration/wsc54/deprecations_removals/#miscellaneous","text":"The global option to set a specific style with a request parameter ( $_REQUEST['styleID'] ) is deprecated ( WoltLab/WCF@0c0111e946 )","title":"Miscellaneous"},{"location":"migration/wsc54/deprecations_removals/#removals","text":"","title":"Removals"},{"location":"migration/wsc54/deprecations_removals/#php_1","text":"","title":"PHP"},{"location":"migration/wsc54/deprecations_removals/#classes_1","text":"gallery\\util\\ExifUtil wbb\\action\\BoardQuickSearchAction wbb\\data\\thread\\NewsList wbb\\data\\thread\\News wcf\\action\\PollAction ( WoltLab/WCF#4662 ) wcf\\form\\RecaptchaForm ( WoltLab/WCF#4289 ) wcf\\system\\background\\job\\ElasticSearchIndexBackgroundJob wcf\\system\\cache\\builder\\TemplateListenerCacheBuilder ( WoltLab/WCF#4297 ) wcf\\system\\log\\modification\\ModificationLogHandler ( WoltLab/WCF#4340 ) wcf\\system\\recaptcha\\RecaptchaHandlerV2 ( WoltLab/WCF#4289 ) wcf\\system\\search\\SearchKeywordManager ( WoltLab/WCF#4313 ) The SCSS compiler\u2019s Leafo class aliases ( WoltLab/WCF#4343 , Migration Guide from 5.2 to 5.3 )","title":"Classes"},{"location":"migration/wsc54/deprecations_removals/#methods_1","text":"wbb\\data\\board\\BoardCache::getLabelGroups() wbb\\data\\post\\PostAction::jumpToExtended() (this method always threw a BadMethodCallException ) wbb\\data\\thread\\ThreadAction::countReplies() wbb\\data\\thread\\ThreadAction::validateCountReplies() wcf\\acp\\form\\UserGroupOptionForm::verifyPermissions() ( WoltLab/WCF#4312 ) wcf\\data\\conversation\\message\\ConversationMessageAction::jumpToExtended() ( WoltLab/com.woltlab.wcf.conversation#162 ) wcf\\data\\moderation\\queue\\ModerationQueueEditor::markAsDone() ( WoltLab/WCF#4317 ) wcf\\data\\tag\\TagCloudTag::getSize() ( WoltLab/WCF#4325 ) wcf\\data\\tag\\TagCloudTag::setSize() ( WoltLab/WCF#4325 ) wcf\\data\\user\\User::getSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::getSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::saveSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::validateGetSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::validateSaveSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\avatar\\DefaultAvatar::canCrop() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\DefaultAvatar::getCropImageTag() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\UserAvatar::canCrop() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\UserAvatar::getCropImageTag() ( WoltLab/WCF#4310 ) wcf\\system\\bbcode\\BBCodeHandler::setAllowedBBCodes() ( WoltLab/WCF#4319 ) wcf\\system\\bbcode\\BBCodeParser::validateBBCodes() ( WoltLab/WCF#4319 ) wcf\\system\\breadcrumb\\Breadcrumbs::add() ( WoltLab/WCF#4298 ) wcf\\system\\breadcrumb\\Breadcrumbs::remove() ( WoltLab/WCF#4298 ) wcf\\system\\breadcrumb\\Breadcrumbs::replace() ( WoltLab/WCF#4298 ) wcf\\system\\form\\builder\\IFormNode::create() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateAttribute() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateClass() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateId() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\IAttributeFormField::validateFieldAttribute() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\dependency\\IFormFieldDependency::create() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\validation\\IFormFieldValidator::validateId() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\message\\embedded\\object\\MessageEmbeddedObjectManager::parseTemporaryMessage() ( WoltLab/WCF#4299 ) wcf\\system\\package\\PackageArchive::getPhpRequirements() ( WoltLab/WCF#4311 ) wcf\\system\\search\\ISearchIndexManager::add() (Removal from Interface, see WoltLab/WCF#4508 ) wcf\\system\\search\\ISearchIndexManager::update() (Removal from Interface, see WoltLab/WCF#4508 ) wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::_add() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::_delete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::add() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::bulkAdd() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::bulkDelete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::delete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::update() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::add() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::update() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchEngine::parseSearchQuery()","title":"Methods"},{"location":"migration/wsc54/deprecations_removals/#properties_1","text":"wcf\\data\\category\\Category::$permissions ( WoltLab/WCF#4303 ) wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::$bulkTypeName","title":"Properties"},{"location":"migration/wsc54/deprecations_removals/#constants_1","text":"wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::HEAD wcf\\system\\tagging\\TagCloud::MAX_FONT_SIZE ( WoltLab/WCF#4325 ) wcf\\system\\tagging\\TagCloud::MIN_FONT_SIZE ( WoltLab/WCF#4325 )","title":"Constants"},{"location":"migration/wsc54/deprecations_removals/#options_1","text":"ENABLE_CENSORSHIP (always call Censorship::test() , see WoltLab/WCF#4567 ) MODULE_SYSTEM_RECAPTCHA ( WoltLab/WCF#4305 ) PROFILE_MAIL_USE_CAPTCHA ( WoltLab/WCF#4399 ) The may value for MAIL_SMTP_STARTTLS ( WoltLab/WCF#4398 ) SEARCH_USE_CAPTCHA (see WoltLab/WCF#4605 )","title":"Options"},{"location":"migration/wsc54/deprecations_removals/#files","text":"acp/dereferrer.php","title":"Files"},{"location":"migration/wsc54/deprecations_removals/#javascript_1","text":"Blog.Entry.QuoteHandler (use WoltLabSuite/Blog/Ui/Entry/Quote ) Calendar.Event.QuoteHandler (use WoltLabSuite/Calendar/Ui/Event/Quote ) WBB.Board.IgnoreBoards (use WoltLabSuite/Forum/Ui/Board/Ignore ) WBB.Board.MarkAllAsRead (use WoltLabSuite/Forum/Ui/Board/MarkAllAsRead ) WBB.Board.MarkAsRead (use WoltLabSuite/Forum/Ui/Board/MarkAsRead ) WBB.Post.QuoteHandler (use WoltLabSuite/Forum/Ui/Post/Quote ) WBB.Thread.LastPageHandler (use WoltLabSuite/Forum/Ui/Thread/LastPageHandler ) WBB.Thread.MarkAsRead (use WoltLabSuite/Forum/Ui/Thread/MarkAsRead ) WBB.Thread.SimilarThreads (use WoltLabSuite/Forum/Ui/Thread/SimilarThreads ) WBB.Thread.WatchedThreadList (use WoltLabSuite/Forum/Controller/Thread/WatchedList ) WCF.ACP.Style.ImageUpload ( WoltLab/WCF#4323 ) WCF.ColorPicker (see migration guide for WCF.ColorPicker ) WCF.Conversation.Message.QuoteHandler (use WoltLabSuite/Core/Conversation/Ui/Message/Quote , see WoltLab/com.woltlab.wcf.conversation#155 ) WCF.Like.js ( WoltLab/WCF#4300 ) WCF.Message.UserMention ( WoltLab/WCF#4324 ) WCF.Poll.Manager ( WoltLab/WCF#4662 ) WCF.UserPanel ( WoltLab/WCF#4316 ) WCF.User.Panel.Moderation ( WoltLab/WCF#4603 ) WCF.User.Panel.Notification ( WoltLab/WCF#4603 ) WCF.User.Panel.UserMenu ( WoltLab/WCF#4603 )","title":"JavaScript"},{"location":"migration/wsc54/deprecations_removals/#phrases","text":"wbb.search.boards.all wcf.global.form.error.greaterThan.javaScript ( WoltLab/WCF#4306 ) wcf.global.form.error.lessThan.javaScript ( WoltLab/WCF#4306 ) wcf.search.type.keywords wcf.acp.option.search_use_captcha wcf.search.query.description wcf.search.results.change wcf.search.results.description wcf.search.general wcf.search.query wcf.search.error.noMatches wcf.search.error.user.noMatches","title":"Phrases"},{"location":"migration/wsc54/deprecations_removals/#templates_1","text":"","title":"Templates"},{"location":"migration/wsc54/deprecations_removals/#templates_2","text":"searchResult","title":"Templates"},{"location":"migration/wsc54/deprecations_removals/#template-events_1","text":"search::tabMenuTabs search::sections tagSearch::tabMenuTabs tagSearch::sections","title":"Template Events"},{"location":"migration/wsc54/deprecations_removals/#miscellaneous_1","text":"Object specific VisitTracker lifetimes ( WoltLab/WCF#4757 )","title":"Miscellaneous"},{"location":"migration/wsc54/forum_subscriptions/","text":"Migrating from WSC 5.4 - WoltLab Suite Forum # Subscriptions # With WoltLab Suite Forum 5.5 we have introduced a new system for subscribing to threads and boards, which also offers the possibility to ignore threads and boards. You can learn more about this feature in our blog . The new system uses a separate mechanism to track the subscribed forums as well as the subscribed threads. The previously used object type com.woltlab.wcf.user.objectWatch is now discontinued, because the object watch system turned out to be too limited for the complex logic behind thread and forum subscriptions. Subscribe to Threads # Previously: 1 2 3 4 5 6 7 $action = new UserObjectWatchAction ([], 'subscribe' , [ 'data' => [ 'objectID' => $threadID , 'objectType' => 'com.woltlab.wbb.thread' , ] ]); $action -> executeAction (); Now: 1 2 3 4 ThreadStatusHandler :: saveSubscriptionStatus ( $threadID , ThreadStatusHandler :: SUBSCRIPTION_MODE_WATCHING ); Filter Ignored Threads # To filter ignored threads from a given ThreadList , you can use the method ThreadStatusHandler::addFilterForIgnoredThreads() to append the filter for ignored threads. The ViewableThreadList filters out ignored threads by default. Example: 1 2 3 4 5 6 7 8 9 $user = new User ( 123 ); $threadList = new ThreadList (); ThreadStatusHandler :: addFilterForIgnoredThreads ( $threadList , // This parameter specifies the target user. Defaults to the current user if the parameter // is omitted or `null`. $user ); $threadList -> readObjects (); Filter Ignored Users # Avoid issuing notifications to users that have ignored the target thread by filtering those out. 1 2 3 4 5 $userIDs = [ 1 , 2 , 3 ]; $users = ThreadStatusHandler :: filterIgnoredUserIDs ( $userIDs , $thread -> threadID ); Subscribe to Boards # Previously: 1 2 3 4 5 6 7 $action = new UserObjectWatchAction ([], 'subscribe' , [ 'data' => [ 'objectID' => $boardID , 'objectType' => 'com.woltlab.wbb.board' , ] ]); $action -> executeAction (); Now: 1 2 3 4 BoardStatusHandler :: saveSubscriptionStatus ( $boardID , ThreadStatusHandler :: SUBSCRIPTION_MODE_WATCHING ); Filter Ignored Boards # Similar to ignored threads you will also have to avoid issuing notifications for boards that a user has ignored. 1 2 3 4 5 $userIDs = [ 1 , 2 , 3 ]; $users = BoardStatusHandler :: filterIgnoredUserIDs ( $userIDs , $board -> boardID );","title":"Migrating from WSC 5.4 - WoltLab Suite Forum"},{"location":"migration/wsc54/forum_subscriptions/#migrating-from-wsc-54-woltlab-suite-forum","text":"","title":"Migrating from WSC 5.4 - WoltLab Suite Forum"},{"location":"migration/wsc54/forum_subscriptions/#subscriptions","text":"With WoltLab Suite Forum 5.5 we have introduced a new system for subscribing to threads and boards, which also offers the possibility to ignore threads and boards. You can learn more about this feature in our blog . The new system uses a separate mechanism to track the subscribed forums as well as the subscribed threads. The previously used object type com.woltlab.wcf.user.objectWatch is now discontinued, because the object watch system turned out to be too limited for the complex logic behind thread and forum subscriptions.","title":"Subscriptions"},{"location":"migration/wsc54/forum_subscriptions/#subscribe-to-threads","text":"Previously: 1 2 3 4 5 6 7 $action = new UserObjectWatchAction ([], 'subscribe' , [ 'data' => [ 'objectID' => $threadID , 'objectType' => 'com.woltlab.wbb.thread' , ] ]); $action -> executeAction (); Now: 1 2 3 4 ThreadStatusHandler :: saveSubscriptionStatus ( $threadID , ThreadStatusHandler :: SUBSCRIPTION_MODE_WATCHING );","title":"Subscribe to Threads"},{"location":"migration/wsc54/forum_subscriptions/#filter-ignored-threads","text":"To filter ignored threads from a given ThreadList , you can use the method ThreadStatusHandler::addFilterForIgnoredThreads() to append the filter for ignored threads. The ViewableThreadList filters out ignored threads by default. Example: 1 2 3 4 5 6 7 8 9 $user = new User ( 123 ); $threadList = new ThreadList (); ThreadStatusHandler :: addFilterForIgnoredThreads ( $threadList , // This parameter specifies the target user. Defaults to the current user if the parameter // is omitted or `null`. $user ); $threadList -> readObjects ();","title":"Filter Ignored Threads"},{"location":"migration/wsc54/forum_subscriptions/#filter-ignored-users","text":"Avoid issuing notifications to users that have ignored the target thread by filtering those out. 1 2 3 4 5 $userIDs = [ 1 , 2 , 3 ]; $users = ThreadStatusHandler :: filterIgnoredUserIDs ( $userIDs , $thread -> threadID );","title":"Filter Ignored Users"},{"location":"migration/wsc54/forum_subscriptions/#subscribe-to-boards","text":"Previously: 1 2 3 4 5 6 7 $action = new UserObjectWatchAction ([], 'subscribe' , [ 'data' => [ 'objectID' => $boardID , 'objectType' => 'com.woltlab.wbb.board' , ] ]); $action -> executeAction (); Now: 1 2 3 4 BoardStatusHandler :: saveSubscriptionStatus ( $boardID , ThreadStatusHandler :: SUBSCRIPTION_MODE_WATCHING );","title":"Subscribe to Boards"},{"location":"migration/wsc54/forum_subscriptions/#filter-ignored-boards","text":"Similar to ignored threads you will also have to avoid issuing notifications for boards that a user has ignored. 1 2 3 4 5 $userIDs = [ 1 , 2 , 3 ]; $users = BoardStatusHandler :: filterIgnoredUserIDs ( $userIDs , $board -> boardID );","title":"Filter Ignored Boards"},{"location":"migration/wsc54/javascript/","text":"Migrating from WSC 5.4 - TypeScript and JavaScript # Ajax.dboAction() # We have introduced a new Promise based API for the interaction with wcf\\data\\DatabaseObjectAction . It provides full IDE autocompletion support and transparent error handling, but is designed to be used with DatabaseObjectAction only. See the documentation for the new API and WoltLab/WCF#4585 for details. WCF.ColorPicker # We have replaced the old jQuery-based color picker WCF.ColorPicker with a more lightweight replacement WoltLabSuite/Core/Ui/Color/Picker , which uses the build-in input[type=color] field. To support transparency, which input[type=color] does not, we also added a slider to set the alpha value. WCF.ColorPicker has been adjusted to internally use WoltLabSuite/Core/Ui/Color/Picker and it has been deprecated. Be aware that the new color picker requires the following new phrases to be available in the TypeScript/JavaScript code: wcf.style.colorPicker.alpha , wcf.style.colorPicker.color , wcf.style.colorPicker.error.invalidColor , wcf.style.colorPicker.hexAlpha , wcf.style.colorPicker.new . See WoltLab/WCF#4353 for details. CodeMirror # The bundled version of CodeMirror was updated and should be loaded using the AMD loader going forward. See the third party libraries migration guide for details. New User Menu # The legacy implementation WCF.User.Panel.Abstract was based on jQuery and has now been retired in favor of a new lightweight implementation that provides a clean interface and improved accessibility. You are strongly encouraged to migrate your existing implementation to integrate with existing menus. Please use WoltLabSuite/Core/Ui/User/Menu/Data/ModerationQueue.ts as a template for your own implementation, it contains only strictly the code you will need. It makes use of the new Ajax.dboAction() (see above) for improved readability and flexibility. You must update your trigger button to include the role , tabindex and ARIA attributes! Please take a look at the links in pageHeaderUser.tpl to see these four attributes in action. See WoltLab/WCF#4603 for details.","title":"TypeScript and JavaScript"},{"location":"migration/wsc54/javascript/#migrating-from-wsc-54-typescript-and-javascript","text":"","title":"Migrating from WSC 5.4 - TypeScript and JavaScript"},{"location":"migration/wsc54/javascript/#ajaxdboaction","text":"We have introduced a new Promise based API for the interaction with wcf\\data\\DatabaseObjectAction . It provides full IDE autocompletion support and transparent error handling, but is designed to be used with DatabaseObjectAction only. See the documentation for the new API and WoltLab/WCF#4585 for details.","title":"Ajax.dboAction()"},{"location":"migration/wsc54/javascript/#wcfcolorpicker","text":"We have replaced the old jQuery-based color picker WCF.ColorPicker with a more lightweight replacement WoltLabSuite/Core/Ui/Color/Picker , which uses the build-in input[type=color] field. To support transparency, which input[type=color] does not, we also added a slider to set the alpha value. WCF.ColorPicker has been adjusted to internally use WoltLabSuite/Core/Ui/Color/Picker and it has been deprecated. Be aware that the new color picker requires the following new phrases to be available in the TypeScript/JavaScript code: wcf.style.colorPicker.alpha , wcf.style.colorPicker.color , wcf.style.colorPicker.error.invalidColor , wcf.style.colorPicker.hexAlpha , wcf.style.colorPicker.new . See WoltLab/WCF#4353 for details.","title":"WCF.ColorPicker"},{"location":"migration/wsc54/javascript/#codemirror","text":"The bundled version of CodeMirror was updated and should be loaded using the AMD loader going forward. See the third party libraries migration guide for details.","title":"CodeMirror"},{"location":"migration/wsc54/javascript/#new-user-menu","text":"The legacy implementation WCF.User.Panel.Abstract was based on jQuery and has now been retired in favor of a new lightweight implementation that provides a clean interface and improved accessibility. You are strongly encouraged to migrate your existing implementation to integrate with existing menus. Please use WoltLabSuite/Core/Ui/User/Menu/Data/ModerationQueue.ts as a template for your own implementation, it contains only strictly the code you will need. It makes use of the new Ajax.dboAction() (see above) for improved readability and flexibility. You must update your trigger button to include the role , tabindex and ARIA attributes! Please take a look at the links in pageHeaderUser.tpl to see these four attributes in action. See WoltLab/WCF#4603 for details.","title":"New User Menu"},{"location":"migration/wsc54/libraries/","text":"Migrating from WSC 5.4 - Third Party Libraries # Symfony PHP Polyfills # WoltLab Suite 5.5 ships with Symfony's PHP 7.3, 7.4, and 8.0 polyfills. These polyfills allow you to reliably use some of the PHP functions only available in PHP versions that are newer than the current minimum of PHP 7.2. Notable mentions are str_starts_with , str_ends_with , array_key_first , and array_key_last . Refer to the documentation within the symfony/polyfill repository for details. scssphp # scssphp was updated from version 1.4 to 1.10. If you interact with scssphp only by deploying .scss files, then you should not experience any breaking changes, except when the improved SCSS compatibility interprets your SCSS code differently. If you happen to directly use scssphp in your PHP code, you should be aware that scssphp deprecated the use of the compile() method, non-UTF-8 processing and also adjusted the handling of pure PHP values for variable handling. Refer to WoltLab/WCF#4345 and the scssphp releases for details. Emogrifier / CSS Inliner # The Emogrifier library was updated from version 5.0 to 6.0. CodeMirror # CodeMirror, the code editor we use for editing templates and SCSS, for example, has been updated to version 5.61.1 and we now also deliver all supported languages/modes. To properly support all languages/modes, CodeMirror is now loaded via the AMD module loader, which requires the original structure of the CodeMirror package, i.e. codemirror.js being in a lib folder. To preserve backward-compatibility, we also keep copies of codemirror.js and codemirror.css in version 5.61.1 directly in js/3rdParty/codemirror . These files are, however, considered deprecated and you should migrate to using require() (see codemirror ACP template). See WoltLab/WCF#4277 for details. Zend/ProgressBar # The old bundled version of Zend/ProgressBar was replaced by a current version of laminas-progressbar. Due to laminas-zendframework-bridge this update is a drop-in replacement. Existing code should continue to work as-is. It is recommended to cleanly migrate to laminas-progressbar to allow for a future removal of the bridge. Updating the use imports should be sufficient to switch to the laminas-progressbar. See WoltLab/WCF#4460 for details.","title":"Third Party Libraries"},{"location":"migration/wsc54/libraries/#migrating-from-wsc-54-third-party-libraries","text":"","title":"Migrating from WSC 5.4 - Third Party Libraries"},{"location":"migration/wsc54/libraries/#symfony-php-polyfills","text":"WoltLab Suite 5.5 ships with Symfony's PHP 7.3, 7.4, and 8.0 polyfills. These polyfills allow you to reliably use some of the PHP functions only available in PHP versions that are newer than the current minimum of PHP 7.2. Notable mentions are str_starts_with , str_ends_with , array_key_first , and array_key_last . Refer to the documentation within the symfony/polyfill repository for details.","title":"Symfony PHP Polyfills"},{"location":"migration/wsc54/libraries/#scssphp","text":"scssphp was updated from version 1.4 to 1.10. If you interact with scssphp only by deploying .scss files, then you should not experience any breaking changes, except when the improved SCSS compatibility interprets your SCSS code differently. If you happen to directly use scssphp in your PHP code, you should be aware that scssphp deprecated the use of the compile() method, non-UTF-8 processing and also adjusted the handling of pure PHP values for variable handling. Refer to WoltLab/WCF#4345 and the scssphp releases for details.","title":"scssphp"},{"location":"migration/wsc54/libraries/#emogrifier-css-inliner","text":"The Emogrifier library was updated from version 5.0 to 6.0.","title":"Emogrifier / CSS Inliner"},{"location":"migration/wsc54/libraries/#codemirror","text":"CodeMirror, the code editor we use for editing templates and SCSS, for example, has been updated to version 5.61.1 and we now also deliver all supported languages/modes. To properly support all languages/modes, CodeMirror is now loaded via the AMD module loader, which requires the original structure of the CodeMirror package, i.e. codemirror.js being in a lib folder. To preserve backward-compatibility, we also keep copies of codemirror.js and codemirror.css in version 5.61.1 directly in js/3rdParty/codemirror . These files are, however, considered deprecated and you should migrate to using require() (see codemirror ACP template). See WoltLab/WCF#4277 for details.","title":"CodeMirror"},{"location":"migration/wsc54/libraries/#zendprogressbar","text":"The old bundled version of Zend/ProgressBar was replaced by a current version of laminas-progressbar. Due to laminas-zendframework-bridge this update is a drop-in replacement. Existing code should continue to work as-is. It is recommended to cleanly migrate to laminas-progressbar to allow for a future removal of the bridge. Updating the use imports should be sufficient to switch to the laminas-progressbar. See WoltLab/WCF#4460 for details.","title":"Zend/ProgressBar"},{"location":"migration/wsc54/php/","text":"Migrating from WSC 5.4 - PHP # Initial PSR-7 support # WoltLab Suite will incrementally add support for object oriented request/response handling based off the PSR-7 and PSR-15 standards in the upcoming versions. WoltLab Suite 5.5 adds initial support by allowing to define the response using objects implementing the PSR-7 ResponseInterface . If a controller returns such a response object from its __run() method, this response will automatically emitted to the client. Any PSR-7 implementation is supported, but WoltLab Suite 5.5 ships with laminas-diactoros as the recommended \u201cbatteries included\u201d implementation of PSR-7. Support for PSR-7 requests and PSR-15 middlewares is expected to follow in future versions. See WoltLab/WCF#4437 for details. Recommended changes for WoltLab Suite 5.5 # With the current support in WoltLab Suite 5.5 it is recommended to migrate the *Action classes to make use of PSR-7 responses. Control and data flow is typically fairly simple in *Action classes with most requests ending up in either a redirect or a JSON response, commonly followed by a call to exit; . Experimental support for *Page and *Form is available. It is recommended to wait for a future version before migrating these types of controllers. Migrating Redirects # Previously: lib/action/ExampleRedirectAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\action ; use wcf\\system\\request\\LinkHandler ; use wcf\\util\\HeaderUtil ; final class ExampleRedirectAction extends AbstractAction { public function execute () { parent :: execute (); // Redirect to the landing page. HeaderUtil :: redirect ( LinkHandler :: getInstance () -> getLink () ); exit ; } } Now: lib/action/ExampleRedirectAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php namespace wcf\\action ; use Laminas\\Diactoros\\Response\\RedirectResponse ; use wcf\\system\\request\\LinkHandler ; final class ExampleRedirectAction extends AbstractAction { public function execute () { parent :: execute (); // Redirect to the landing page. return new RedirectResponse ( LinkHandler :: getInstance () -> getLink () ); } } Migrating JSON responses # Previously: lib/action/ExampleJsonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\action ; use wcf\\util\\JSON ; final class ExampleJsonAction extends AbstractAction { public function execute () { parent :: execute (); \\header ( 'Content-type: application/json; charset=UTF-8' ); echo JSON :: encode ([ 'foo' => 'bar' , ]); exit ; } } Now: lib/action/ExampleJsonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php namespace wcf\\action ; use Laminas\\Diactoros\\Response\\JsonResponse ; final class ExampleJsonAction extends AbstractAction { public function execute () { parent :: execute (); return new JsonResponse ([ 'foo' => 'bar' , ]); } } Events # Historically, events were tightly coupled with a single class, with the event object being an object of this class, expecting the event listener to consume public properties and method of the event object. The $parameters array was introduced due to limitations of this pattern, avoiding moving all the values that might be of interest to the event listener into the state of the object. Events were still tightly coupled with the class that fired the event and using the opaque parameters array prevented IDEs from assisting with autocompletion and typing. WoltLab Suite 5.5 introduces the concept of dedicated, reusable event classes. Any newly introduced event will receive a dedicated class, implementing the wcf\\system\\event\\IEvent interface. These event classes may be fired from multiple locations, making them reusable to convey that a conceptual action happened, instead of a specific class doing something. An example for using the new event system could be a user logging in: Instead of listening on a the login form being submitted and the Facebook login action successfully running, an event UserLoggedIn might be fired whenever a user logs in, no matter how the login is performed. Additionally, these dedicated event classes will benefit from full IDE support. All the relevant values may be stored as real properties on the event object. Event classes should not have an Event suffix and should be stored in an event namespace in a matching location. Thus, the UserLoggedIn example might have a FQCN of \\wcf\\system\\user\\authentication\\event\\UserLoggedIn . Event listeners for events implementing IEvent need to follow PSR-14 , i.e. they need to be callable. In practice, this means that the event listener class needs to implement __invoke() . No interface has to be implemented in this case. Previously: 1 2 3 4 5 $parameters = [ 'value' => \\random_int ( 1 , 1024 ), ]; EventHandler :: getInstance () -> fireAction ( $this , 'valueAvailable' , $parameters ); lib/system/event/listener/ValueDumpListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php namespace wcf\\system\\event\\listener ; use wcf\\form\\ValueForm ; final class ValueDumpListener implements IParameterizedEventListener { /** * @inheritDoc * @param ValueForm $eventObj */ public function execute ( $eventObj , $className , $eventName , array & $parameters ) { var_dump ( $parameters [ 'value' ]); } } Now: 1 EventHandler::getInstance()->fire(new ValueAvailable(\\random_int(1, 1024))); lib/system/foo/event/ValueAvailable.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <? php namespace wcf\\system\\foo\\event ; use wcf\\system\\event\\IEvent ; final class ValueAvailable implements IEvent { /** * @var int */ private $value ; public function __construct ( int $value ) { $this -> value = $value ; } public function getValue () : int { return $this -> value ; } } lib/system/event/listener/ValueDumpListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\foo\\event\\ValueAvailable ; final class ValueDumpListener { public function __invoke ( ValueAvailable $event ) { var_dump ( $event -> getValue ()); } } See WoltLab/WCF#4000 and WoltLab/WCF#4265 for details. Authentication # The UserLoggedIn event was added. You should fire this event if you implement a custom login process (e.g. when adding additional external authentication providers). Example: 1 2 3 EventHandler :: getInstance () -> fire ( new UserLoggedIn ( $user ) ); See WoltLab/WCF#4356 for details. Embedded Objects in Comments # WoltLab/WCF#4275 added support for embedded objects like mentions for comments and comment responses. To properly render embedded objects whenever you are using comments in your packages, you have to use ViewableCommentList / ViewableCommentResponseList in these places or ViewableCommentRuntimeCache / ViewableCommentResponseRuntimeCache . While these runtime caches are only available since version 5.5, the viewable list classes have always been available so that changing CommentList to ViewableCommentList , for example, is a backwards-compatible change. Emails # Mailbox # The Mailbox and UserMailbox classes no longer store the passed Language and User objects, but the respective ID instead. This change reduces the size of the serialized email when stored in the background queue. If you inherit from the Mailbox or UserMailbox classes, you might experience issues if you directly access the $this->language or $this->user properties. Adjust your class to use composition instead of inheritance if possible. Use the getLanguage() or getUser() getters if using composition is not possible. See WoltLab/WCF#4389 for details. SMTP # The SmtpEmailTransport no longer supports a value of may for the $starttls property. Using the may value is unsafe as it allows for undetected MITM attacks. The use of encrypt is recommended, unless it is certain that the SMTP server does not support TLS. See WoltLab/WCF#4398 for details. Search # Search Form # After the overhaul of the search form, search providers are no longer bound to SearchForm and SearchResultPage . The interface ISearchObjectType and the abstract implementation AbstractSearchableObjectType have been replaced by ISearchProvider and AbstractSearchProvider . Please use ArticleSearch as a template for your own implementation See WoltLab/WCF#4605 for details. Exceptions # A new wcf\\system\\search\\exception\\SearchFailed exception was added. This exception should be thrown when executing the search query fails for (mostly) temporary reasons, such as a network partition to a remote service. It is not meant as a blanket exception to wrap everything. For example it must not be returned obvious programming errors, such as an access to an undefined variable ( ErrorException ). Catching the SearchFailed exception allows consuming code to gracefully handle search requests that are not essential for proceeding, without silencing other types of error. See WoltLab/WCF#4476 and WoltLab/WCF#4483 for details. Package Installation Plugins # Database # WoltLab Suite 5.5 changes the factory classes for common configurations of database columns within the PHP-based DDL API to contain a private constructor, preventing object creation. This change affects the following classes: DefaultFalseBooleanDatabaseTableColumn DefaultTrueBooleanDatabaseTableColumn NotNullInt10DatabaseTableColumn NotNullVarchar191DatabaseTableColumn NotNullVarchar255DatabaseTableColumn ObjectIdDatabaseTableColumn DatabaseTablePrimaryIndex The static create() method never returned an object of the factory class, but instead in object of the base type (e.g. IntDatabaseTableColumn for NotNullInt10DatabaseTableColumn ). Constructing an object of these factory classes is considered a bug, as the class name implies a specific column configuration, that might or might not hold if the object is modified afterwards. See WoltLab/WCF#4564 for details. WoltLab Suite 5.5 adds the IDefaultValueDatabaseTableColumn interface which is used to check whether specifying a default value is legal. For backwards compatibility this interface is implemented by AbstractDatabaseTableColumn . You should explicitly add this interface to custom table column type classes to avoid breakage if the interface is removed from AbstractDatabaseTableColumn in a future version. Likewise you should explicitly check for the interface before attempting to access the methods related to the default value of a column. See WoltLab/WCF#4733 for details. File Deletion # Three new package installation plugins have been added to delete ACP templates with acpTemplateDelete , files with fileDelete , and templates with templateDelete . Language # WoltLab/WCF#4261 has added support for deleting existing phrases with the language package installation plugin. The current structure of the language XML files language/en.xml 1 2 3 4 5 6 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </language> is deprecated and should be replaced with the new structure with an explicit <import> element like in the other package installation plugins: language/en.xml 1 2 3 4 5 6 7 8 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <import> <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </import> </language> Additionally, to now also support deleting phrases with this package installation plugin, support for a <delete> element has been added: language/en.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <import> <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </import> <delete> <item name= \"wcf.foo.barrr\" /> </delete> </language> Note that when deleting phrases, the category does not have to be specified because phrase identifiers are unique globally. Mixing the old structure and the new structure is not supported and will result in an error message during the import! Board and Thread Subscriptions # WoltLab Suite Forum 5.5 updates the subscription logic for boards and threads to properly support the ignoring of threads. See the dedicated migration guide for details. Miscellaneous Changes # View Counters # With WoltLab Suite 5.5 it is expected that view/download counters do not increase for disabled content. See WoltLab/WCF#4374 for details. Form Builder # ValueIntervalFormFieldDependency ColorFormField MultipleBoardSelectionFormField","title":"PHP API"},{"location":"migration/wsc54/php/#migrating-from-wsc-54-php","text":"","title":"Migrating from WSC 5.4 - PHP"},{"location":"migration/wsc54/php/#initial-psr-7-support","text":"WoltLab Suite will incrementally add support for object oriented request/response handling based off the PSR-7 and PSR-15 standards in the upcoming versions. WoltLab Suite 5.5 adds initial support by allowing to define the response using objects implementing the PSR-7 ResponseInterface . If a controller returns such a response object from its __run() method, this response will automatically emitted to the client. Any PSR-7 implementation is supported, but WoltLab Suite 5.5 ships with laminas-diactoros as the recommended \u201cbatteries included\u201d implementation of PSR-7. Support for PSR-7 requests and PSR-15 middlewares is expected to follow in future versions. See WoltLab/WCF#4437 for details.","title":"Initial PSR-7 support"},{"location":"migration/wsc54/php/#recommended-changes-for-woltlab-suite-55","text":"With the current support in WoltLab Suite 5.5 it is recommended to migrate the *Action classes to make use of PSR-7 responses. Control and data flow is typically fairly simple in *Action classes with most requests ending up in either a redirect or a JSON response, commonly followed by a call to exit; . Experimental support for *Page and *Form is available. It is recommended to wait for a future version before migrating these types of controllers.","title":"Recommended changes for WoltLab Suite 5.5"},{"location":"migration/wsc54/php/#migrating-redirects","text":"Previously: lib/action/ExampleRedirectAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\action ; use wcf\\system\\request\\LinkHandler ; use wcf\\util\\HeaderUtil ; final class ExampleRedirectAction extends AbstractAction { public function execute () { parent :: execute (); // Redirect to the landing page. HeaderUtil :: redirect ( LinkHandler :: getInstance () -> getLink () ); exit ; } } Now: lib/action/ExampleRedirectAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php namespace wcf\\action ; use Laminas\\Diactoros\\Response\\RedirectResponse ; use wcf\\system\\request\\LinkHandler ; final class ExampleRedirectAction extends AbstractAction { public function execute () { parent :: execute (); // Redirect to the landing page. return new RedirectResponse ( LinkHandler :: getInstance () -> getLink () ); } }","title":"Migrating Redirects"},{"location":"migration/wsc54/php/#migrating-json-responses","text":"Previously: lib/action/ExampleJsonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\action ; use wcf\\util\\JSON ; final class ExampleJsonAction extends AbstractAction { public function execute () { parent :: execute (); \\header ( 'Content-type: application/json; charset=UTF-8' ); echo JSON :: encode ([ 'foo' => 'bar' , ]); exit ; } } Now: lib/action/ExampleJsonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php namespace wcf\\action ; use Laminas\\Diactoros\\Response\\JsonResponse ; final class ExampleJsonAction extends AbstractAction { public function execute () { parent :: execute (); return new JsonResponse ([ 'foo' => 'bar' , ]); } }","title":"Migrating JSON responses"},{"location":"migration/wsc54/php/#events","text":"Historically, events were tightly coupled with a single class, with the event object being an object of this class, expecting the event listener to consume public properties and method of the event object. The $parameters array was introduced due to limitations of this pattern, avoiding moving all the values that might be of interest to the event listener into the state of the object. Events were still tightly coupled with the class that fired the event and using the opaque parameters array prevented IDEs from assisting with autocompletion and typing. WoltLab Suite 5.5 introduces the concept of dedicated, reusable event classes. Any newly introduced event will receive a dedicated class, implementing the wcf\\system\\event\\IEvent interface. These event classes may be fired from multiple locations, making them reusable to convey that a conceptual action happened, instead of a specific class doing something. An example for using the new event system could be a user logging in: Instead of listening on a the login form being submitted and the Facebook login action successfully running, an event UserLoggedIn might be fired whenever a user logs in, no matter how the login is performed. Additionally, these dedicated event classes will benefit from full IDE support. All the relevant values may be stored as real properties on the event object. Event classes should not have an Event suffix and should be stored in an event namespace in a matching location. Thus, the UserLoggedIn example might have a FQCN of \\wcf\\system\\user\\authentication\\event\\UserLoggedIn . Event listeners for events implementing IEvent need to follow PSR-14 , i.e. they need to be callable. In practice, this means that the event listener class needs to implement __invoke() . No interface has to be implemented in this case. Previously: 1 2 3 4 5 $parameters = [ 'value' => \\random_int ( 1 , 1024 ), ]; EventHandler :: getInstance () -> fireAction ( $this , 'valueAvailable' , $parameters ); lib/system/event/listener/ValueDumpListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php namespace wcf\\system\\event\\listener ; use wcf\\form\\ValueForm ; final class ValueDumpListener implements IParameterizedEventListener { /** * @inheritDoc * @param ValueForm $eventObj */ public function execute ( $eventObj , $className , $eventName , array & $parameters ) { var_dump ( $parameters [ 'value' ]); } } Now: 1 EventHandler::getInstance()->fire(new ValueAvailable(\\random_int(1, 1024))); lib/system/foo/event/ValueAvailable.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <? php namespace wcf\\system\\foo\\event ; use wcf\\system\\event\\IEvent ; final class ValueAvailable implements IEvent { /** * @var int */ private $value ; public function __construct ( int $value ) { $this -> value = $value ; } public function getValue () : int { return $this -> value ; } } lib/system/event/listener/ValueDumpListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\foo\\event\\ValueAvailable ; final class ValueDumpListener { public function __invoke ( ValueAvailable $event ) { var_dump ( $event -> getValue ()); } } See WoltLab/WCF#4000 and WoltLab/WCF#4265 for details.","title":"Events"},{"location":"migration/wsc54/php/#authentication","text":"The UserLoggedIn event was added. You should fire this event if you implement a custom login process (e.g. when adding additional external authentication providers). Example: 1 2 3 EventHandler :: getInstance () -> fire ( new UserLoggedIn ( $user ) ); See WoltLab/WCF#4356 for details.","title":"Authentication"},{"location":"migration/wsc54/php/#embedded-objects-in-comments","text":"WoltLab/WCF#4275 added support for embedded objects like mentions for comments and comment responses. To properly render embedded objects whenever you are using comments in your packages, you have to use ViewableCommentList / ViewableCommentResponseList in these places or ViewableCommentRuntimeCache / ViewableCommentResponseRuntimeCache . While these runtime caches are only available since version 5.5, the viewable list classes have always been available so that changing CommentList to ViewableCommentList , for example, is a backwards-compatible change.","title":"Embedded Objects in Comments"},{"location":"migration/wsc54/php/#emails","text":"","title":"Emails"},{"location":"migration/wsc54/php/#mailbox","text":"The Mailbox and UserMailbox classes no longer store the passed Language and User objects, but the respective ID instead. This change reduces the size of the serialized email when stored in the background queue. If you inherit from the Mailbox or UserMailbox classes, you might experience issues if you directly access the $this->language or $this->user properties. Adjust your class to use composition instead of inheritance if possible. Use the getLanguage() or getUser() getters if using composition is not possible. See WoltLab/WCF#4389 for details.","title":"Mailbox"},{"location":"migration/wsc54/php/#smtp","text":"The SmtpEmailTransport no longer supports a value of may for the $starttls property. Using the may value is unsafe as it allows for undetected MITM attacks. The use of encrypt is recommended, unless it is certain that the SMTP server does not support TLS. See WoltLab/WCF#4398 for details.","title":"SMTP"},{"location":"migration/wsc54/php/#search","text":"","title":"Search"},{"location":"migration/wsc54/php/#search-form","text":"After the overhaul of the search form, search providers are no longer bound to SearchForm and SearchResultPage . The interface ISearchObjectType and the abstract implementation AbstractSearchableObjectType have been replaced by ISearchProvider and AbstractSearchProvider . Please use ArticleSearch as a template for your own implementation See WoltLab/WCF#4605 for details.","title":"Search Form"},{"location":"migration/wsc54/php/#exceptions","text":"A new wcf\\system\\search\\exception\\SearchFailed exception was added. This exception should be thrown when executing the search query fails for (mostly) temporary reasons, such as a network partition to a remote service. It is not meant as a blanket exception to wrap everything. For example it must not be returned obvious programming errors, such as an access to an undefined variable ( ErrorException ). Catching the SearchFailed exception allows consuming code to gracefully handle search requests that are not essential for proceeding, without silencing other types of error. See WoltLab/WCF#4476 and WoltLab/WCF#4483 for details.","title":"Exceptions"},{"location":"migration/wsc54/php/#package-installation-plugins","text":"","title":"Package Installation Plugins"},{"location":"migration/wsc54/php/#database","text":"WoltLab Suite 5.5 changes the factory classes for common configurations of database columns within the PHP-based DDL API to contain a private constructor, preventing object creation. This change affects the following classes: DefaultFalseBooleanDatabaseTableColumn DefaultTrueBooleanDatabaseTableColumn NotNullInt10DatabaseTableColumn NotNullVarchar191DatabaseTableColumn NotNullVarchar255DatabaseTableColumn ObjectIdDatabaseTableColumn DatabaseTablePrimaryIndex The static create() method never returned an object of the factory class, but instead in object of the base type (e.g. IntDatabaseTableColumn for NotNullInt10DatabaseTableColumn ). Constructing an object of these factory classes is considered a bug, as the class name implies a specific column configuration, that might or might not hold if the object is modified afterwards. See WoltLab/WCF#4564 for details. WoltLab Suite 5.5 adds the IDefaultValueDatabaseTableColumn interface which is used to check whether specifying a default value is legal. For backwards compatibility this interface is implemented by AbstractDatabaseTableColumn . You should explicitly add this interface to custom table column type classes to avoid breakage if the interface is removed from AbstractDatabaseTableColumn in a future version. Likewise you should explicitly check for the interface before attempting to access the methods related to the default value of a column. See WoltLab/WCF#4733 for details.","title":"Database"},{"location":"migration/wsc54/php/#file-deletion","text":"Three new package installation plugins have been added to delete ACP templates with acpTemplateDelete , files with fileDelete , and templates with templateDelete .","title":"File Deletion"},{"location":"migration/wsc54/php/#language","text":"WoltLab/WCF#4261 has added support for deleting existing phrases with the language package installation plugin. The current structure of the language XML files language/en.xml 1 2 3 4 5 6 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </language> is deprecated and should be replaced with the new structure with an explicit <import> element like in the other package installation plugins: language/en.xml 1 2 3 4 5 6 7 8 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <import> <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </import> </language> Additionally, to now also support deleting phrases with this package installation plugin, support for a <delete> element has been added: language/en.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <import> <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </import> <delete> <item name= \"wcf.foo.barrr\" /> </delete> </language> Note that when deleting phrases, the category does not have to be specified because phrase identifiers are unique globally. Mixing the old structure and the new structure is not supported and will result in an error message during the import!","title":"Language"},{"location":"migration/wsc54/php/#board-and-thread-subscriptions","text":"WoltLab Suite Forum 5.5 updates the subscription logic for boards and threads to properly support the ignoring of threads. See the dedicated migration guide for details.","title":"Board and Thread Subscriptions"},{"location":"migration/wsc54/php/#miscellaneous-changes","text":"","title":"Miscellaneous Changes"},{"location":"migration/wsc54/php/#view-counters","text":"With WoltLab Suite 5.5 it is expected that view/download counters do not increase for disabled content. See WoltLab/WCF#4374 for details.","title":"View Counters"},{"location":"migration/wsc54/php/#form-builder","text":"ValueIntervalFormFieldDependency ColorFormField MultipleBoardSelectionFormField","title":"Form Builder"},{"location":"migration/wsc54/templates/","text":"Migrating from WSC 5.4 - Templates # Content Interaction Buttons # Content interactions buttons are a new way to display action buttons at the top of the page. They are intended to replace the icons in pageNavigationIcons for better accessibility while reducing the amount of buttons in contentHeaderNavigation . As a rule of thumb, there should be at most only one button in contentHeaderNavigation (primary action on this page) and three buttons in contentInteractionButtons (important actions on this page). Use contentInteractionDropdownItems for all other buttons. The template contentInteraction is included in the header and the corresponding placeholders are thus available on every page. See WoltLab/WCF#4315 for details. Phrase Modifier # The |language modifier was added to allow the piping of the phrase through other functions. This has some unwanted side effects when used with plain strings that should not support variable interpolation. Another difference to {lang} is the evaluation on runtime rather than at compile time, allowing the phrase to be taken from a variable instead. We introduces the new modifier |phrase as a thin wrapper around \\wcf\\system::WCF::getLanguage()->get() . Use |phrase instead of |language unless you want to explicitly allow template scripting on a variable's output. See WoltLab/WCF#4657 for details.","title":"Templates"},{"location":"migration/wsc54/templates/#migrating-from-wsc-54-templates","text":"","title":"Migrating from WSC 5.4 - Templates"},{"location":"migration/wsc54/templates/#content-interaction-buttons","text":"Content interactions buttons are a new way to display action buttons at the top of the page. They are intended to replace the icons in pageNavigationIcons for better accessibility while reducing the amount of buttons in contentHeaderNavigation . As a rule of thumb, there should be at most only one button in contentHeaderNavigation (primary action on this page) and three buttons in contentInteractionButtons (important actions on this page). Use contentInteractionDropdownItems for all other buttons. The template contentInteraction is included in the header and the corresponding placeholders are thus available on every page. See WoltLab/WCF#4315 for details.","title":"Content Interaction Buttons"},{"location":"migration/wsc54/templates/#phrase-modifier","text":"The |language modifier was added to allow the piping of the phrase through other functions. This has some unwanted side effects when used with plain strings that should not support variable interpolation. Another difference to {lang} is the evaluation on runtime rather than at compile time, allowing the phrase to be taken from a variable instead. We introduces the new modifier |phrase as a thin wrapper around \\wcf\\system::WCF::getLanguage()->get() . Use |phrase instead of |language unless you want to explicitly allow template scripting on a variable's output. See WoltLab/WCF#4657 for details.","title":"Phrase Modifier"},{"location":"package/database-php-api/","text":"Database PHP API # While the sql package installation plugin supports adding and removing tables, columns, and indices, it is not able to handle cases where the added table, column, or index already exist. We have added a new PHP-based API to manipulate the database scheme which can be used in combination with the script package installation plugin that skips parts that already exist: 1 2 3 4 5 6 7 8 9 10 $tables = [ // list of `DatabaseTable` objects ]; ( new DatabaseTableChangeProcessor ( /** @var ScriptPackageInstallationPlugin $this */ $this -> installation -> getPackage (), $tables , WCF :: getDB () -> getEditor ()) ) -> process (); All of the relevant components can be found in the wcf\\system\\database\\table namespace. With WoltLab Suite 5.4, you should use the new database package installation plugin for which you only have to return the array of affected database tables: 1 2 3 return [ // list of `DatabaseTable` objects ]; Database Tables # There are two classes representing database tables: DatabaseTable and PartialDatabaseTable . If a new table should be created, use DatabaseTable . In all other cases, PartialDatabaseTable should be used as it provides an additional save-guard against accidentally creating a new table by having a typo in the table name: If the tables does not already exist, a table represented by PartialDatabaseTable will cause an exception (while a DatabaseTable table will simply be created). To create a table, a DatabaseTable object with the table's name as to be created and table's columns, foreign keys and indices have to be specified: 1 2 3 4 5 6 7 8 9 10 DatabaseTable :: create ( 'foo1_bar' ) -> columns ([ // columns ]) -> foreignKeys ([ // foreign keys ]) -> indices ([ // indices ]) To update a table, the same code as above can be used, except for PartialDatabaseTable being used instead of DatabaseTable . To drop a table, only the drop() method has to be called: 1 2 PartialDatabaseTable :: create ( 'foo1_bar' ) -> drop () Columns # To represent a column of a database table, you have to create an instance of the relevant column class found in the wcf\\system\\database\\table\\column namespace. Such instances are created similarly to database table objects using the create() factory method and passing the column name as the parameter. Every column type supports the following methods: defaultValue($defaultValue) sets the default value of the column (default: none). drop() to drop the column. notNull($notNull = true) sets if the value of the column can be NULL (default: false ). Depending on the specific column class implementing additional interfaces, the following methods are also available: IAutoIncrementDatabaseTableColumn::autoIncrement($autoIncrement = true) sets if the value of the colum is auto-incremented. IDecimalsDatabaseTableColumn::decimals($decimals) sets the number of decimals the column supports. IEnumDatabaseTableColumn::enumValues(array $values) sets the predetermined set of valid values of the column. ILengthDatabaseTableColumn::length($length) sets the (maximum) length of the column. Additionally, there are some additionally classes of commonly used columns with specific properties: DefaultFalseBooleanDatabaseTableColumn (a tinyint column with length 1 , default value 0 and whose values cannot be null ) DefaultTrueBooleanDatabaseTableColumn (a tinyint column with length 0 , default value 0 and whose values cannot be null ) NotNullInt10DatabaseTableColumn (a int column with length 10 and whose values cannot be null ) NotNullVarchar191DatabaseTableColumn (a varchar column with length 191 and whose values cannot be null ) NotNullVarchar255DatabaseTableColumn (a varchar column with length 255 and whose values cannot be null ) ObjectIdDatabaseTableColumn (a int column with length 10 , whose values cannot be null , and whose values are auto-incremented) Examples: 1 2 3 4 5 6 7 DefaultFalseBooleanDatabaseTableColumn :: create ( 'isDisabled' ) NotNullInt10DatabaseTableColumn :: create ( 'fooTypeID' ) SmallintDatabaseTableColumn :: create ( 'bar' ) -> length ( 5 ) -> notNull () Foreign Keys # Foreign keys are represented by DatabaseTableForeignKey objects: 1 2 3 4 5 DatabaseTableForeignKey :: create () -> columns ([ 'fooID' ]) -> referencedTable ( 'wcf1_foo' ) -> referencedColumns ([ 'fooID' ]) -> onDelete ( 'CASCADE' ) The supported actions for onDelete() and onUpdate() are CASCADE , NO ACTION , and SET NULL . To drop a foreign key, all of the relevant data to create the foreign key has to be present and the drop() method has to be called. DatabaseTableForeignKey::create() also supports the foreign key name as a parameter. If it is not present, DatabaseTable::foreignKeys() will automatically set one based on the foreign key's data. Indices # Indices are represented by DatabaseTableIndex objects: 1 2 3 DatabaseTableIndex :: create () -> type ( DatabaseTableIndex :: UNIQUE_TYPE ) -> columns ([ 'fooID' ]) There are four different types: DatabaseTableIndex::DEFAULT_TYPE (default), DatabaseTableIndex::PRIMARY_TYPE , DatabaseTableIndex::UNIQUE_TYPE , and DatabaseTableIndex::FULLTEXT_TYPE . For primary keys, there is also the DatabaseTablePrimaryIndex class which automatically sets the type to DatabaseTableIndex::PRIMARY_TYPE . To drop a index, all of the relevant data to create the index has to be present and the drop() method has to be called. DatabaseTableIndex::create() also supports the index name as a parameter. If it is not present, DatabaseTable::indices() will automatically set one based on the index data.","title":"Database PHP API"},{"location":"package/database-php-api/#database-php-api","text":"While the sql package installation plugin supports adding and removing tables, columns, and indices, it is not able to handle cases where the added table, column, or index already exist. We have added a new PHP-based API to manipulate the database scheme which can be used in combination with the script package installation plugin that skips parts that already exist: 1 2 3 4 5 6 7 8 9 10 $tables = [ // list of `DatabaseTable` objects ]; ( new DatabaseTableChangeProcessor ( /** @var ScriptPackageInstallationPlugin $this */ $this -> installation -> getPackage (), $tables , WCF :: getDB () -> getEditor ()) ) -> process (); All of the relevant components can be found in the wcf\\system\\database\\table namespace. With WoltLab Suite 5.4, you should use the new database package installation plugin for which you only have to return the array of affected database tables: 1 2 3 return [ // list of `DatabaseTable` objects ];","title":"Database PHP API"},{"location":"package/database-php-api/#database-tables","text":"There are two classes representing database tables: DatabaseTable and PartialDatabaseTable . If a new table should be created, use DatabaseTable . In all other cases, PartialDatabaseTable should be used as it provides an additional save-guard against accidentally creating a new table by having a typo in the table name: If the tables does not already exist, a table represented by PartialDatabaseTable will cause an exception (while a DatabaseTable table will simply be created). To create a table, a DatabaseTable object with the table's name as to be created and table's columns, foreign keys and indices have to be specified: 1 2 3 4 5 6 7 8 9 10 DatabaseTable :: create ( 'foo1_bar' ) -> columns ([ // columns ]) -> foreignKeys ([ // foreign keys ]) -> indices ([ // indices ]) To update a table, the same code as above can be used, except for PartialDatabaseTable being used instead of DatabaseTable . To drop a table, only the drop() method has to be called: 1 2 PartialDatabaseTable :: create ( 'foo1_bar' ) -> drop ()","title":"Database Tables"},{"location":"package/database-php-api/#columns","text":"To represent a column of a database table, you have to create an instance of the relevant column class found in the wcf\\system\\database\\table\\column namespace. Such instances are created similarly to database table objects using the create() factory method and passing the column name as the parameter. Every column type supports the following methods: defaultValue($defaultValue) sets the default value of the column (default: none). drop() to drop the column. notNull($notNull = true) sets if the value of the column can be NULL (default: false ). Depending on the specific column class implementing additional interfaces, the following methods are also available: IAutoIncrementDatabaseTableColumn::autoIncrement($autoIncrement = true) sets if the value of the colum is auto-incremented. IDecimalsDatabaseTableColumn::decimals($decimals) sets the number of decimals the column supports. IEnumDatabaseTableColumn::enumValues(array $values) sets the predetermined set of valid values of the column. ILengthDatabaseTableColumn::length($length) sets the (maximum) length of the column. Additionally, there are some additionally classes of commonly used columns with specific properties: DefaultFalseBooleanDatabaseTableColumn (a tinyint column with length 1 , default value 0 and whose values cannot be null ) DefaultTrueBooleanDatabaseTableColumn (a tinyint column with length 0 , default value 0 and whose values cannot be null ) NotNullInt10DatabaseTableColumn (a int column with length 10 and whose values cannot be null ) NotNullVarchar191DatabaseTableColumn (a varchar column with length 191 and whose values cannot be null ) NotNullVarchar255DatabaseTableColumn (a varchar column with length 255 and whose values cannot be null ) ObjectIdDatabaseTableColumn (a int column with length 10 , whose values cannot be null , and whose values are auto-incremented) Examples: 1 2 3 4 5 6 7 DefaultFalseBooleanDatabaseTableColumn :: create ( 'isDisabled' ) NotNullInt10DatabaseTableColumn :: create ( 'fooTypeID' ) SmallintDatabaseTableColumn :: create ( 'bar' ) -> length ( 5 ) -> notNull ()","title":"Columns"},{"location":"package/database-php-api/#foreign-keys","text":"Foreign keys are represented by DatabaseTableForeignKey objects: 1 2 3 4 5 DatabaseTableForeignKey :: create () -> columns ([ 'fooID' ]) -> referencedTable ( 'wcf1_foo' ) -> referencedColumns ([ 'fooID' ]) -> onDelete ( 'CASCADE' ) The supported actions for onDelete() and onUpdate() are CASCADE , NO ACTION , and SET NULL . To drop a foreign key, all of the relevant data to create the foreign key has to be present and the drop() method has to be called. DatabaseTableForeignKey::create() also supports the foreign key name as a parameter. If it is not present, DatabaseTable::foreignKeys() will automatically set one based on the foreign key's data.","title":"Foreign Keys"},{"location":"package/database-php-api/#indices","text":"Indices are represented by DatabaseTableIndex objects: 1 2 3 DatabaseTableIndex :: create () -> type ( DatabaseTableIndex :: UNIQUE_TYPE ) -> columns ([ 'fooID' ]) There are four different types: DatabaseTableIndex::DEFAULT_TYPE (default), DatabaseTableIndex::PRIMARY_TYPE , DatabaseTableIndex::UNIQUE_TYPE , and DatabaseTableIndex::FULLTEXT_TYPE . For primary keys, there is also the DatabaseTablePrimaryIndex class which automatically sets the type to DatabaseTableIndex::PRIMARY_TYPE . To drop a index, all of the relevant data to create the index has to be present and the drop() method has to be called. DatabaseTableIndex::create() also supports the index name as a parameter. If it is not present, DatabaseTable::indices() will automatically set one based on the index data.","title":"Indices"},{"location":"package/package-xml/","text":"package.xml # The package.xml is the core component of every package. It provides the meta data (e.g. package name, description, author) and the instruction set for a new installation and/or updating from a previous version. Example # package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.example.package\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/package.xsd\" > <packageinformation> <packagename> Simple Package </packagename> <packagedescription> A simple package to demonstrate the package system of WoltLab Suite Core </packagedescription> <version> 1.0.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> YOUR NAME </author> <authorurl> http://www.example.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"template\" > templates.tar </instruction> </instructions> </package> Elements # <package> # The root node of every package.xml it contains the reference to the namespace and the location of the XML Schema Definition (XSD). The attribute name is the most important part, it holds the unique package identifier and is mandatory. It is based upon your domain name and the package name of your choice. For example WoltLab Suite Forum (formerly know an WoltLab Burning Board and usually abbreviated as wbb ) is created by WoltLab which owns the domain woltlab.com . The resulting package identifier is com.woltlab.wbb ( <tld>.<domain>.<packageName> ). <packageinformation> # Holds the entire meta data of the package. <packagename> # This is the actual package name displayed to the end user, this can be anything you want, try to keep it short. It supports the attribute languagecode which allows you to provide the package name in different languages, please be aware that if it is not present, en (English) is assumed: 1 2 3 4 <packageinformation> <packagename> Simple Package </packagename> <packagename languagecode= \"de\" > Einfaches Paket </packagename> </packageinformation> <packagedescription> # Brief summary of the package, use it to explain what it does since the package name might not always be clear enough. The attribute languagecode is available here too, please reference to <packagename> for details. <version> # The package's version number, this is a string consisting of three numbers separated with a dot and optionally followed by a keyword (must be followed with another number). The possible keywords are: Alpha/dev (both is regarded to be the same) Beta RC (release candidate) pl (patch level) Valid examples: 1.0.0 1.12.13 Alpha 19 7.0.0 pl 3 Invalid examples: 1.0.0 Beta (keyword Beta must be followed by a number) 2.0 RC 3 (version number must consists of 3 blocks of numbers) 1.2.3 dev 4.5 (4.5 is not an integer, 4 or 5 would be valid but not the fraction) <date> # Must be a valid ISO 8601 date, e.g. 2013-12-27 . <authorinformation> # Holds meta data regarding the package's author. <author> # Can be anything you want. <authorurl> # (optional) URL to the author's website. <requiredpackages> # A list of packages including their version required for this package to work. <requiredpackage> # Example: 1 <requiredpackage minversion= \"2.7.5\" file= \"requirements/com.example.foo.tar\" > com.example.foo </requiredpackage> The attribute minversion must be a valid version number as described in <version> . The file attribute is optional and specifies the location of the required package's archive relative to the package.xml . <optionalpackage> # A list of optional packages which can be selected by the user at the very end of the installation process. <optionalpackage> # Example: 1 <optionalpackage file= \"optionals/com.example.bar.tar\" > com.example.bar </optionalpackage> The file attribute specifies the location of the optional package's archive relative to the package.xml . <excludedpackages> # List of packages which conflict with this package. It is not possible to install it if any of the specified packages is installed. In return you cannot install an excluded package if this package is installed. <excludedpackage> # Example: 1 <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> The attribute version must be a valid version number as described in the \\<version> section. In the example above it will be impossible to install this package in WoltLab Suite Core 6.0.0 Alpha 1 or higher. <compatibility> # Available since WoltLab Suite 3.1 With the release of WoltLab Suite 5.2 the API versions were abolished. Instead of using API versions packages should exclude version 6.0.0 Alpha 1 of com.woltlab.wcf going forward. WoltLab Suite 3.1 introduced a new versioning system that focused around the API compatibility and is intended to replace the <excludedpackage> instruction for the Core for most plugins. The <compatibility> -tag holds a list of compatible API versions, and while only a single version is available at the time of writing, future versions will add more versions with backwards-compatibility in mind. Example: 1 2 3 <compatibility> <api version= \"2018\" /> </compatibility> Existing API versions # WoltLab Suite Core API-Version Backwards-Compatible to API-Version 3.1 2018 n/a <instructions> # List of instructions to be executed upon install or update. The order is important, the topmost <instruction> will be executed first. <instructions type=\"install\"> # List of instructions for a new installation of this package. <instructions type=\"update\" fromversion=\"\u2026\"> # The attribute fromversion must be a valid version number as described in the \\<version> section and specifies a possible update from that very version to the package's version. The installation process will pick exactly one update instruction, ignoring everything else. Please read the explanation below! Example: Installed version: 1.0.0 Package version: 1.0.2 1 2 3 4 5 6 <instructions type= \"update\" fromversion= \"1.0.0\" > <!-- \u2026 --> </instructions> <instructions type= \"update\" fromversion= \"1.0.1\" > <!-- \u2026 --> </instructions> In this example WoltLab Suite Core will pick the first update block since it allows an update from 1.0.0 -> 1.0.2 . The other block is not considered, since the currently installed version is 1.0.0 . After applying the update block ( fromversion=\"1.0.0\" ), the version now reads 1.0.2 . <instruction> # Example: 1 <instruction type= \"objectTypeDefinition\" > objectTypeDefinition.xml </instruction> The attribute type specifies the instruction type which is used to determine the package installation plugin (PIP) invoked to handle its value. The value must be a valid file relative to the location of package.xml . Many PIPs provide default file names which are used if no value is given: 1 <instruction type= \"objectTypeDefinition\" /> There is a list of all default PIPs available. Both the type -attribute and the element value are case-sensitive. Windows does not care if the file is called objecttypedefinition.xml but was referenced as objectTypeDefinition.xml , but both Linux and Mac systems will be unable to find the file. In addition to the type attribute, an optional run attribute (with standalone as the only valid value) is supported which forces the installation to execute this PIP in an isolated request, allowing a single, resource-heavy PIP to execute without encountering restrictions such as PHP\u2019s memory_limit or max_execution_time : 1 <instruction type= \"file\" run= \"standalone\" /> <void/> # Sometimes a package update should only adjust the metadata of the package, for example, an optional package was added. However, WoltLab Suite Core requires that the list of <instructions> is non-empty. Instead of using a dummy <instruction> that idempotently updates some PIP, the <void/> tag can be used for this use-case. Using the <void/> tag is only valid for <instructions type=\"update\"> and must not be accompanied by other <instruction> tags. Example: 1 2 3 <instructions type= \"update\" fromversion= \"1.0.0\" > <void/> </instructions>","title":"package.xml"},{"location":"package/package-xml/#packagexml","text":"The package.xml is the core component of every package. It provides the meta data (e.g. package name, description, author) and the instruction set for a new installation and/or updating from a previous version.","title":"package.xml"},{"location":"package/package-xml/#example","text":"package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.example.package\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/package.xsd\" > <packageinformation> <packagename> Simple Package </packagename> <packagedescription> A simple package to demonstrate the package system of WoltLab Suite Core </packagedescription> <version> 1.0.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> YOUR NAME </author> <authorurl> http://www.example.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"template\" > templates.tar </instruction> </instructions> </package>","title":"Example"},{"location":"package/package-xml/#elements","text":"","title":"Elements"},{"location":"package/package-xml/#package","text":"The root node of every package.xml it contains the reference to the namespace and the location of the XML Schema Definition (XSD). The attribute name is the most important part, it holds the unique package identifier and is mandatory. It is based upon your domain name and the package name of your choice. For example WoltLab Suite Forum (formerly know an WoltLab Burning Board and usually abbreviated as wbb ) is created by WoltLab which owns the domain woltlab.com . The resulting package identifier is com.woltlab.wbb ( <tld>.<domain>.<packageName> ).","title":"<package>"},{"location":"package/package-xml/#packageinformation","text":"Holds the entire meta data of the package.","title":"<packageinformation>"},{"location":"package/package-xml/#packagename","text":"This is the actual package name displayed to the end user, this can be anything you want, try to keep it short. It supports the attribute languagecode which allows you to provide the package name in different languages, please be aware that if it is not present, en (English) is assumed: 1 2 3 4 <packageinformation> <packagename> Simple Package </packagename> <packagename languagecode= \"de\" > Einfaches Paket </packagename> </packageinformation>","title":"<packagename>"},{"location":"package/package-xml/#packagedescription","text":"Brief summary of the package, use it to explain what it does since the package name might not always be clear enough. The attribute languagecode is available here too, please reference to <packagename> for details.","title":"<packagedescription>"},{"location":"package/package-xml/#version","text":"The package's version number, this is a string consisting of three numbers separated with a dot and optionally followed by a keyword (must be followed with another number). The possible keywords are: Alpha/dev (both is regarded to be the same) Beta RC (release candidate) pl (patch level) Valid examples: 1.0.0 1.12.13 Alpha 19 7.0.0 pl 3 Invalid examples: 1.0.0 Beta (keyword Beta must be followed by a number) 2.0 RC 3 (version number must consists of 3 blocks of numbers) 1.2.3 dev 4.5 (4.5 is not an integer, 4 or 5 would be valid but not the fraction)","title":"<version>"},{"location":"package/package-xml/#date","text":"Must be a valid ISO 8601 date, e.g. 2013-12-27 .","title":"<date>"},{"location":"package/package-xml/#authorinformation","text":"Holds meta data regarding the package's author.","title":"<authorinformation>"},{"location":"package/package-xml/#author","text":"Can be anything you want.","title":"<author>"},{"location":"package/package-xml/#authorurl","text":"(optional) URL to the author's website.","title":"<authorurl>"},{"location":"package/package-xml/#requiredpackages","text":"A list of packages including their version required for this package to work.","title":"<requiredpackages>"},{"location":"package/package-xml/#requiredpackage","text":"Example: 1 <requiredpackage minversion= \"2.7.5\" file= \"requirements/com.example.foo.tar\" > com.example.foo </requiredpackage> The attribute minversion must be a valid version number as described in <version> . The file attribute is optional and specifies the location of the required package's archive relative to the package.xml .","title":"<requiredpackage>"},{"location":"package/package-xml/#optionalpackage","text":"A list of optional packages which can be selected by the user at the very end of the installation process.","title":"<optionalpackage>"},{"location":"package/package-xml/#optionalpackage_1","text":"Example: 1 <optionalpackage file= \"optionals/com.example.bar.tar\" > com.example.bar </optionalpackage> The file attribute specifies the location of the optional package's archive relative to the package.xml .","title":"<optionalpackage>"},{"location":"package/package-xml/#excludedpackages","text":"List of packages which conflict with this package. It is not possible to install it if any of the specified packages is installed. In return you cannot install an excluded package if this package is installed.","title":"<excludedpackages>"},{"location":"package/package-xml/#excludedpackage","text":"Example: 1 <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> The attribute version must be a valid version number as described in the \\<version> section. In the example above it will be impossible to install this package in WoltLab Suite Core 6.0.0 Alpha 1 or higher.","title":"<excludedpackage>"},{"location":"package/package-xml/#compatibility","text":"Available since WoltLab Suite 3.1 With the release of WoltLab Suite 5.2 the API versions were abolished. Instead of using API versions packages should exclude version 6.0.0 Alpha 1 of com.woltlab.wcf going forward. WoltLab Suite 3.1 introduced a new versioning system that focused around the API compatibility and is intended to replace the <excludedpackage> instruction for the Core for most plugins. The <compatibility> -tag holds a list of compatible API versions, and while only a single version is available at the time of writing, future versions will add more versions with backwards-compatibility in mind. Example: 1 2 3 <compatibility> <api version= \"2018\" /> </compatibility>","title":"<compatibility>"},{"location":"package/package-xml/#existing-api-versions","text":"WoltLab Suite Core API-Version Backwards-Compatible to API-Version 3.1 2018 n/a","title":"Existing API versions"},{"location":"package/package-xml/#instructions","text":"List of instructions to be executed upon install or update. The order is important, the topmost <instruction> will be executed first.","title":"<instructions>"},{"location":"package/package-xml/#instructions-typeinstall","text":"List of instructions for a new installation of this package.","title":"<instructions type=\"install\">"},{"location":"package/package-xml/#instructions-typeupdate-fromversion","text":"The attribute fromversion must be a valid version number as described in the \\<version> section and specifies a possible update from that very version to the package's version. The installation process will pick exactly one update instruction, ignoring everything else. Please read the explanation below! Example: Installed version: 1.0.0 Package version: 1.0.2 1 2 3 4 5 6 <instructions type= \"update\" fromversion= \"1.0.0\" > <!-- \u2026 --> </instructions> <instructions type= \"update\" fromversion= \"1.0.1\" > <!-- \u2026 --> </instructions> In this example WoltLab Suite Core will pick the first update block since it allows an update from 1.0.0 -> 1.0.2 . The other block is not considered, since the currently installed version is 1.0.0 . After applying the update block ( fromversion=\"1.0.0\" ), the version now reads 1.0.2 .","title":"<instructions type=\"update\" fromversion=\"\u2026\">"},{"location":"package/package-xml/#instruction","text":"Example: 1 <instruction type= \"objectTypeDefinition\" > objectTypeDefinition.xml </instruction> The attribute type specifies the instruction type which is used to determine the package installation plugin (PIP) invoked to handle its value. The value must be a valid file relative to the location of package.xml . Many PIPs provide default file names which are used if no value is given: 1 <instruction type= \"objectTypeDefinition\" /> There is a list of all default PIPs available. Both the type -attribute and the element value are case-sensitive. Windows does not care if the file is called objecttypedefinition.xml but was referenced as objectTypeDefinition.xml , but both Linux and Mac systems will be unable to find the file. In addition to the type attribute, an optional run attribute (with standalone as the only valid value) is supported which forces the installation to execute this PIP in an isolated request, allowing a single, resource-heavy PIP to execute without encountering restrictions such as PHP\u2019s memory_limit or max_execution_time : 1 <instruction type= \"file\" run= \"standalone\" />","title":"<instruction>"},{"location":"package/package-xml/#void","text":"Sometimes a package update should only adjust the metadata of the package, for example, an optional package was added. However, WoltLab Suite Core requires that the list of <instructions> is non-empty. Instead of using a dummy <instruction> that idempotently updates some PIP, the <void/> tag can be used for this use-case. Using the <void/> tag is only valid for <instructions type=\"update\"> and must not be accompanied by other <instruction> tags. Example: 1 2 3 <instructions type= \"update\" fromversion= \"1.0.0\" > <void/> </instructions>","title":"<void/>"},{"location":"package/pip/","text":"Package Installation Plugins # Package Installation Plugins (PIPs) are interfaces to deploy and edit content as well as components. For XML-based PIPs: <![CDATA[]]> must be used for language items and page contents. In all other cases it may only be used when necessary. Built-In PIPs # Name Description aclOption Customizable permissions for individual objects acpMenu Admin panel menu categories and items acpSearchProvider Data provider for the admin panel search acpTemplate Admin panel templates acpTemplateDelete Deletes admin panel templates installed with acpTemplate bbcode BBCodes for rich message formatting box Boxes that can be placed anywhere on a page clipboardAction Perform bulk operations on marked objects coreObject Access Singletons from within the template cronjob Periodically execute code with customizable intervals database Updates the database layout using the PHP API eventListener Register listeners for the event system file Deploy any type of files with the exception of templates fileDelete Deletes files installed with file language Language items mediaProvider Detect and convert links to media providers menu Side-wide and custom per-page menus menuItem Menu items for menus created through the menu PIP objectType Flexible type registry based on definitions objectTypeDefinition Groups objects and classes by functionality option Side-wide configuration options page Register page controllers and text-based pages pip Package Installation Plugins script Execute arbitrary PHP code during installation, update and uninstallation smiley Smileys sql Execute SQL instructions using a MySQL-flavored syntax (also see database PHP API ) style Style template Frontend templates templateDelete Deletes frontend templates installed with template templateListener Embed template code into templates without altering the original userGroupOption Permissions for user groups userMenu User menu categories and items userNotificationEvent Events of the user notification system userOption User settings userProfileMenu User profile tabs","title":"Overview"},{"location":"package/pip/#package-installation-plugins","text":"Package Installation Plugins (PIPs) are interfaces to deploy and edit content as well as components. For XML-based PIPs: <![CDATA[]]> must be used for language items and page contents. In all other cases it may only be used when necessary.","title":"Package Installation Plugins"},{"location":"package/pip/#built-in-pips","text":"Name Description aclOption Customizable permissions for individual objects acpMenu Admin panel menu categories and items acpSearchProvider Data provider for the admin panel search acpTemplate Admin panel templates acpTemplateDelete Deletes admin panel templates installed with acpTemplate bbcode BBCodes for rich message formatting box Boxes that can be placed anywhere on a page clipboardAction Perform bulk operations on marked objects coreObject Access Singletons from within the template cronjob Periodically execute code with customizable intervals database Updates the database layout using the PHP API eventListener Register listeners for the event system file Deploy any type of files with the exception of templates fileDelete Deletes files installed with file language Language items mediaProvider Detect and convert links to media providers menu Side-wide and custom per-page menus menuItem Menu items for menus created through the menu PIP objectType Flexible type registry based on definitions objectTypeDefinition Groups objects and classes by functionality option Side-wide configuration options page Register page controllers and text-based pages pip Package Installation Plugins script Execute arbitrary PHP code during installation, update and uninstallation smiley Smileys sql Execute SQL instructions using a MySQL-flavored syntax (also see database PHP API ) style Style template Frontend templates templateDelete Deletes frontend templates installed with template templateListener Embed template code into templates without altering the original userGroupOption Permissions for user groups userMenu User menu categories and items userNotificationEvent Events of the user notification system userOption User settings userProfileMenu User profile tabs","title":"Built-In PIPs"},{"location":"package/pip/acl-option/","text":"ACL Option Package Installation Plugin # Add customizable permissions for individual objects. Option Components # Each acl option is described as an <option> element with the mandatory attribute name . <categoryname> # Optional The name of the acl option category to which the option belongs. <objecttype> # The name of the acl object type (of the object type definition com.woltlab.wcf.acl ). Category Components # Each acl option category is described as an <category> element with the mandatory attribute name that should follow the naming pattern <permissionName> or <permissionType>.<permissionName> , with <permissionType> generally having user or mod as value. <objecttype> # The name of the acl object type (of the object type definition com.woltlab.wcf.acl ). Example # aclOption.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/aclOption.xsd\" > <import> <categories> <category name= \"user.example\" > <objecttype> com.example.wcf.example </objecttype> </category> <category name= \"mod.example\" > <objecttype> com.example.wcf.example </objecttype> </category> </categories> <options> <option name= \"canAddExample\" > <categoryname> user.example </categoryname> <objecttype> com.example.wcf.example </objecttype> </option> <option name= \"canDeleteExample\" > <categoryname> mod.example </categoryname> <objecttype> com.example.wcf.example </objecttype> </option> </options> </import> <delete> <optioncategory name= \"old.example\" > <objecttype> com.example.wcf.example </objecttype> </optioncategory> <option name= \"canDoSomethingWithExample\" > <objecttype> com.example.wcf.example </objecttype> </option> </delete> </data>","title":"aclOption"},{"location":"package/pip/acl-option/#acl-option-package-installation-plugin","text":"Add customizable permissions for individual objects.","title":"ACL Option Package Installation Plugin"},{"location":"package/pip/acl-option/#option-components","text":"Each acl option is described as an <option> element with the mandatory attribute name .","title":"Option Components"},{"location":"package/pip/acl-option/#categoryname","text":"Optional The name of the acl option category to which the option belongs.","title":"<categoryname>"},{"location":"package/pip/acl-option/#objecttype","text":"The name of the acl object type (of the object type definition com.woltlab.wcf.acl ).","title":"<objecttype>"},{"location":"package/pip/acl-option/#category-components","text":"Each acl option category is described as an <category> element with the mandatory attribute name that should follow the naming pattern <permissionName> or <permissionType>.<permissionName> , with <permissionType> generally having user or mod as value.","title":"Category Components"},{"location":"package/pip/acl-option/#objecttype_1","text":"The name of the acl object type (of the object type definition com.woltlab.wcf.acl ).","title":"<objecttype>"},{"location":"package/pip/acl-option/#example","text":"aclOption.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/aclOption.xsd\" > <import> <categories> <category name= \"user.example\" > <objecttype> com.example.wcf.example </objecttype> </category> <category name= \"mod.example\" > <objecttype> com.example.wcf.example </objecttype> </category> </categories> <options> <option name= \"canAddExample\" > <categoryname> user.example </categoryname> <objecttype> com.example.wcf.example </objecttype> </option> <option name= \"canDeleteExample\" > <categoryname> mod.example </categoryname> <objecttype> com.example.wcf.example </objecttype> </option> </options> </import> <delete> <optioncategory name= \"old.example\" > <objecttype> com.example.wcf.example </objecttype> </optioncategory> <option name= \"canDoSomethingWithExample\" > <objecttype> com.example.wcf.example </objecttype> </option> </delete> </data>","title":"Example"},{"location":"package/pip/acp-menu/","text":"ACP Menu Package Installation Plugin # Registers new ACP menu items. Components # Each item is described as an <acpmenuitem> element with the mandatory attribute name . <parent> # Optional The item\u2019s parent item. <showorder> # Optional Specifies the order of this item within the parent item. <controller> # The fully qualified class name of the target controller. If not specified this item serves as a category. <link> # Additional components if <controller> is set, the full external link otherwise. <icon> # Use an icon only for top-level and 4th-level items. Name of the Font Awesome icon class. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the tab to be shown. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the tab to be shown. Example # acpMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpMenu.xsd\" > <import> <acpmenuitem name= \"foo.acp.menu.link.example\" > <parent> wcf.acp.menu.link.application </parent> </acpmenuitem> <acpmenuitem name= \"foo.acp.menu.link.example.list\" > <controller> foo\\acp\\page\\ExampleListPage </controller> <parent> foo.acp.menu.link.example </parent> <permissions> admin.foo.canManageExample </permissions> <showorder> 1 </showorder> </acpmenuitem> <acpmenuitem name= \"foo.acp.menu.link.example.add\" > <controller> foo\\acp\\form\\ExampleAddForm </controller> <parent> foo.acp.menu.link.example.list </parent> <permissions> admin.foo.canManageExample </permissions> <icon> fa-plus </icon> </acpmenuitem> </import> </data>","title":"acpMenu"},{"location":"package/pip/acp-menu/#acp-menu-package-installation-plugin","text":"Registers new ACP menu items.","title":"ACP Menu Package Installation Plugin"},{"location":"package/pip/acp-menu/#components","text":"Each item is described as an <acpmenuitem> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/acp-menu/#parent","text":"Optional The item\u2019s parent item.","title":"<parent>"},{"location":"package/pip/acp-menu/#showorder","text":"Optional Specifies the order of this item within the parent item.","title":"<showorder>"},{"location":"package/pip/acp-menu/#controller","text":"The fully qualified class name of the target controller. If not specified this item serves as a category.","title":"<controller>"},{"location":"package/pip/acp-menu/#link","text":"Additional components if <controller> is set, the full external link otherwise.","title":"<link>"},{"location":"package/pip/acp-menu/#icon","text":"Use an icon only for top-level and 4th-level items. Name of the Font Awesome icon class.","title":"<icon>"},{"location":"package/pip/acp-menu/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the tab to be shown.","title":"<options>"},{"location":"package/pip/acp-menu/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the tab to be shown.","title":"<permissions>"},{"location":"package/pip/acp-menu/#example","text":"acpMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpMenu.xsd\" > <import> <acpmenuitem name= \"foo.acp.menu.link.example\" > <parent> wcf.acp.menu.link.application </parent> </acpmenuitem> <acpmenuitem name= \"foo.acp.menu.link.example.list\" > <controller> foo\\acp\\page\\ExampleListPage </controller> <parent> foo.acp.menu.link.example </parent> <permissions> admin.foo.canManageExample </permissions> <showorder> 1 </showorder> </acpmenuitem> <acpmenuitem name= \"foo.acp.menu.link.example.add\" > <controller> foo\\acp\\form\\ExampleAddForm </controller> <parent> foo.acp.menu.link.example.list </parent> <permissions> admin.foo.canManageExample </permissions> <icon> fa-plus </icon> </acpmenuitem> </import> </data>","title":"Example"},{"location":"package/pip/acp-search-provider/","text":"ACP Search Provider Package Installation Plugin # Registers data provider for the admin panel search. Components # Each acp search result provider is described as an <acpsearchprovider> element with the mandatory attribute name . <classname> # The name of the class providing the search results, the class has to implement the wcf\\system\\search\\acp\\IACPSearchResultProvider interface. <showorder> # Optional Determines at which position of the search result list the provided results are shown. Example # acpSearchProvider.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpSearchProvider.xsd\" > <import> <acpsearchprovider name= \"com.woltlab.wcf.example\" > <classname> wcf\\system\\search\\acp\\ExampleACPSearchResultProvider </classname> <showorder> 1 </showorder> </acpsearchprovider> </import> </data>","title":"acpSearchProvider"},{"location":"package/pip/acp-search-provider/#acp-search-provider-package-installation-plugin","text":"Registers data provider for the admin panel search.","title":"ACP Search Provider Package Installation Plugin"},{"location":"package/pip/acp-search-provider/#components","text":"Each acp search result provider is described as an <acpsearchprovider> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/acp-search-provider/#classname","text":"The name of the class providing the search results, the class has to implement the wcf\\system\\search\\acp\\IACPSearchResultProvider interface.","title":"<classname>"},{"location":"package/pip/acp-search-provider/#showorder","text":"Optional Determines at which position of the search result list the provided results are shown.","title":"<showorder>"},{"location":"package/pip/acp-search-provider/#example","text":"acpSearchProvider.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpSearchProvider.xsd\" > <import> <acpsearchprovider name= \"com.woltlab.wcf.example\" > <classname> wcf\\system\\search\\acp\\ExampleACPSearchResultProvider </classname> <showorder> 1 </showorder> </acpsearchprovider> </import> </data>","title":"Example"},{"location":"package/pip/acp-template-delete/","text":"ACP Template Delete Package Installation Plugin # Available since WoltLab Suite 5.5. Deletes admin panel templates installed with the acpTemplate package installation plugin. You cannot delete acp templates provided by other packages. Components # Each item is described as a <template> element with an optional application , which behaves like it does for acp templates . The templates are identified by their name like when adding template listeners , i.e. by the file name without the .tpl file extension. Example # acpTemplateDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpTemplateDelete.xsd\" > <delete> <template> fouAdd </template> <template application= \"app\" > __appAdd </template> </delete> </data>","title":"acpTemplateDelete"},{"location":"package/pip/acp-template-delete/#acp-template-delete-package-installation-plugin","text":"Available since WoltLab Suite 5.5. Deletes admin panel templates installed with the acpTemplate package installation plugin. You cannot delete acp templates provided by other packages.","title":"ACP Template Delete Package Installation Plugin"},{"location":"package/pip/acp-template-delete/#components","text":"Each item is described as a <template> element with an optional application , which behaves like it does for acp templates . The templates are identified by their name like when adding template listeners , i.e. by the file name without the .tpl file extension.","title":"Components"},{"location":"package/pip/acp-template-delete/#example","text":"acpTemplateDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpTemplateDelete.xsd\" > <delete> <template> fouAdd </template> <template application= \"app\" > __appAdd </template> </delete> </data>","title":"Example"},{"location":"package/pip/acp-template/","text":"ACP Template Installation Plugin # Add templates for acp pages and forms by providing an archive containing the template files. You cannot overwrite acp templates provided by other packages. Archive # The acpTemplate package installation plugins expects a .tar (recommended) or .tar.gz archive. The templates must all be in the root of the archive. Do not include any directories in the archive. The file path given in the instruction element as its value must be relative to the package.xml file. Attributes # application # The application attribute determines to which application the installed acp templates belong and thus in which directory the templates are installed. The value of the application attribute has to be the abbreviation of an installed application. If no application attribute is given, the following rules are applied: If the package installing the acp templates is an application, then the templates will be installed in this application's directory. If the package installing the acp templates is no application, then the templates will be installed in WoltLab Suite Core's directory. Example in package.xml # 1 2 3 4 5 6 7 <instruction type= \"acpTemplate\" /> <!-- is the same as --> <instruction type= \"acpTemplate\" > acptemplates.tar </instruction> <!-- if an application \"com.woltlab.example\" is being installed, the following lines are equivalent --> <instruction type= \"acpTemplate\" /> <instruction type= \"acpTemplate\" application= \"example\" />","title":"acpTemplate"},{"location":"package/pip/acp-template/#acp-template-installation-plugin","text":"Add templates for acp pages and forms by providing an archive containing the template files. You cannot overwrite acp templates provided by other packages.","title":"ACP Template Installation Plugin"},{"location":"package/pip/acp-template/#archive","text":"The acpTemplate package installation plugins expects a .tar (recommended) or .tar.gz archive. The templates must all be in the root of the archive. Do not include any directories in the archive. The file path given in the instruction element as its value must be relative to the package.xml file.","title":"Archive"},{"location":"package/pip/acp-template/#attributes","text":"","title":"Attributes"},{"location":"package/pip/acp-template/#application","text":"The application attribute determines to which application the installed acp templates belong and thus in which directory the templates are installed. The value of the application attribute has to be the abbreviation of an installed application. If no application attribute is given, the following rules are applied: If the package installing the acp templates is an application, then the templates will be installed in this application's directory. If the package installing the acp templates is no application, then the templates will be installed in WoltLab Suite Core's directory.","title":"application"},{"location":"package/pip/acp-template/#example-in-packagexml","text":"1 2 3 4 5 6 7 <instruction type= \"acpTemplate\" /> <!-- is the same as --> <instruction type= \"acpTemplate\" > acptemplates.tar </instruction> <!-- if an application \"com.woltlab.example\" is being installed, the following lines are equivalent --> <instruction type= \"acpTemplate\" /> <instruction type= \"acpTemplate\" application= \"example\" />","title":"Example in package.xml"},{"location":"package/pip/bbcode/","text":"BBCode Package Installation Plugin # Registers new BBCodes. Components # Each bbcode is described as an <bbcode> element with the mandatory attribute name . The name attribute must contain alphanumeric characters only and is exposed to the user. <htmlopen> # Optional: Must not be provided if the BBCode is being processed a PHP class ( <classname> ). The contents of this tag are literally copied into the opening tag of the bbcode. <htmlclose> # Optional: Must not be provided if <htmlopen> is not given. Must match the <htmlopen> tag. Do not provide for self-closing tags. <classname> # The name of the class providing the bbcode output, the class has to implement the wcf\\system\\bbcode\\IBBCode interface. BBCodes can be statically converted to HTML during input processing using a wcf\\system\\html\\metacode\\converter\\*MetaConverter class. This class does not need to be registered. <wysiwygicon> # Optional Name of the Font Awesome icon class or path to a gif , jpg , jpeg , png , or svg image (placed inside the icon/ directory) to show in the editor toolbar. <buttonlabel> # Optional: Must be provided if an icon is given. Explanatory text to show when hovering the icon. <sourcecode> # Do not set this to 1 if you don't specify a PHP class for processing. You must perform XSS sanitizing yourself! If set to 1 contents of this BBCode will not be interpreted, but literally passed through instead. <isBlockElement> # Set to 1 if the output of this BBCode is a HTML block element (according to the HTML specification). <attributes> # Each bbcode is described as an <attribute> element with the mandatory attribute name . The name attribute is a 0-indexed integer. <html> # Optional: Must not be provided if the BBCode is being processed a PHP class ( <classname> ). The contents of this tag are copied into the opening tag of the bbcode. %s is replaced by the attribute value. <validationpattern> # Optional Defines a regular expression that is used to validate the value of the attribute. <required> # Optional Specifies whether this attribute must be provided. <usetext> # Optional Should only be set to 1 for the attribute with name 0 . Specifies whether the text content of the BBCode should become this attribute's value. Example # bbcode.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/bbcode.xsd\" > <import> <bbcode name= \"foo\" > <classname> wcf\\system\\bbcode\\FooBBCode </classname> <attributes> <attribute name= \"0\" > <validationpattern> ^\\d+$ </validationpattern> <required> 1 </required> </attribute> </attributes> </bbcode> <bbcode name= \"example\" > <htmlopen> div </htmlopen> <htmlclose> div </htmlclose> <isBlockElement> 1 </isBlockElement> <wysiwygicon> fa-bath </wysiwygicon> <buttonlabel> wcf.editor.button.example </buttonlabel> </bbcode> </import> </data>","title":"bbcode"},{"location":"package/pip/bbcode/#bbcode-package-installation-plugin","text":"Registers new BBCodes.","title":"BBCode Package Installation Plugin"},{"location":"package/pip/bbcode/#components","text":"Each bbcode is described as an <bbcode> element with the mandatory attribute name . The name attribute must contain alphanumeric characters only and is exposed to the user.","title":"Components"},{"location":"package/pip/bbcode/#htmlopen","text":"Optional: Must not be provided if the BBCode is being processed a PHP class ( <classname> ). The contents of this tag are literally copied into the opening tag of the bbcode.","title":"<htmlopen>"},{"location":"package/pip/bbcode/#htmlclose","text":"Optional: Must not be provided if <htmlopen> is not given. Must match the <htmlopen> tag. Do not provide for self-closing tags.","title":"<htmlclose>"},{"location":"package/pip/bbcode/#classname","text":"The name of the class providing the bbcode output, the class has to implement the wcf\\system\\bbcode\\IBBCode interface. BBCodes can be statically converted to HTML during input processing using a wcf\\system\\html\\metacode\\converter\\*MetaConverter class. This class does not need to be registered.","title":"<classname>"},{"location":"package/pip/bbcode/#wysiwygicon","text":"Optional Name of the Font Awesome icon class or path to a gif , jpg , jpeg , png , or svg image (placed inside the icon/ directory) to show in the editor toolbar.","title":"<wysiwygicon>"},{"location":"package/pip/bbcode/#buttonlabel","text":"Optional: Must be provided if an icon is given. Explanatory text to show when hovering the icon.","title":"<buttonlabel>"},{"location":"package/pip/bbcode/#sourcecode","text":"Do not set this to 1 if you don't specify a PHP class for processing. You must perform XSS sanitizing yourself! If set to 1 contents of this BBCode will not be interpreted, but literally passed through instead.","title":"<sourcecode>"},{"location":"package/pip/bbcode/#isblockelement","text":"Set to 1 if the output of this BBCode is a HTML block element (according to the HTML specification).","title":"<isBlockElement>"},{"location":"package/pip/bbcode/#attributes","text":"Each bbcode is described as an <attribute> element with the mandatory attribute name . The name attribute is a 0-indexed integer.","title":"<attributes>"},{"location":"package/pip/bbcode/#html","text":"Optional: Must not be provided if the BBCode is being processed a PHP class ( <classname> ). The contents of this tag are copied into the opening tag of the bbcode. %s is replaced by the attribute value.","title":"<html>"},{"location":"package/pip/bbcode/#validationpattern","text":"Optional Defines a regular expression that is used to validate the value of the attribute.","title":"<validationpattern>"},{"location":"package/pip/bbcode/#required","text":"Optional Specifies whether this attribute must be provided.","title":"<required>"},{"location":"package/pip/bbcode/#usetext","text":"Optional Should only be set to 1 for the attribute with name 0 . Specifies whether the text content of the BBCode should become this attribute's value.","title":"<usetext>"},{"location":"package/pip/bbcode/#example","text":"bbcode.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/bbcode.xsd\" > <import> <bbcode name= \"foo\" > <classname> wcf\\system\\bbcode\\FooBBCode </classname> <attributes> <attribute name= \"0\" > <validationpattern> ^\\d+$ </validationpattern> <required> 1 </required> </attribute> </attributes> </bbcode> <bbcode name= \"example\" > <htmlopen> div </htmlopen> <htmlclose> div </htmlclose> <isBlockElement> 1 </isBlockElement> <wysiwygicon> fa-bath </wysiwygicon> <buttonlabel> wcf.editor.button.example </buttonlabel> </bbcode> </import> </data>","title":"Example"},{"location":"package/pip/box/","text":"Box Package Installation Plugin # Deploy and manage boxes that can be placed anywhere on the site, they come in two flavors: system and content-based. Components # Each item is described as a <box> element with the mandatory attribute name that should follow the naming pattern <packageIdentifier>.<BoxName> , e.g. com.woltlab.wcf.RecentActivity . <name> # The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <name> elements. <boxType> # system # The special system type is reserved for boxes that pull their properties and content from a registered PHP class. Requires the <objectType> element. html , text or tpl # Provide arbitrary content, requires the <content> element. <objectType> # Required for boxes with boxType = system , must be registered through the objectType PIP for the definition com.woltlab.wcf.boxController . <position> # The default display position of this box, can be any of the following: bottom contentBottom contentTop footer footerBoxes headerBoxes hero sidebarLeft sidebarRight top Placeholder Positions # <showHeader> # Setting this to 0 will suppress display of the box title, useful for boxes containing advertisements or similar. Defaults to 1 . <visibleEverywhere> # Controls the display on all pages ( 1 ) or none ( 0 ), can be used in conjunction with <visibilityExceptions> . <visibilityExceptions> # Inverts the <visibleEverywhere> setting for the listed pages only. <cssClassName> # Provide a custom CSS class name that is added to the menu container, allowing further customization of the menu's appearance. <content> # The language attribute is required and should specify the ISO-639-1 language code. <title> # The title element is required and controls the box title shown to the end users. <content> # The content that should be used to populate the box, only used and required if the boxType equals text , html and tpl . Example # box.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/box.xsd\" > <import> <box identifier= \"com.woltlab.wcf.RecentActivity\" > <name language= \"de\" > Letzte Aktivit\u00e4ten </name> <name language= \"en\" > Recent Activities </name> <boxType> system </boxType> <objectType> com.woltlab.wcf.recentActivityList </objectType> <position> contentBottom </position> <showHeader> 0 </showHeader> <visibleEverywhere> 0 </visibleEverywhere> <visibilityExceptions> <page> com.woltlab.wcf.Dashboard </page> </visibilityExceptions> <limit> 10 </limit> <content language= \"de\" > <title> Letzte Aktivit\u00e4ten </title> </content> <content language= \"en\" > <title> Recent Activities </title> </content> </box> </import> <delete> <box identifier= \"com.woltlab.wcf.RecentActivity\" /> </delete> </data>","title":"box"},{"location":"package/pip/box/#box-package-installation-plugin","text":"Deploy and manage boxes that can be placed anywhere on the site, they come in two flavors: system and content-based.","title":"Box Package Installation Plugin"},{"location":"package/pip/box/#components","text":"Each item is described as a <box> element with the mandatory attribute name that should follow the naming pattern <packageIdentifier>.<BoxName> , e.g. com.woltlab.wcf.RecentActivity .","title":"Components"},{"location":"package/pip/box/#name","text":"The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <name> elements.","title":"<name>"},{"location":"package/pip/box/#boxtype","text":"","title":"<boxType>"},{"location":"package/pip/box/#system","text":"The special system type is reserved for boxes that pull their properties and content from a registered PHP class. Requires the <objectType> element.","title":"system"},{"location":"package/pip/box/#html-text-or-tpl","text":"Provide arbitrary content, requires the <content> element.","title":"html, text or tpl"},{"location":"package/pip/box/#objecttype","text":"Required for boxes with boxType = system , must be registered through the objectType PIP for the definition com.woltlab.wcf.boxController .","title":"<objectType>"},{"location":"package/pip/box/#position","text":"The default display position of this box, can be any of the following: bottom contentBottom contentTop footer footerBoxes headerBoxes hero sidebarLeft sidebarRight top","title":"<position>"},{"location":"package/pip/box/#placeholder-positions","text":"","title":"Placeholder Positions"},{"location":"package/pip/box/#showheader","text":"Setting this to 0 will suppress display of the box title, useful for boxes containing advertisements or similar. Defaults to 1 .","title":"<showHeader>"},{"location":"package/pip/box/#visibleeverywhere","text":"Controls the display on all pages ( 1 ) or none ( 0 ), can be used in conjunction with <visibilityExceptions> .","title":"<visibleEverywhere>"},{"location":"package/pip/box/#visibilityexceptions","text":"Inverts the <visibleEverywhere> setting for the listed pages only.","title":"<visibilityExceptions>"},{"location":"package/pip/box/#cssclassname","text":"Provide a custom CSS class name that is added to the menu container, allowing further customization of the menu's appearance.","title":"<cssClassName>"},{"location":"package/pip/box/#content","text":"The language attribute is required and should specify the ISO-639-1 language code.","title":"<content>"},{"location":"package/pip/box/#title","text":"The title element is required and controls the box title shown to the end users.","title":"<title>"},{"location":"package/pip/box/#content_1","text":"The content that should be used to populate the box, only used and required if the boxType equals text , html and tpl .","title":"<content>"},{"location":"package/pip/box/#example","text":"box.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/box.xsd\" > <import> <box identifier= \"com.woltlab.wcf.RecentActivity\" > <name language= \"de\" > Letzte Aktivit\u00e4ten </name> <name language= \"en\" > Recent Activities </name> <boxType> system </boxType> <objectType> com.woltlab.wcf.recentActivityList </objectType> <position> contentBottom </position> <showHeader> 0 </showHeader> <visibleEverywhere> 0 </visibleEverywhere> <visibilityExceptions> <page> com.woltlab.wcf.Dashboard </page> </visibilityExceptions> <limit> 10 </limit> <content language= \"de\" > <title> Letzte Aktivit\u00e4ten </title> </content> <content language= \"en\" > <title> Recent Activities </title> </content> </box> </import> <delete> <box identifier= \"com.woltlab.wcf.RecentActivity\" /> </delete> </data>","title":"Example"},{"location":"package/pip/clipboard-action/","text":"Clipboard Action Package Installation Plugin # Registers clipboard actions. Components # Each clipboard action is described as an <action> element with the mandatory attribute name . <actionclassname> # The name of the class used by the clipboard API to process the concrete action. The class has to implement the wcf\\system\\clipboard\\action\\IClipboardAction interface, best by extending wcf\\system\\clipboard\\action\\AbstractClipboardAction . <pages> # Element with <page> children whose value contains the class name of the controller of the page on which the clipboard action is available. <showorder> # Optional Determines at which position of the clipboard action list the action is shown. Example # clipboardAction.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/clipboardAction.xsd\" > <import> <action name= \"delete\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 1 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> <action name= \"foo\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 2 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> <action name= \"bar\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 3 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> </import> </data>","title":"clipboardAction"},{"location":"package/pip/clipboard-action/#clipboard-action-package-installation-plugin","text":"Registers clipboard actions.","title":"Clipboard Action Package Installation Plugin"},{"location":"package/pip/clipboard-action/#components","text":"Each clipboard action is described as an <action> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/clipboard-action/#actionclassname","text":"The name of the class used by the clipboard API to process the concrete action. The class has to implement the wcf\\system\\clipboard\\action\\IClipboardAction interface, best by extending wcf\\system\\clipboard\\action\\AbstractClipboardAction .","title":"<actionclassname>"},{"location":"package/pip/clipboard-action/#pages","text":"Element with <page> children whose value contains the class name of the controller of the page on which the clipboard action is available.","title":"<pages>"},{"location":"package/pip/clipboard-action/#showorder","text":"Optional Determines at which position of the clipboard action list the action is shown.","title":"<showorder>"},{"location":"package/pip/clipboard-action/#example","text":"clipboardAction.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/clipboardAction.xsd\" > <import> <action name= \"delete\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 1 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> <action name= \"foo\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 2 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> <action name= \"bar\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 3 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> </import> </data>","title":"Example"},{"location":"package/pip/core-object/","text":"Core Object Package Installation Plugin # Registers wcf\\system\\SingletonFactory objects to be accessible in templates. Components # Each item is described as a <coreobject> element with the mandatory element objectname . <objectname> # The fully qualified class name of the class. Example # coreObject.xml 1 2 3 4 5 6 7 8 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/coreObject.xsd\" > <import> <coreobject> <objectname> wcf\\system\\example\\ExampleHandler </objectname> </coreobject> </import> </data> This object can be accessed in templates via $__wcf->getExampleHandler() (in general: the method name begins with get and ends with the unqualified class name).","title":"coreObject"},{"location":"package/pip/core-object/#core-object-package-installation-plugin","text":"Registers wcf\\system\\SingletonFactory objects to be accessible in templates.","title":"Core Object Package Installation Plugin"},{"location":"package/pip/core-object/#components","text":"Each item is described as a <coreobject> element with the mandatory element objectname .","title":"Components"},{"location":"package/pip/core-object/#objectname","text":"The fully qualified class name of the class.","title":"<objectname>"},{"location":"package/pip/core-object/#example","text":"coreObject.xml 1 2 3 4 5 6 7 8 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/coreObject.xsd\" > <import> <coreobject> <objectname> wcf\\system\\example\\ExampleHandler </objectname> </coreobject> </import> </data> This object can be accessed in templates via $__wcf->getExampleHandler() (in general: the method name begins with get and ends with the unqualified class name).","title":"Example"},{"location":"package/pip/cronjob/","text":"Cronjob Package Installation Plugin # Registers new cronjobs. The cronjob schedular works similar to the cron(8) daemon, which might not available to web applications on regular webspaces. The main difference is that WoltLab Suite\u2019s cronjobs do not guarantee execution at the specified points in time: WoltLab Suite\u2019s cronjobs are triggered by regular visitors in an AJAX request, once the next execution point lies in the past. Components # Each cronjob is described as an <cronjob> element with the mandatory attribute name . <classname> # The name of the class providing the cronjob's behaviour, the class has to implement the wcf\\system\\cronjob\\ICronjob interface. <description> # The language attribute is optional and should specify the ISO-639-1 language code. Provides a human readable description for the administrator. <start*> # All of the five startMinute , startHour , startDom (Day Of Month), startMonth , startDow (Day Of Week) are required. They correspond to the fields in crontab(5) of a cron daemon and accept the same syntax. <canbeedited> # Controls whether the administrator may edit the fields of the cronjob. Defaults to 1 . <canbedisabled> # Controls whether the administrator may disable the cronjob. Defaults to 1 . <isdisabled> # Controls whether the cronjob is disabled by default. Defaults to 0 . <options> # The options element can contain a comma-separated list of options of which at least one needs to be enabled for the template listener to be executed. Example # cronjob.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/cronjob.xsd\" > <import> <cronjob name= \"com.example.package.example\" > <classname> wcf\\system\\cronjob\\ExampleCronjob </classname> <description> Serves as an example </description> <description language= \"de\" > Stellt ein Beispiel dar </description> <startminute> 0 </startminute> <starthour> 2 </starthour> <startdom> */2 </startdom> <startmonth> * </startmonth> <startdow> * </startdow> <canbeedited> 1 </canbeedited> <canbedisabled> 1 </canbedisabled> </cronjob> </import> </data>","title":"cronjob"},{"location":"package/pip/cronjob/#cronjob-package-installation-plugin","text":"Registers new cronjobs. The cronjob schedular works similar to the cron(8) daemon, which might not available to web applications on regular webspaces. The main difference is that WoltLab Suite\u2019s cronjobs do not guarantee execution at the specified points in time: WoltLab Suite\u2019s cronjobs are triggered by regular visitors in an AJAX request, once the next execution point lies in the past.","title":"Cronjob Package Installation Plugin"},{"location":"package/pip/cronjob/#components","text":"Each cronjob is described as an <cronjob> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/cronjob/#classname","text":"The name of the class providing the cronjob's behaviour, the class has to implement the wcf\\system\\cronjob\\ICronjob interface.","title":"<classname>"},{"location":"package/pip/cronjob/#description","text":"The language attribute is optional and should specify the ISO-639-1 language code. Provides a human readable description for the administrator.","title":"<description>"},{"location":"package/pip/cronjob/#start","text":"All of the five startMinute , startHour , startDom (Day Of Month), startMonth , startDow (Day Of Week) are required. They correspond to the fields in crontab(5) of a cron daemon and accept the same syntax.","title":"<start*>"},{"location":"package/pip/cronjob/#canbeedited","text":"Controls whether the administrator may edit the fields of the cronjob. Defaults to 1 .","title":"<canbeedited>"},{"location":"package/pip/cronjob/#canbedisabled","text":"Controls whether the administrator may disable the cronjob. Defaults to 1 .","title":"<canbedisabled>"},{"location":"package/pip/cronjob/#isdisabled","text":"Controls whether the cronjob is disabled by default. Defaults to 0 .","title":"<isdisabled>"},{"location":"package/pip/cronjob/#options","text":"The options element can contain a comma-separated list of options of which at least one needs to be enabled for the template listener to be executed.","title":"<options>"},{"location":"package/pip/cronjob/#example","text":"cronjob.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/cronjob.xsd\" > <import> <cronjob name= \"com.example.package.example\" > <classname> wcf\\system\\cronjob\\ExampleCronjob </classname> <description> Serves as an example </description> <description language= \"de\" > Stellt ein Beispiel dar </description> <startminute> 0 </startminute> <starthour> 2 </starthour> <startdom> */2 </startdom> <startmonth> * </startmonth> <startdow> * </startdow> <canbeedited> 1 </canbeedited> <canbedisabled> 1 </canbedisabled> </cronjob> </import> </data>","title":"Example"},{"location":"package/pip/database/","text":"Database Package Installation Plugin # Available since WoltLab Suite 5.4. Update the database layout using the PHP API . You must install the PHP script through the file package installation plugin . The installation will attempt to delete the script after successful execution. Attributes # application # The application attribute must have the same value as the application attribute of the file package installation plugin instruction so that the correct file in the intended application directory is executed. For further information about the application attribute, refer to its documentation on the acpTemplate package installation plugin page . Expected value # The database -PIP expects a relative path to a .php file that returns an array of DatabaseTable objects. Naming convention # The PHP script is deployed by using the file package installation plugin . To prevent it from colliding with other install script (remember: You cannot overwrite files created by another plugin), we highly recommend to make use of these naming conventions: Installation: acp/database/install_<package>.php (example: acp/database/install_com.woltlab.wbb.php ) Update: acp/database/update_<package>_<targetVersion>.php (example: acp/database/update_com.woltlab.wbb_5.4.1.php ) <targetVersion> equals the version number of the current package being installed. If you're updating from 1.0.0 to 1.0.1 , <targetVersion> should read 1.0.1 . If you run multiple update scripts, you can append additional information in the filename. Execution environment # The script is included using include() within DatabasePackageInstallationPlugin::updateDatabase() .","title":"database"},{"location":"package/pip/database/#database-package-installation-plugin","text":"Available since WoltLab Suite 5.4. Update the database layout using the PHP API . You must install the PHP script through the file package installation plugin . The installation will attempt to delete the script after successful execution.","title":"Database Package Installation Plugin"},{"location":"package/pip/database/#attributes","text":"","title":"Attributes"},{"location":"package/pip/database/#application","text":"The application attribute must have the same value as the application attribute of the file package installation plugin instruction so that the correct file in the intended application directory is executed. For further information about the application attribute, refer to its documentation on the acpTemplate package installation plugin page .","title":"application"},{"location":"package/pip/database/#expected-value","text":"The database -PIP expects a relative path to a .php file that returns an array of DatabaseTable objects.","title":"Expected value"},{"location":"package/pip/database/#naming-convention","text":"The PHP script is deployed by using the file package installation plugin . To prevent it from colliding with other install script (remember: You cannot overwrite files created by another plugin), we highly recommend to make use of these naming conventions: Installation: acp/database/install_<package>.php (example: acp/database/install_com.woltlab.wbb.php ) Update: acp/database/update_<package>_<targetVersion>.php (example: acp/database/update_com.woltlab.wbb_5.4.1.php ) <targetVersion> equals the version number of the current package being installed. If you're updating from 1.0.0 to 1.0.1 , <targetVersion> should read 1.0.1 . If you run multiple update scripts, you can append additional information in the filename.","title":"Naming convention"},{"location":"package/pip/database/#execution-environment","text":"The script is included using include() within DatabasePackageInstallationPlugin::updateDatabase() .","title":"Execution environment"},{"location":"package/pip/event-listener/","text":"Event Listener Package Installation Plugin # Registers event listeners. An explanation of events and event listeners can be found here . Components # Each event listener is described as an <eventlistener> element with a name attribute. As the name attribute has only be introduced with WSC 3.0, it is not yet mandatory to allow backwards compatibility. If name is not given, the system automatically sets the name based on the id of the event listener in the database. <eventclassname> # The event class name is the name of the class in which the event is fired. <eventname> # The event name is the name given when the event is fired to identify different events within the same class. You can either give a single event name or a comma-separated list of event names in which case the event listener listens to all of the listed events. Since the introduction of the new event system with version 5.5 , the event name is optional and defaults to :default . <listenerclassname> # The listener class name is the name of the class which is triggered if the relevant event is fired. The PHP class has to implement the wcf\\system\\event\\listener\\IParameterizedEventListener interface. Legacy event listeners are only required to implement the deprecated wcf\\system\\event\\IEventListener interface. When writing new code or update existing code, you should always implement the wcf\\system\\event\\listener\\IParameterizedEventListener interface! <inherit> # The inherit value can either be 0 (default value if the element is omitted) or 1 and determines if the event listener is also triggered for child classes of the given event class name. This is the case if 1 is used as the value. <environment> # The value of the environment element must be one of user , admin or all and defaults to user if no value is given. The value determines if the event listener will be executed in the frontend ( user ), the backend ( admin ) or both ( all ). <nice> # The nice value element can contain an integer value out of the interval [-128,127] with 0 being the default value if the element is omitted. The nice value determines the execution order of event listeners. Event listeners with smaller nice values are executed first. If the nice value of two event listeners is equal, they are sorted by the listener class name. If you pass a value out of the mentioned interval, the value will be adjusted to the closest value in the interval. <options> # The options element can contain a comma-separated list of options of which at least one needs to be enabled for the event listener to be executed. <permissions> # The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the event listener to be executed. Example # eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/eventListener.xsd\" > <import> <eventlistener name= \"inheritedAdminExample\" > <eventclassname> wcf\\acp\\form\\UserAddForm </eventclassname> <eventname> assignVariables,readFormParameters,save,validate </eventname> <listenerclassname> wcf\\system\\event\\listener\\InheritedAdminExampleListener </listenerclassname> <inherit> 1 </inherit> <environment> admin </environment> </eventlistener> <eventlistener name= \"nonInheritedUserExample\" > <eventclassname> wcf\\form\\SettingsForm </eventclassname> <eventname> assignVariables </eventname> <listenerclassname> wcf\\system\\event\\listener\\NonInheritedUserExampleListener </listenerclassname> </eventlistener> </import> <delete> <eventlistener name= \"oldEventListenerName\" /> </delete> </data>","title":"eventListener"},{"location":"package/pip/event-listener/#event-listener-package-installation-plugin","text":"Registers event listeners. An explanation of events and event listeners can be found here .","title":"Event Listener Package Installation Plugin"},{"location":"package/pip/event-listener/#components","text":"Each event listener is described as an <eventlistener> element with a name attribute. As the name attribute has only be introduced with WSC 3.0, it is not yet mandatory to allow backwards compatibility. If name is not given, the system automatically sets the name based on the id of the event listener in the database.","title":"Components"},{"location":"package/pip/event-listener/#eventclassname","text":"The event class name is the name of the class in which the event is fired.","title":"<eventclassname>"},{"location":"package/pip/event-listener/#eventname","text":"The event name is the name given when the event is fired to identify different events within the same class. You can either give a single event name or a comma-separated list of event names in which case the event listener listens to all of the listed events. Since the introduction of the new event system with version 5.5 , the event name is optional and defaults to :default .","title":"<eventname>"},{"location":"package/pip/event-listener/#listenerclassname","text":"The listener class name is the name of the class which is triggered if the relevant event is fired. The PHP class has to implement the wcf\\system\\event\\listener\\IParameterizedEventListener interface. Legacy event listeners are only required to implement the deprecated wcf\\system\\event\\IEventListener interface. When writing new code or update existing code, you should always implement the wcf\\system\\event\\listener\\IParameterizedEventListener interface!","title":"<listenerclassname>"},{"location":"package/pip/event-listener/#inherit","text":"The inherit value can either be 0 (default value if the element is omitted) or 1 and determines if the event listener is also triggered for child classes of the given event class name. This is the case if 1 is used as the value.","title":"<inherit>"},{"location":"package/pip/event-listener/#environment","text":"The value of the environment element must be one of user , admin or all and defaults to user if no value is given. The value determines if the event listener will be executed in the frontend ( user ), the backend ( admin ) or both ( all ).","title":"<environment>"},{"location":"package/pip/event-listener/#nice","text":"The nice value element can contain an integer value out of the interval [-128,127] with 0 being the default value if the element is omitted. The nice value determines the execution order of event listeners. Event listeners with smaller nice values are executed first. If the nice value of two event listeners is equal, they are sorted by the listener class name. If you pass a value out of the mentioned interval, the value will be adjusted to the closest value in the interval.","title":"<nice>"},{"location":"package/pip/event-listener/#options","text":"The options element can contain a comma-separated list of options of which at least one needs to be enabled for the event listener to be executed.","title":"<options>"},{"location":"package/pip/event-listener/#permissions","text":"The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the event listener to be executed.","title":"<permissions>"},{"location":"package/pip/event-listener/#example","text":"eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/eventListener.xsd\" > <import> <eventlistener name= \"inheritedAdminExample\" > <eventclassname> wcf\\acp\\form\\UserAddForm </eventclassname> <eventname> assignVariables,readFormParameters,save,validate </eventname> <listenerclassname> wcf\\system\\event\\listener\\InheritedAdminExampleListener </listenerclassname> <inherit> 1 </inherit> <environment> admin </environment> </eventlistener> <eventlistener name= \"nonInheritedUserExample\" > <eventclassname> wcf\\form\\SettingsForm </eventclassname> <eventname> assignVariables </eventname> <listenerclassname> wcf\\system\\event\\listener\\NonInheritedUserExampleListener </listenerclassname> </eventlistener> </import> <delete> <eventlistener name= \"oldEventListenerName\" /> </delete> </data>","title":"Example"},{"location":"package/pip/file-delete/","text":"File Delete Package Installation Plugin # Available since WoltLab Suite 5.5. Deletes files installed with the file package installation plugin. You cannot delete files provided by other packages. Components # Each item is described as a <file> element with an optional application , which behaves like it does for acp templates . The file path is relative to the installation of the app to which the file belongs. Example # fileDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/fileDelete.xsd\" > <delete> <file> path/file.ext </file> <file application= \"app\" > lib/data/foo/Fou.class.php </file> </delete> </data>","title":"fileDelete"},{"location":"package/pip/file-delete/#file-delete-package-installation-plugin","text":"Available since WoltLab Suite 5.5. Deletes files installed with the file package installation plugin. You cannot delete files provided by other packages.","title":"File Delete Package Installation Plugin"},{"location":"package/pip/file-delete/#components","text":"Each item is described as a <file> element with an optional application , which behaves like it does for acp templates . The file path is relative to the installation of the app to which the file belongs.","title":"Components"},{"location":"package/pip/file-delete/#example","text":"fileDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/fileDelete.xsd\" > <delete> <file> path/file.ext </file> <file application= \"app\" > lib/data/foo/Fou.class.php </file> </delete> </data>","title":"Example"},{"location":"package/pip/file/","text":"File Package Installation Plugin # Adds any type of files with the exception of templates. You cannot overwrite files provided by other packages. The application attribute behaves like it does for acp templates . Archive # The acpTemplate package installation plugins expects a .tar (recommended) or .tar.gz archive. The file path given in the instruction element as its value must be relative to the package.xml file. Example in package.xml # 1 2 3 4 5 6 7 8 9 10 <instruction type= \"file\" /> <!-- is the same as --> <instruction type= \"file\" > files.tar </instruction> <!-- if an application \"com.woltlab.example\" is being installed, the following lines are equivalent --> <instruction type= \"file\" /> <instruction type= \"file\" application= \"example\" /> <!-- if the same application wants to install additional files, in WoltLab Suite Core's directory: --> <instruction type= \"file\" application= \"wcf\" > files_wcf.tar </instruction>","title":"file"},{"location":"package/pip/file/#file-package-installation-plugin","text":"Adds any type of files with the exception of templates. You cannot overwrite files provided by other packages. The application attribute behaves like it does for acp templates .","title":"File Package Installation Plugin"},{"location":"package/pip/file/#archive","text":"The acpTemplate package installation plugins expects a .tar (recommended) or .tar.gz archive. The file path given in the instruction element as its value must be relative to the package.xml file.","title":"Archive"},{"location":"package/pip/file/#example-in-packagexml","text":"1 2 3 4 5 6 7 8 9 10 <instruction type= \"file\" /> <!-- is the same as --> <instruction type= \"file\" > files.tar </instruction> <!-- if an application \"com.woltlab.example\" is being installed, the following lines are equivalent --> <instruction type= \"file\" /> <instruction type= \"file\" application= \"example\" /> <!-- if the same application wants to install additional files, in WoltLab Suite Core's directory: --> <instruction type= \"file\" application= \"wcf\" > files_wcf.tar </instruction>","title":"Example in package.xml"},{"location":"package/pip/language/","text":"Language Package Installation Plugin # Registers new language items. Components # The languagecode attribute is required and should specify the ISO-639-1 language code. The top level <language> node must contain a languagecode attribute. <category> # Each category must contain a name attribute containing two or three components consisting of alphanumeric character only, separated by a single full stop ( . , U+002E). <item> # Each language item must contain a name attribute containing at least three components consisting of alphanumeric character only, separated by a single full stop ( . , U+002E). The name of the parent <category> node followed by a full stop must be a prefix of the <item> \u2019s name . Wrap the text content inside a CDATA to avoid escaping of special characters. Do not use the {lang} tag inside a language item. The text content of the <item> node is the value of the language item. Language items that are not in the wcf.global category support template scripting. Example # Prior to version 5.5, there was no support for deleting language items and the category elements had to be placed directly as children of the language element, see the migration guide to version 5.5 . language/en.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/language.xsd\" languagecode= \"en\" > <import> <category name= \"wcf.example\" > <item name= \"wcf.example.foo\" > <![CDATA[<strong>Look!</strong>]]> </item> </category> </import> <delete> <item name= \"wcf.example.obsolete\" /> </delete> </language>","title":"language"},{"location":"package/pip/language/#language-package-installation-plugin","text":"Registers new language items.","title":"Language Package Installation Plugin"},{"location":"package/pip/language/#components","text":"The languagecode attribute is required and should specify the ISO-639-1 language code. The top level <language> node must contain a languagecode attribute.","title":"Components"},{"location":"package/pip/language/#category","text":"Each category must contain a name attribute containing two or three components consisting of alphanumeric character only, separated by a single full stop ( . , U+002E).","title":"<category>"},{"location":"package/pip/language/#item","text":"Each language item must contain a name attribute containing at least three components consisting of alphanumeric character only, separated by a single full stop ( . , U+002E). The name of the parent <category> node followed by a full stop must be a prefix of the <item> \u2019s name . Wrap the text content inside a CDATA to avoid escaping of special characters. Do not use the {lang} tag inside a language item. The text content of the <item> node is the value of the language item. Language items that are not in the wcf.global category support template scripting.","title":"<item>"},{"location":"package/pip/language/#example","text":"Prior to version 5.5, there was no support for deleting language items and the category elements had to be placed directly as children of the language element, see the migration guide to version 5.5 . language/en.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/language.xsd\" languagecode= \"en\" > <import> <category name= \"wcf.example\" > <item name= \"wcf.example.foo\" > <![CDATA[<strong>Look!</strong>]]> </item> </category> </import> <delete> <item name= \"wcf.example.obsolete\" /> </delete> </language>","title":"Example"},{"location":"package/pip/media-provider/","text":"Media Provider Package Installation Plugin # Media providers are responsible to detect and convert links to a 3rd party service inside messages. Components # Each item is described as a <provider> element with the mandatory attribute name that should equal the lower-cased provider name. If a provider provides multiple components that are (largely) unrelated to each other, it is recommended to use a dash to separate the name and the component, e. g. youtube-playlist . <title> # The title is displayed in the administration control panel and is only used there, the value is neither localizable nor is it ever exposed to regular users. <regex> # The regular expression used to identify links to this provider, it must not contain anchors or delimiters. It is strongly recommended to capture the primary object id using the (?P<ID>...) group. <className> # <className> and <html> are mutually exclusive. PHP-Callback-Class that is invoked to process the matched link in case that additional logic must be applied that cannot be handled through a simple replacement as defined by the <html> element. The callback-class must implement the interface \\wcf\\system\\bbcode\\media\\provider\\IBBCodeMediaProvider . <html> # <className> and <html> are mutually exclusive. Replacement HTML that gets populated using the captured matches in <regex> , variables are accessed as {$VariableName} . For example, the capture group (?P<ID>...) is accessed using {$ID} . Example # mediaProvider.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/mediaProvider.xsd\" > <import> <provider name= \"youtube\" > <title> YouTube </title> <regex> <![CDATA[https?://(?:.+?\\.)?youtu(?:\\.be/|be\\.com/(?:#/)?watch\\?(?:.*?&)?v=)(?P<ID>[a-zA-Z0-9_-]+)(?:(?:\\?|&)t=(?P<start>[0-9hms]+)$)?]]> </regex> <!-- advanced PHP callback --> <className> <![CDATA[wcf\\system\\bbcode\\media\\provider\\YouTubeBBCodeMediaProvider]]> </className> </provider> <provider name= \"youtube-playlist\" > <title> YouTube Playlist </title> <regex> <![CDATA[https?://(?:.+?\\.)?youtu(?:\\.be/|be\\.com/)playlist\\?(?:.*?&)?list=(?P<ID>[a-zA-Z0-9_-]+)]]> </regex> <!-- uses a simple HTML replacement --> <html> <![CDATA[<div class=\"videoContainer\"><iframe src=\"https://www.youtube.com/embed/videoseries?list={$ID}\" allowfullscreen></iframe></div>]]> </html> </provider> </import> <delete> <provider name= \"example\" /> </delete> </data>","title":"mediaProvider"},{"location":"package/pip/media-provider/#media-provider-package-installation-plugin","text":"Media providers are responsible to detect and convert links to a 3rd party service inside messages.","title":"Media Provider Package Installation Plugin"},{"location":"package/pip/media-provider/#components","text":"Each item is described as a <provider> element with the mandatory attribute name that should equal the lower-cased provider name. If a provider provides multiple components that are (largely) unrelated to each other, it is recommended to use a dash to separate the name and the component, e. g. youtube-playlist .","title":"Components"},{"location":"package/pip/media-provider/#title","text":"The title is displayed in the administration control panel and is only used there, the value is neither localizable nor is it ever exposed to regular users.","title":"<title>"},{"location":"package/pip/media-provider/#regex","text":"The regular expression used to identify links to this provider, it must not contain anchors or delimiters. It is strongly recommended to capture the primary object id using the (?P<ID>...) group.","title":"<regex>"},{"location":"package/pip/media-provider/#classname","text":"<className> and <html> are mutually exclusive. PHP-Callback-Class that is invoked to process the matched link in case that additional logic must be applied that cannot be handled through a simple replacement as defined by the <html> element. The callback-class must implement the interface \\wcf\\system\\bbcode\\media\\provider\\IBBCodeMediaProvider .","title":"<className>"},{"location":"package/pip/media-provider/#html","text":"<className> and <html> are mutually exclusive. Replacement HTML that gets populated using the captured matches in <regex> , variables are accessed as {$VariableName} . For example, the capture group (?P<ID>...) is accessed using {$ID} .","title":"<html>"},{"location":"package/pip/media-provider/#example","text":"mediaProvider.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/mediaProvider.xsd\" > <import> <provider name= \"youtube\" > <title> YouTube </title> <regex> <![CDATA[https?://(?:.+?\\.)?youtu(?:\\.be/|be\\.com/(?:#/)?watch\\?(?:.*?&)?v=)(?P<ID>[a-zA-Z0-9_-]+)(?:(?:\\?|&)t=(?P<start>[0-9hms]+)$)?]]> </regex> <!-- advanced PHP callback --> <className> <![CDATA[wcf\\system\\bbcode\\media\\provider\\YouTubeBBCodeMediaProvider]]> </className> </provider> <provider name= \"youtube-playlist\" > <title> YouTube Playlist </title> <regex> <![CDATA[https?://(?:.+?\\.)?youtu(?:\\.be/|be\\.com/)playlist\\?(?:.*?&)?list=(?P<ID>[a-zA-Z0-9_-]+)]]> </regex> <!-- uses a simple HTML replacement --> <html> <![CDATA[<div class=\"videoContainer\"><iframe src=\"https://www.youtube.com/embed/videoseries?list={$ID}\" allowfullscreen></iframe></div>]]> </html> </provider> </import> <delete> <provider name= \"example\" /> </delete> </data>","title":"Example"},{"location":"package/pip/menu-item/","text":"Menu Item Package Installation Plugin # Adds menu items to existing menus. Components # Each item is described as an <item> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<PageName> , e.g. com.woltlab.wcf.Dashboard . <menu> # The target menu that the item should be added to, requires the internal identifier set by creating a menu through the menu.xml . <title> # The language attribute is required and should specify the ISO-639-1 language code. The title is displayed as the link title of the menu item and can be fully customized by the administrator, thus is immutable after deployment. Supports multiple <title> elements to provide localized values. <page> # The page that the link should point to, requires the internal identifier set by creating a page through the page.xml . Example # menuItem.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/menuItem.xsd\" > <import> <item identifier= \"com.woltlab.wcf.Dashboard\" > <menu> com.woltlab.wcf.MainMenu </menu> <title language= \"de\" > Dashboard </title> <title language= \"en\" > Dashboard </title> <page> com.woltlab.wcf.Dashboard </page> </item> </import> <delete> <item identifier= \"com.woltlab.wcf.FooterLinks\" /> </delete> </data>","title":"menuItem"},{"location":"package/pip/menu-item/#menu-item-package-installation-plugin","text":"Adds menu items to existing menus.","title":"Menu Item Package Installation Plugin"},{"location":"package/pip/menu-item/#components","text":"Each item is described as an <item> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<PageName> , e.g. com.woltlab.wcf.Dashboard .","title":"Components"},{"location":"package/pip/menu-item/#menu","text":"The target menu that the item should be added to, requires the internal identifier set by creating a menu through the menu.xml .","title":"<menu>"},{"location":"package/pip/menu-item/#title","text":"The language attribute is required and should specify the ISO-639-1 language code. The title is displayed as the link title of the menu item and can be fully customized by the administrator, thus is immutable after deployment. Supports multiple <title> elements to provide localized values.","title":"<title>"},{"location":"package/pip/menu-item/#page","text":"The page that the link should point to, requires the internal identifier set by creating a page through the page.xml .","title":"<page>"},{"location":"package/pip/menu-item/#example","text":"menuItem.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/menuItem.xsd\" > <import> <item identifier= \"com.woltlab.wcf.Dashboard\" > <menu> com.woltlab.wcf.MainMenu </menu> <title language= \"de\" > Dashboard </title> <title language= \"en\" > Dashboard </title> <page> com.woltlab.wcf.Dashboard </page> </item> </import> <delete> <item identifier= \"com.woltlab.wcf.FooterLinks\" /> </delete> </data>","title":"Example"},{"location":"package/pip/menu/","text":"Menu Package Installation Plugin # Deploy and manage menus that can be placed anywhere on the site. Components # Each item is described as a <menu> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<MenuName> , e.g. com.woltlab.wcf.MainMenu . <title> # The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <title> elements. <box> # The following elements of the box PIP are supported, please refer to the documentation to learn more about them: <position> <showHeader> <visibleEverywhere> <visibilityExceptions> cssClassName Example # menu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/menu.xsd\" > <import> <menu identifier= \"com.woltlab.wcf.FooterLinks\" > <title language= \"de\" > Footer-Links </title> <title language= \"en\" > Footer Links </title> <box> <position> footer </position> <cssClassName> boxMenuLinkGroup </cssClassName> <showHeader> 0 </showHeader> <visibleEverywhere> 1 </visibleEverywhere> </box> </menu> </import> <delete> <menu identifier= \"com.woltlab.wcf.FooterLinks\" /> </delete> </data>","title":"menu"},{"location":"package/pip/menu/#menu-package-installation-plugin","text":"Deploy and manage menus that can be placed anywhere on the site.","title":"Menu Package Installation Plugin"},{"location":"package/pip/menu/#components","text":"Each item is described as a <menu> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<MenuName> , e.g. com.woltlab.wcf.MainMenu .","title":"Components"},{"location":"package/pip/menu/#title","text":"The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <title> elements.","title":"<title>"},{"location":"package/pip/menu/#box","text":"The following elements of the box PIP are supported, please refer to the documentation to learn more about them: <position> <showHeader> <visibleEverywhere> <visibilityExceptions> cssClassName","title":"<box>"},{"location":"package/pip/menu/#example","text":"menu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/menu.xsd\" > <import> <menu identifier= \"com.woltlab.wcf.FooterLinks\" > <title language= \"de\" > Footer-Links </title> <title language= \"en\" > Footer Links </title> <box> <position> footer </position> <cssClassName> boxMenuLinkGroup </cssClassName> <showHeader> 0 </showHeader> <visibleEverywhere> 1 </visibleEverywhere> </box> </menu> </import> <delete> <menu identifier= \"com.woltlab.wcf.FooterLinks\" /> </delete> </data>","title":"Example"},{"location":"package/pip/object-type-definition/","text":"Object Type Definition Package Installation Plugin # Registers an object type definition. An object type definition is a blueprint for a certain behaviour that is particularized by objectTypes . As an example: Tags can be attached to different types of content (such as forum posts or gallery images). The bulk of the work is implemented in a generalized fashion, with all the tags stored in a single database table. Certain things, such as permission checking, need to be particularized for the specific type of content, though. Thus tags (or rather \u201ctaggable content\u201d) are registered as an object type definition. Posts are then registered as an object type, implementing the \u201ctaggable content\u201d behaviour. Other types of object type definitions include attachments, likes, polls, subscriptions, or even the category system. Components # Each item is described as a <definition> element with the mandatory child <name> that should follow the naming pattern <packageIdentifier>.<definition> , e.g. com.woltlab.wcf.example . <interfacename> # Optional The name of the PHP interface objectTypes have to implement. Example # objectTypeDefinition.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectTypeDefinition.xsd\" > <import> <definition> <name> com.woltlab.wcf.example </name> <interfacename> wcf\\system\\example\\IExampleObjectType </interfacename> </definition> </import> </data>","title":"objectTypeDefinition"},{"location":"package/pip/object-type-definition/#object-type-definition-package-installation-plugin","text":"Registers an object type definition. An object type definition is a blueprint for a certain behaviour that is particularized by objectTypes . As an example: Tags can be attached to different types of content (such as forum posts or gallery images). The bulk of the work is implemented in a generalized fashion, with all the tags stored in a single database table. Certain things, such as permission checking, need to be particularized for the specific type of content, though. Thus tags (or rather \u201ctaggable content\u201d) are registered as an object type definition. Posts are then registered as an object type, implementing the \u201ctaggable content\u201d behaviour. Other types of object type definitions include attachments, likes, polls, subscriptions, or even the category system.","title":"Object Type Definition Package Installation Plugin"},{"location":"package/pip/object-type-definition/#components","text":"Each item is described as a <definition> element with the mandatory child <name> that should follow the naming pattern <packageIdentifier>.<definition> , e.g. com.woltlab.wcf.example .","title":"Components"},{"location":"package/pip/object-type-definition/#interfacename","text":"Optional The name of the PHP interface objectTypes have to implement.","title":"<interfacename>"},{"location":"package/pip/object-type-definition/#example","text":"objectTypeDefinition.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectTypeDefinition.xsd\" > <import> <definition> <name> com.woltlab.wcf.example </name> <interfacename> wcf\\system\\example\\IExampleObjectType </interfacename> </definition> </import> </data>","title":"Example"},{"location":"package/pip/object-type/","text":"Object Type Package Installation Plugin # Registers an object type. Read about object types in the objectTypeDefinition PIP. Components # Each item is described as a <type> element with the mandatory child <name> that should follow the naming pattern <packageIdentifier>.<definition> , e.g. com.woltlab.wcf.example . <definitionname> # The <name> of the objectTypeDefinition . <classname> # The name of the class providing the object types's behaviour, the class has to implement the <interfacename> interface of the object type definition. <*> # Optional Additional fields may be defined for specific definitions of object types. Refer to the documentation of these for further explanation. Example # objectType.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectType.xsd\" > <import> <type> <name> com.woltlab.wcf.example </name> <definitionname> com.woltlab.wcf.rebuildData </definitionname> <classname> wcf\\system\\worker\\ExampleRebuildWorker </classname> <nicevalue> 130 </nicevalue> </type> </import> </data>","title":"objectType"},{"location":"package/pip/object-type/#object-type-package-installation-plugin","text":"Registers an object type. Read about object types in the objectTypeDefinition PIP.","title":"Object Type Package Installation Plugin"},{"location":"package/pip/object-type/#components","text":"Each item is described as a <type> element with the mandatory child <name> that should follow the naming pattern <packageIdentifier>.<definition> , e.g. com.woltlab.wcf.example .","title":"Components"},{"location":"package/pip/object-type/#definitionname","text":"The <name> of the objectTypeDefinition .","title":"<definitionname>"},{"location":"package/pip/object-type/#classname","text":"The name of the class providing the object types's behaviour, the class has to implement the <interfacename> interface of the object type definition.","title":"<classname>"},{"location":"package/pip/object-type/#_1","text":"Optional Additional fields may be defined for specific definitions of object types. Refer to the documentation of these for further explanation.","title":"<*>"},{"location":"package/pip/object-type/#example","text":"objectType.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectType.xsd\" > <import> <type> <name> com.woltlab.wcf.example </name> <definitionname> com.woltlab.wcf.rebuildData </definitionname> <classname> wcf\\system\\worker\\ExampleRebuildWorker </classname> <nicevalue> 130 </nicevalue> </type> </import> </data>","title":"Example"},{"location":"package/pip/option/","text":"Option Package Installation Plugin # Registers new options. Options allow the administrator to configure the behaviour of installed packages. The specified values are exposed as PHP constants. Category Components # Each category is described as an <category> element with the mandatory attribute name . <parent> # Optional The category\u2019s parent category. <showorder> # Optional Specifies the order of this option within the parent category. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the category to be shown to the administrator. Option Components # Each option is described as an <option> element with the mandatory attribute name . The name is transformed into a PHP constant name by uppercasing it. <categoryname> # The option\u2019s category. <optiontype> # The type of input to be used for this option. Valid types are defined by the wcf\\system\\option\\*OptionType classes. <defaultvalue> # The value that is set after installation of a package. Valid values are defined by the optiontype . <validationpattern> # Optional Defines a regular expression that is used to validate the value of a free form option (such as text ). <showorder> # Optional Specifies the order of this option within the category. <selectoptions> # Optional Defined only for select , multiSelect and radioButton types. Specifies a newline-separated list of selectable values. Each line consists of an internal handle, followed by a colon ( : , U+003A), followed by a language item. The language item is shown to the administrator, the internal handle is what is saved and exposed to the code. <enableoptions> # Optional Defined only for boolean , select and radioButton types. Specifies a comma-separated list of options which should be visually enabled when this option is enabled. A leading exclamation mark ( ! , U+0021) will disable the specified option when this option is enabled. For select and radioButton types the list should be prefixed by the internal selectoptions handle followed by a colon ( : , U+003A). This setting is a visual helper for the administrator only. It does not have an effect on the server side processing of the option. <hidden> # Optional If hidden is set to 1 the option will not be shown to the administrator. It still can be modified programmatically. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the option to be shown to the administrator. <supporti18n> # Optional Specifies whether this option supports localized input. <requirei18n> # Optional Specifies whether this option requires localized input (i.e. the administrator must specify a value for every installed language). <*> # Optional Additional fields may be defined by specific types of options. Refer to the documentation of these for further explanation. Language Items # All relevant language items have to be put into the wcf.acp.option language item category. Categories # If you install a category named example.sub , you have to provide the language item wcf.acp.option.category.example.sub , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.acp.option.category.example.sub.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level. Options # If you install an option named module_example , you have to provide the language item wcf.acp.option.module_example , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.acp.option.module_example.description . Example # option.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/option.xsd\" > <import> <categories> <category name= \"example\" /> <category name= \"example.sub\" > <parent> example </parent> <options> module_example </options> </category> </categories> <options> <option name= \"module_example\" > <categoryname> module.community </categoryname> <optiontype> boolean </optiontype> <defaultvalue> 1 </defaultvalue> </option> <option name= \"example_integer\" > <categoryname> example.sub </categoryname> <optiontype> integer </optiontype> <defaultvalue> 10 </defaultvalue> <minvalue> 5 </minvalue> <maxvalue> 40 </maxvalue> </option> <option name= \"example_select\" > <categoryname> example.sub </categoryname> <optiontype> select </optiontype> <defaultvalue> DESC </defaultvalue> <selectoptions> ASC:wcf.global.sortOrder.ascending DESC:wcf.global.sortOrder.descending </selectoptions> </option> </options> </import> <delete> <option name= \"outdated_example\" /> </delete> </data>","title":"option"},{"location":"package/pip/option/#option-package-installation-plugin","text":"Registers new options. Options allow the administrator to configure the behaviour of installed packages. The specified values are exposed as PHP constants.","title":"Option Package Installation Plugin"},{"location":"package/pip/option/#category-components","text":"Each category is described as an <category> element with the mandatory attribute name .","title":"Category Components"},{"location":"package/pip/option/#parent","text":"Optional The category\u2019s parent category.","title":"<parent>"},{"location":"package/pip/option/#showorder","text":"Optional Specifies the order of this option within the parent category.","title":"<showorder>"},{"location":"package/pip/option/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the category to be shown to the administrator.","title":"<options>"},{"location":"package/pip/option/#option-components","text":"Each option is described as an <option> element with the mandatory attribute name . The name is transformed into a PHP constant name by uppercasing it.","title":"Option Components"},{"location":"package/pip/option/#categoryname","text":"The option\u2019s category.","title":"<categoryname>"},{"location":"package/pip/option/#optiontype","text":"The type of input to be used for this option. Valid types are defined by the wcf\\system\\option\\*OptionType classes.","title":"<optiontype>"},{"location":"package/pip/option/#defaultvalue","text":"The value that is set after installation of a package. Valid values are defined by the optiontype .","title":"<defaultvalue>"},{"location":"package/pip/option/#validationpattern","text":"Optional Defines a regular expression that is used to validate the value of a free form option (such as text ).","title":"<validationpattern>"},{"location":"package/pip/option/#showorder_1","text":"Optional Specifies the order of this option within the category.","title":"<showorder>"},{"location":"package/pip/option/#selectoptions","text":"Optional Defined only for select , multiSelect and radioButton types. Specifies a newline-separated list of selectable values. Each line consists of an internal handle, followed by a colon ( : , U+003A), followed by a language item. The language item is shown to the administrator, the internal handle is what is saved and exposed to the code.","title":"<selectoptions>"},{"location":"package/pip/option/#enableoptions","text":"Optional Defined only for boolean , select and radioButton types. Specifies a comma-separated list of options which should be visually enabled when this option is enabled. A leading exclamation mark ( ! , U+0021) will disable the specified option when this option is enabled. For select and radioButton types the list should be prefixed by the internal selectoptions handle followed by a colon ( : , U+003A). This setting is a visual helper for the administrator only. It does not have an effect on the server side processing of the option.","title":"<enableoptions>"},{"location":"package/pip/option/#hidden","text":"Optional If hidden is set to 1 the option will not be shown to the administrator. It still can be modified programmatically.","title":"<hidden>"},{"location":"package/pip/option/#options_1","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the option to be shown to the administrator.","title":"<options>"},{"location":"package/pip/option/#supporti18n","text":"Optional Specifies whether this option supports localized input.","title":"<supporti18n>"},{"location":"package/pip/option/#requirei18n","text":"Optional Specifies whether this option requires localized input (i.e. the administrator must specify a value for every installed language).","title":"<requirei18n>"},{"location":"package/pip/option/#_1","text":"Optional Additional fields may be defined by specific types of options. Refer to the documentation of these for further explanation.","title":"<*>"},{"location":"package/pip/option/#language-items","text":"All relevant language items have to be put into the wcf.acp.option language item category.","title":"Language Items"},{"location":"package/pip/option/#categories","text":"If you install a category named example.sub , you have to provide the language item wcf.acp.option.category.example.sub , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.acp.option.category.example.sub.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level.","title":"Categories"},{"location":"package/pip/option/#options_2","text":"If you install an option named module_example , you have to provide the language item wcf.acp.option.module_example , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.acp.option.module_example.description .","title":"Options"},{"location":"package/pip/option/#example","text":"option.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/option.xsd\" > <import> <categories> <category name= \"example\" /> <category name= \"example.sub\" > <parent> example </parent> <options> module_example </options> </category> </categories> <options> <option name= \"module_example\" > <categoryname> module.community </categoryname> <optiontype> boolean </optiontype> <defaultvalue> 1 </defaultvalue> </option> <option name= \"example_integer\" > <categoryname> example.sub </categoryname> <optiontype> integer </optiontype> <defaultvalue> 10 </defaultvalue> <minvalue> 5 </minvalue> <maxvalue> 40 </maxvalue> </option> <option name= \"example_select\" > <categoryname> example.sub </categoryname> <optiontype> select </optiontype> <defaultvalue> DESC </defaultvalue> <selectoptions> ASC:wcf.global.sortOrder.ascending DESC:wcf.global.sortOrder.descending </selectoptions> </option> </options> </import> <delete> <option name= \"outdated_example\" /> </delete> </data>","title":"Example"},{"location":"package/pip/page/","text":"Page Package Installation Plugin # Registers page controllers, making them available for selection and configuration, including but not limited to boxes and menus. Components # Each item is described as a <page> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<PageName> , e.g. com.woltlab.wcf.MembersList . <pageType> # system # The special system type is reserved for pages that pull their properties and content from a registered PHP class. Requires the <controller> element. html , text or tpl # Provide arbitrary content, requires the <content> element. <controller> # Fully qualified class name for the controller, must implement wcf\\page\\IPage or wcf\\form\\IForm . <handler> # Fully qualified class name that can be optionally set to provide additional methods, such as displaying a badge for unread content and verifying permissions per page object id. <name> # The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <name> elements. <parent> # Sets the default parent page using its internal identifier, this setting controls the breadcrumbs and active menu item hierarchy. <hasFixedParent> # Pages can be assigned any other page as parent page by default, set to 1 to make the parent setting immutable. <permissions> # The comma represents a logical or , the check is successful if at least one permission is set. Comma separated list of permission names that will be checked one after another until at least one permission is set. <options> # The comma represents a logical or , the check is successful if at least one option is enabled. Comma separated list of options that will be checked one after another until at least one option is set. <excludeFromLandingPage> # Some pages should not be used as landing page, because they may not always be available and/or accessible to the user. For example, the account management page is available to logged-in users only and any guest attempting to visit that page would be presented with a permission denied message. Set this to 1 to prevent this page from becoming a landing page ever. <requireObjectID> # If the page requires an id of a specific object, like the user profile page requires the id of the user whose profile page is requested, <requireObjectID>1</requireObjectID> has to be added. If this item is not present, requireObjectID defaults to 0 . <availableDuringOfflineMode> # During offline mode, most pages should generally not be available. Certain pages, however, might still have to be accessible due to, for example, legal reasons. To make a page available during offline mode, <availableDuringOfflineMode>1</availableDuringOfflineMode> has to be added. If this item is not present, availableDuringOfflineMode defaults to 0 . <allowSpidersToIndex> # Administrators are able to set in the admin panel for each page, whether or not spiders are allowed to index it. The default value for this option can be set with the allowSpidersToIndex item whose value defaults to 0 . <cssClassName> # To add custom CSS classes to a page\u2019s <body> HTML element, you can specify them via the cssClassName item. If you want to add multiple CSS classes, separate them with spaces! <content> # The language attribute is required and should specify the ISO-639-1 language code. <title> # The title element is required and controls the page title shown to the end users. <content> # The content that should be used to populate the page, only used and required if the pageType equals text , html and tpl . Example # page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.MembersList\" > <pageType> system </pageType> <controller> wcf\\page\\MembersListPage </controller> <name language= \"de\" > Mitglieder </name> <name language= \"en\" > Members </name> <options> module_members_list </options> <permissions> user.profile.canViewMembersList </permissions> <allowSpidersToIndex> 1 </allowSpidersToIndex> <content language= \"en\" > <title> Members </title> </content> <content language= \"de\" > <title> Mitglieder </title> </content> </page> </import> <delete> <page identifier= \"com.woltlab.wcf.MembersList\" /> </delete> </data>","title":"page"},{"location":"package/pip/page/#page-package-installation-plugin","text":"Registers page controllers, making them available for selection and configuration, including but not limited to boxes and menus.","title":"Page Package Installation Plugin"},{"location":"package/pip/page/#components","text":"Each item is described as a <page> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<PageName> , e.g. com.woltlab.wcf.MembersList .","title":"Components"},{"location":"package/pip/page/#pagetype","text":"","title":"<pageType>"},{"location":"package/pip/page/#system","text":"The special system type is reserved for pages that pull their properties and content from a registered PHP class. Requires the <controller> element.","title":"system"},{"location":"package/pip/page/#html-text-or-tpl","text":"Provide arbitrary content, requires the <content> element.","title":"html, text or tpl"},{"location":"package/pip/page/#controller","text":"Fully qualified class name for the controller, must implement wcf\\page\\IPage or wcf\\form\\IForm .","title":"<controller>"},{"location":"package/pip/page/#handler","text":"Fully qualified class name that can be optionally set to provide additional methods, such as displaying a badge for unread content and verifying permissions per page object id.","title":"<handler>"},{"location":"package/pip/page/#name","text":"The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <name> elements.","title":"<name>"},{"location":"package/pip/page/#parent","text":"Sets the default parent page using its internal identifier, this setting controls the breadcrumbs and active menu item hierarchy.","title":"<parent>"},{"location":"package/pip/page/#hasfixedparent","text":"Pages can be assigned any other page as parent page by default, set to 1 to make the parent setting immutable.","title":"<hasFixedParent>"},{"location":"package/pip/page/#permissions","text":"The comma represents a logical or , the check is successful if at least one permission is set. Comma separated list of permission names that will be checked one after another until at least one permission is set.","title":"<permissions>"},{"location":"package/pip/page/#options","text":"The comma represents a logical or , the check is successful if at least one option is enabled. Comma separated list of options that will be checked one after another until at least one option is set.","title":"<options>"},{"location":"package/pip/page/#excludefromlandingpage","text":"Some pages should not be used as landing page, because they may not always be available and/or accessible to the user. For example, the account management page is available to logged-in users only and any guest attempting to visit that page would be presented with a permission denied message. Set this to 1 to prevent this page from becoming a landing page ever.","title":"<excludeFromLandingPage>"},{"location":"package/pip/page/#requireobjectid","text":"If the page requires an id of a specific object, like the user profile page requires the id of the user whose profile page is requested, <requireObjectID>1</requireObjectID> has to be added. If this item is not present, requireObjectID defaults to 0 .","title":"<requireObjectID>"},{"location":"package/pip/page/#availableduringofflinemode","text":"During offline mode, most pages should generally not be available. Certain pages, however, might still have to be accessible due to, for example, legal reasons. To make a page available during offline mode, <availableDuringOfflineMode>1</availableDuringOfflineMode> has to be added. If this item is not present, availableDuringOfflineMode defaults to 0 .","title":"<availableDuringOfflineMode>"},{"location":"package/pip/page/#allowspiderstoindex","text":"Administrators are able to set in the admin panel for each page, whether or not spiders are allowed to index it. The default value for this option can be set with the allowSpidersToIndex item whose value defaults to 0 .","title":"<allowSpidersToIndex>"},{"location":"package/pip/page/#cssclassname","text":"To add custom CSS classes to a page\u2019s <body> HTML element, you can specify them via the cssClassName item. If you want to add multiple CSS classes, separate them with spaces!","title":"<cssClassName>"},{"location":"package/pip/page/#content","text":"The language attribute is required and should specify the ISO-639-1 language code.","title":"<content>"},{"location":"package/pip/page/#title","text":"The title element is required and controls the page title shown to the end users.","title":"<title>"},{"location":"package/pip/page/#content_1","text":"The content that should be used to populate the page, only used and required if the pageType equals text , html and tpl .","title":"<content>"},{"location":"package/pip/page/#example","text":"page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.MembersList\" > <pageType> system </pageType> <controller> wcf\\page\\MembersListPage </controller> <name language= \"de\" > Mitglieder </name> <name language= \"en\" > Members </name> <options> module_members_list </options> <permissions> user.profile.canViewMembersList </permissions> <allowSpidersToIndex> 1 </allowSpidersToIndex> <content language= \"en\" > <title> Members </title> </content> <content language= \"de\" > <title> Mitglieder </title> </content> </page> </import> <delete> <page identifier= \"com.woltlab.wcf.MembersList\" /> </delete> </data>","title":"Example"},{"location":"package/pip/pip/","text":"Package Installation Plugin Package Installation Plugin # Registers new package installation plugins. Components # Each package installation plugin is described as an <pip> element with a name attribute and a PHP classname as the text content. The package installation plugin\u2019s class file must be installed into the wcf application and must not include classes outside the \\wcf\\* hierarchy to allow for proper uninstallation! Example # packageInstallationPlugin.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/packageInstallationPlugin.xsd\" > <import> <pip name= \"custom\" > wcf\\system\\package\\plugin\\CustomPackageInstallationPlugin </pip> </import> <delete> <pip name= \"outdated\" /> </delete> </data>","title":"pip"},{"location":"package/pip/pip/#package-installation-plugin-package-installation-plugin","text":"Registers new package installation plugins.","title":"Package Installation Plugin Package Installation Plugin"},{"location":"package/pip/pip/#components","text":"Each package installation plugin is described as an <pip> element with a name attribute and a PHP classname as the text content. The package installation plugin\u2019s class file must be installed into the wcf application and must not include classes outside the \\wcf\\* hierarchy to allow for proper uninstallation!","title":"Components"},{"location":"package/pip/pip/#example","text":"packageInstallationPlugin.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/packageInstallationPlugin.xsd\" > <import> <pip name= \"custom\" > wcf\\system\\package\\plugin\\CustomPackageInstallationPlugin </pip> </import> <delete> <pip name= \"outdated\" /> </delete> </data>","title":"Example"},{"location":"package/pip/script/","text":"Script Package Installation Plugin # Execute arbitrary PHP code during installation, update and uninstallation of the package. You must install the PHP script through the file package installation plugin . The installation will attempt to delete the script after successful execution. Attributes # application # The application attribute must have the same value as the application attribute of the file package installation plugin instruction so that the correct file in the intended application directory is executed. For further information about the application attribute, refer to its documentation on the acpTemplate package installation plugin page . Expected value # The script -PIP expects a relative path to a .php file. Naming convention # The PHP script is deployed by using the file package installation plugin . To prevent it from colliding with other install script (remember: You cannot overwrite files created by another plugin), we highly recommend to make use of these naming conventions: Installation: install_<package>.php (example: install_com.woltlab.wbb.php ) Update: update_<package>_<targetVersion>.php (example: update_com.woltlab.wbb_5.0.0_pl_1.php ) <targetVersion> equals the version number of the current package being installed. If you're updating from 1.0.0 to 1.0.1 , <targetVersion> should read 1.0.1 . Execution environment # The script is included using include() within ScriptPackageInstallationPlugin::run() . This grants you access to the class members, including $this->installation . You can retrieve the package id of the current package through $this->installation->getPackageID() .","title":"script"},{"location":"package/pip/script/#script-package-installation-plugin","text":"Execute arbitrary PHP code during installation, update and uninstallation of the package. You must install the PHP script through the file package installation plugin . The installation will attempt to delete the script after successful execution.","title":"Script Package Installation Plugin"},{"location":"package/pip/script/#attributes","text":"","title":"Attributes"},{"location":"package/pip/script/#application","text":"The application attribute must have the same value as the application attribute of the file package installation plugin instruction so that the correct file in the intended application directory is executed. For further information about the application attribute, refer to its documentation on the acpTemplate package installation plugin page .","title":"application"},{"location":"package/pip/script/#expected-value","text":"The script -PIP expects a relative path to a .php file.","title":"Expected value"},{"location":"package/pip/script/#naming-convention","text":"The PHP script is deployed by using the file package installation plugin . To prevent it from colliding with other install script (remember: You cannot overwrite files created by another plugin), we highly recommend to make use of these naming conventions: Installation: install_<package>.php (example: install_com.woltlab.wbb.php ) Update: update_<package>_<targetVersion>.php (example: update_com.woltlab.wbb_5.0.0_pl_1.php ) <targetVersion> equals the version number of the current package being installed. If you're updating from 1.0.0 to 1.0.1 , <targetVersion> should read 1.0.1 .","title":"Naming convention"},{"location":"package/pip/script/#execution-environment","text":"The script is included using include() within ScriptPackageInstallationPlugin::run() . This grants you access to the class members, including $this->installation . You can retrieve the package id of the current package through $this->installation->getPackageID() .","title":"Execution environment"},{"location":"package/pip/smiley/","text":"Smiley Package Installation Plugin # Installs new smileys. Components # Each smiley is described as an <smiley> element with the mandatory attribute name . <title> # Short human readable description of the smiley. <path(2x)?> # The files must be installed using the file PIP. File path relative to the root of WoltLab Suite Core. path2x is optional and being used for High-DPI screens. <aliases> # Optional List of smiley aliases. Aliases must be separated by a line feed character ( \\n , U+000A). <showorder> # Optional Determines at which position of the smiley list the smiley is shown. Example # smiley.xml 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/smiley.xsd\" > <import> <smiley name= \":example:\" > <title> example </title> <path> images/smilies/example.png </path> <path2x> images/smilies/example@2x.png </path2x> <aliases> <![CDATA[:alias: :more_aliases:]]> </aliases> </smiley> </import> </data>","title":"smiley"},{"location":"package/pip/smiley/#smiley-package-installation-plugin","text":"Installs new smileys.","title":"Smiley Package Installation Plugin"},{"location":"package/pip/smiley/#components","text":"Each smiley is described as an <smiley> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/smiley/#title","text":"Short human readable description of the smiley.","title":"<title>"},{"location":"package/pip/smiley/#path2x","text":"The files must be installed using the file PIP. File path relative to the root of WoltLab Suite Core. path2x is optional and being used for High-DPI screens.","title":"<path(2x)?>"},{"location":"package/pip/smiley/#aliases","text":"Optional List of smiley aliases. Aliases must be separated by a line feed character ( \\n , U+000A).","title":"<aliases>"},{"location":"package/pip/smiley/#showorder","text":"Optional Determines at which position of the smiley list the smiley is shown.","title":"<showorder>"},{"location":"package/pip/smiley/#example","text":"smiley.xml 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/smiley.xsd\" > <import> <smiley name= \":example:\" > <title> example </title> <path> images/smilies/example.png </path> <path2x> images/smilies/example@2x.png </path2x> <aliases> <![CDATA[:alias: :more_aliases:]]> </aliases> </smiley> </import> </data>","title":"Example"},{"location":"package/pip/sql/","text":"SQL Package Installation Plugin # Execute SQL instructions using a MySQL-flavored syntax. This file is parsed by WoltLab Suite Core to allow reverting of certain changes, but not every syntax MySQL supports is recognized by the parser. To avoid any troubles, you should always use statements relying on the SQL standard. Expected Value # The sql package installation plugin expects a relative path to a .sql file. Features # Logging # WoltLab Suite Core uses a SQL parser to extract queries and log certain actions. This allows WoltLab Suite Core to revert some of the changes you apply upon package uninstallation. The logged changes are: CREATE TABLE ALTER TABLE \u2026 ADD COLUMN ALTER TABLE \u2026 ADD \u2026 KEY Instance Number # It is possible to use different instance numbers, e.g. two separate WoltLab Suite Core installations within one database. WoltLab Suite Core requires you to always use wcf1_<tableName> or <app>1_<tableName> (e.g. blog1_blog in WoltLab Suite Blog), the number ( 1 ) will be automatically replaced prior to execution. If you every use anything other but 1 , you will eventually break things, thus always use 1 ! Table Type # WoltLab Suite Core will determine the type of database tables on its own: If the table contains a FULLTEXT index, it uses MyISAM , otherwise InnoDB is used. Limitations # Logging # WoltLab Suite Core cannot revert changes to the database structure which would cause to the data to be either changed or new data to be incompatible with the original format. Additionally, WoltLab Suite Core does not track regular SQL queries such as DELETE or UPDATE . Triggers # WoltLab Suite Core does not support trigger since MySQL does not support execution of triggers if the event was fired by a cascading foreign key action. If you really need triggers, you should consider adding them by custom SQL queries using a script . Example # package.xml : 1 <instruction type= \"sql\" > install.sql </instruction> Example content: install.sql 1 2 3 4 5 6 7 8 9 10 CREATE TABLE wcf1_foo_bar ( fooID INT ( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , packageID INT ( 10 ) NOT NULL , bar VARCHAR ( 255 ) NOT NULL DEFAULT '' , foobar VARCHAR ( 50 ) NOT NULL DEFAULT '' , UNIQUE KEY baz ( bar , foobar ) ); ALTER TABLE wcf1_foo_bar ADD FOREIGN KEY ( packageID ) REFERENCES wcf1_package ( packageID ) ON DELETE CASCADE ;","title":"sql"},{"location":"package/pip/sql/#sql-package-installation-plugin","text":"Execute SQL instructions using a MySQL-flavored syntax. This file is parsed by WoltLab Suite Core to allow reverting of certain changes, but not every syntax MySQL supports is recognized by the parser. To avoid any troubles, you should always use statements relying on the SQL standard.","title":"SQL Package Installation Plugin"},{"location":"package/pip/sql/#expected-value","text":"The sql package installation plugin expects a relative path to a .sql file.","title":"Expected Value"},{"location":"package/pip/sql/#features","text":"","title":"Features"},{"location":"package/pip/sql/#logging","text":"WoltLab Suite Core uses a SQL parser to extract queries and log certain actions. This allows WoltLab Suite Core to revert some of the changes you apply upon package uninstallation. The logged changes are: CREATE TABLE ALTER TABLE \u2026 ADD COLUMN ALTER TABLE \u2026 ADD \u2026 KEY","title":"Logging"},{"location":"package/pip/sql/#instance-number","text":"It is possible to use different instance numbers, e.g. two separate WoltLab Suite Core installations within one database. WoltLab Suite Core requires you to always use wcf1_<tableName> or <app>1_<tableName> (e.g. blog1_blog in WoltLab Suite Blog), the number ( 1 ) will be automatically replaced prior to execution. If you every use anything other but 1 , you will eventually break things, thus always use 1 !","title":"Instance Number"},{"location":"package/pip/sql/#table-type","text":"WoltLab Suite Core will determine the type of database tables on its own: If the table contains a FULLTEXT index, it uses MyISAM , otherwise InnoDB is used.","title":"Table Type"},{"location":"package/pip/sql/#limitations","text":"","title":"Limitations"},{"location":"package/pip/sql/#logging_1","text":"WoltLab Suite Core cannot revert changes to the database structure which would cause to the data to be either changed or new data to be incompatible with the original format. Additionally, WoltLab Suite Core does not track regular SQL queries such as DELETE or UPDATE .","title":"Logging"},{"location":"package/pip/sql/#triggers","text":"WoltLab Suite Core does not support trigger since MySQL does not support execution of triggers if the event was fired by a cascading foreign key action. If you really need triggers, you should consider adding them by custom SQL queries using a script .","title":"Triggers"},{"location":"package/pip/sql/#example","text":"package.xml : 1 <instruction type= \"sql\" > install.sql </instruction> Example content: install.sql 1 2 3 4 5 6 7 8 9 10 CREATE TABLE wcf1_foo_bar ( fooID INT ( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , packageID INT ( 10 ) NOT NULL , bar VARCHAR ( 255 ) NOT NULL DEFAULT '' , foobar VARCHAR ( 50 ) NOT NULL DEFAULT '' , UNIQUE KEY baz ( bar , foobar ) ); ALTER TABLE wcf1_foo_bar ADD FOREIGN KEY ( packageID ) REFERENCES wcf1_package ( packageID ) ON DELETE CASCADE ;","title":"Example"},{"location":"package/pip/style/","text":"Style Package Installation Plugin # Install styles during package installation. The style package installation plugins expects a relative path to a .tar file, a .tar.gz file or a .tgz file. Please use the ACP's export mechanism to export styles. Example in package.xml # 1 <instruction type= \"style\" > style.tgz </instruction>","title":"style"},{"location":"package/pip/style/#style-package-installation-plugin","text":"Install styles during package installation. The style package installation plugins expects a relative path to a .tar file, a .tar.gz file or a .tgz file. Please use the ACP's export mechanism to export styles.","title":"Style Package Installation Plugin"},{"location":"package/pip/style/#example-in-packagexml","text":"1 <instruction type= \"style\" > style.tgz </instruction>","title":"Example in package.xml"},{"location":"package/pip/template-delete/","text":"Template Delete Package Installation Plugin # Available since WoltLab Suite 5.5. Deletes frontend templates installed with the template package installation plugin. You cannot delete templates provided by other packages. Components # Each item is described as a <template> element with an optional application , which behaves like it does for acp templates . The templates are identified by their name like when adding template listeners , i.e. by the file name without the .tpl file extension. Example # templateDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/templateDelete.xsd\" > <delete> <template> fouAdd </template> <template application= \"app\" > __appAdd </template> </delete> </data>","title":"templateDelete"},{"location":"package/pip/template-delete/#template-delete-package-installation-plugin","text":"Available since WoltLab Suite 5.5. Deletes frontend templates installed with the template package installation plugin. You cannot delete templates provided by other packages.","title":"Template Delete Package Installation Plugin"},{"location":"package/pip/template-delete/#components","text":"Each item is described as a <template> element with an optional application , which behaves like it does for acp templates . The templates are identified by their name like when adding template listeners , i.e. by the file name without the .tpl file extension.","title":"Components"},{"location":"package/pip/template-delete/#example","text":"templateDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/templateDelete.xsd\" > <delete> <template> fouAdd </template> <template application= \"app\" > __appAdd </template> </delete> </data>","title":"Example"},{"location":"package/pip/template-listener/","text":"Template Listener Package Installation Plugin # Registers template listeners. Template listeners supplement event listeners , which modify server side behaviour, by adding additional template code to display additional elements. The added template code behaves as if it was part of the original template (i.e. it has access to all local variables). Components # Each event listener is described as an <templatelistener> element with a name attribute. As the name attribute has only be introduced with WSC 3.0, it is not yet mandatory to allow backwards compatibility. If name is not given, the system automatically sets the name based on the id of the event listener in the database. <templatename> # The template name is the name of the template in which the event is fired. It correspondes to the eventclassname field of event listeners. <eventname> # The event name is the name given when the event is fired to identify different events within the same template. <templatecode> # The given template code is literally copied into the target template during compile time. The original template is not modified. If multiple template listeners listen to a single event their output is concatenated using the line feed character ( \\n , U+000A) in the order defined by the niceValue . It is recommend that the only code is an {include} of a template to enable changes by the administrator. Names of templates included by a template listener start with two underscores by convention. <environment> # The value of the environment element can either be admin or user and is user if no value is given. The value determines if the template listener will be executed in the frontend ( user ) or the backend ( admin ). <nice> # Optional The nice value element can contain an integer value out of the interval [-128,127] with 0 being the default value if the element is omitted. The nice value determines the execution order of template listeners. Template listeners with smaller nice values are executed first. If the nice value of two template listeners is equal, the order is undefined. If you pass a value out of the mentioned interval, the value will be adjusted to the closest value in the interval. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the template listener to be executed. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the template listener to be executed. Example # templateListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/templatelistener.xsd\" > <import> <templatelistener name= \"example\" > <environment> user </environment> <templatename> headIncludeJavaScript </templatename> <eventname> javascriptInclude </eventname> <templatecode> <![CDATA[{include file='__myCustomJavaScript'}]]> </templatecode> </templatelistener> </import> <delete> <templatelistener name= \"oldTemplateListenerName\" > <environment> user </environment> <templatename> headIncludeJavaScript </templatename> <eventname> javascriptInclude </eventname> </templatelistener> </delete> </data>","title":"templateListener"},{"location":"package/pip/template-listener/#template-listener-package-installation-plugin","text":"Registers template listeners. Template listeners supplement event listeners , which modify server side behaviour, by adding additional template code to display additional elements. The added template code behaves as if it was part of the original template (i.e. it has access to all local variables).","title":"Template Listener Package Installation Plugin"},{"location":"package/pip/template-listener/#components","text":"Each event listener is described as an <templatelistener> element with a name attribute. As the name attribute has only be introduced with WSC 3.0, it is not yet mandatory to allow backwards compatibility. If name is not given, the system automatically sets the name based on the id of the event listener in the database.","title":"Components"},{"location":"package/pip/template-listener/#templatename","text":"The template name is the name of the template in which the event is fired. It correspondes to the eventclassname field of event listeners.","title":"<templatename>"},{"location":"package/pip/template-listener/#eventname","text":"The event name is the name given when the event is fired to identify different events within the same template.","title":"<eventname>"},{"location":"package/pip/template-listener/#templatecode","text":"The given template code is literally copied into the target template during compile time. The original template is not modified. If multiple template listeners listen to a single event their output is concatenated using the line feed character ( \\n , U+000A) in the order defined by the niceValue . It is recommend that the only code is an {include} of a template to enable changes by the administrator. Names of templates included by a template listener start with two underscores by convention.","title":"<templatecode>"},{"location":"package/pip/template-listener/#environment","text":"The value of the environment element can either be admin or user and is user if no value is given. The value determines if the template listener will be executed in the frontend ( user ) or the backend ( admin ).","title":"<environment>"},{"location":"package/pip/template-listener/#nice","text":"Optional The nice value element can contain an integer value out of the interval [-128,127] with 0 being the default value if the element is omitted. The nice value determines the execution order of template listeners. Template listeners with smaller nice values are executed first. If the nice value of two template listeners is equal, the order is undefined. If you pass a value out of the mentioned interval, the value will be adjusted to the closest value in the interval.","title":"<nice>"},{"location":"package/pip/template-listener/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the template listener to be executed.","title":"<options>"},{"location":"package/pip/template-listener/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the template listener to be executed.","title":"<permissions>"},{"location":"package/pip/template-listener/#example","text":"templateListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/templatelistener.xsd\" > <import> <templatelistener name= \"example\" > <environment> user </environment> <templatename> headIncludeJavaScript </templatename> <eventname> javascriptInclude </eventname> <templatecode> <![CDATA[{include file='__myCustomJavaScript'}]]> </templatecode> </templatelistener> </import> <delete> <templatelistener name= \"oldTemplateListenerName\" > <environment> user </environment> <templatename> headIncludeJavaScript </templatename> <eventname> javascriptInclude </eventname> </templatelistener> </delete> </data>","title":"Example"},{"location":"package/pip/template/","text":"Template Package Installation Plugin # Add templates for frontend pages and forms by providing an archive containing the template files. You cannot overwrite templates provided by other packages. This package installation plugin behaves exactly like the acpTemplate package installation plugin except for installing frontend templates instead of backend/acp templates.","title":"template"},{"location":"package/pip/template/#template-package-installation-plugin","text":"Add templates for frontend pages and forms by providing an archive containing the template files. You cannot overwrite templates provided by other packages. This package installation plugin behaves exactly like the acpTemplate package installation plugin except for installing frontend templates instead of backend/acp templates.","title":"Template Package Installation Plugin"},{"location":"package/pip/user-group-option/","text":"User Group Option Package Installation Plugin # Registers new user group options (\u201cpermissions\u201d). The behaviour of this package installation plugin closely follows the option PIP. Category Components # The category definition works exactly like the option PIP. Option Components # The fields hidden , supporti18n and requirei18n do not apply. The following extra fields are defined: <(admin|mod|user)defaultvalue> # Defines the defaultvalue s for subsets of the groups: Type Description admin Groups where the admin.user.accessibleGroups user group option includes every group. mod Groups where the mod.general.canUseModeration is set to true . user Groups where the internal group type is neither UserGroup::EVERYONE nor UserGroup::GUESTS . <usersonly> # Makes the option unavailable for groups with the group type UserGroup::GUESTS . Language Items # All relevant language items have to be put into the wcf.acp.group language item category. Categories # If you install a category named user.foo , you have to provide the language item wcf.acp.group.option.category.user.foo , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.acp.group.option.category.user.foo.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level. Options # If you install an option named user.foo.canBar , you have to provide the language item wcf.acp.group.option.user.foo.canBar , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.acp.group.option.user.foo.canBar.description .","title":"userGroupOption"},{"location":"package/pip/user-group-option/#user-group-option-package-installation-plugin","text":"Registers new user group options (\u201cpermissions\u201d). The behaviour of this package installation plugin closely follows the option PIP.","title":"User Group Option Package Installation Plugin"},{"location":"package/pip/user-group-option/#category-components","text":"The category definition works exactly like the option PIP.","title":"Category Components"},{"location":"package/pip/user-group-option/#option-components","text":"The fields hidden , supporti18n and requirei18n do not apply. The following extra fields are defined:","title":"Option Components"},{"location":"package/pip/user-group-option/#adminmoduserdefaultvalue","text":"Defines the defaultvalue s for subsets of the groups: Type Description admin Groups where the admin.user.accessibleGroups user group option includes every group. mod Groups where the mod.general.canUseModeration is set to true . user Groups where the internal group type is neither UserGroup::EVERYONE nor UserGroup::GUESTS .","title":"<(admin|mod|user)defaultvalue>"},{"location":"package/pip/user-group-option/#usersonly","text":"Makes the option unavailable for groups with the group type UserGroup::GUESTS .","title":"<usersonly>"},{"location":"package/pip/user-group-option/#language-items","text":"All relevant language items have to be put into the wcf.acp.group language item category.","title":"Language Items"},{"location":"package/pip/user-group-option/#categories","text":"If you install a category named user.foo , you have to provide the language item wcf.acp.group.option.category.user.foo , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.acp.group.option.category.user.foo.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level.","title":"Categories"},{"location":"package/pip/user-group-option/#options","text":"If you install an option named user.foo.canBar , you have to provide the language item wcf.acp.group.option.user.foo.canBar , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.acp.group.option.user.foo.canBar.description .","title":"Options"},{"location":"package/pip/user-menu/","text":"User Menu Package Installation Plugin # Registers new user menu items. Components # Each item is described as an <usermenuitem> element with the mandatory attribute name . <parent> # Optional The item\u2019s parent item. <showorder> # Optional Specifies the order of this item within the parent item. <controller> # The fully qualified class name of the target controller. If not specified this item serves as a category. <link> # Additional components if <controller> is set, the full external link otherwise. <iconclassname> # Use an icon only for top-level items. Name of the Font Awesome icon class. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the menu item to be shown. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the menu item to be shown. <classname> # The name of the class providing the user menu item\u2019s behaviour, the class has to implement the wcf\\system\\menu\\user\\IUserMenuItemProvider interface. Example # userMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userMenu.xsd\" > <import> <usermenuitem name= \"wcf.user.menu.foo\" > <iconclassname> fa-home </iconclassname> </usermenuitem> <usermenuitem name= \"wcf.user.menu.foo.bar\" > <controller> wcf\\page\\FooBarListPage </controller> <parent> wcf.user.menu.foo </parent> <permissions> user.foo.canBar </permissions> <classname> wcf\\system\\menu\\user\\FooBarMenuItemProvider </classname> </usermenuitem> <usermenuitem name= \"wcf.user.menu.foo.baz\" > <controller> wcf\\page\\FooBazListPage </controller> <parent> wcf.user.menu.foo </parent> <permissions> user.foo.canBaz </permissions> <options> module_foo_bar </options> </usermenuitem> </import> </data>","title":"userMenu"},{"location":"package/pip/user-menu/#user-menu-package-installation-plugin","text":"Registers new user menu items.","title":"User Menu Package Installation Plugin"},{"location":"package/pip/user-menu/#components","text":"Each item is described as an <usermenuitem> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/user-menu/#parent","text":"Optional The item\u2019s parent item.","title":"<parent>"},{"location":"package/pip/user-menu/#showorder","text":"Optional Specifies the order of this item within the parent item.","title":"<showorder>"},{"location":"package/pip/user-menu/#controller","text":"The fully qualified class name of the target controller. If not specified this item serves as a category.","title":"<controller>"},{"location":"package/pip/user-menu/#link","text":"Additional components if <controller> is set, the full external link otherwise.","title":"<link>"},{"location":"package/pip/user-menu/#iconclassname","text":"Use an icon only for top-level items. Name of the Font Awesome icon class.","title":"<iconclassname>"},{"location":"package/pip/user-menu/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the menu item to be shown.","title":"<options>"},{"location":"package/pip/user-menu/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the menu item to be shown.","title":"<permissions>"},{"location":"package/pip/user-menu/#classname","text":"The name of the class providing the user menu item\u2019s behaviour, the class has to implement the wcf\\system\\menu\\user\\IUserMenuItemProvider interface.","title":"<classname>"},{"location":"package/pip/user-menu/#example","text":"userMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userMenu.xsd\" > <import> <usermenuitem name= \"wcf.user.menu.foo\" > <iconclassname> fa-home </iconclassname> </usermenuitem> <usermenuitem name= \"wcf.user.menu.foo.bar\" > <controller> wcf\\page\\FooBarListPage </controller> <parent> wcf.user.menu.foo </parent> <permissions> user.foo.canBar </permissions> <classname> wcf\\system\\menu\\user\\FooBarMenuItemProvider </classname> </usermenuitem> <usermenuitem name= \"wcf.user.menu.foo.baz\" > <controller> wcf\\page\\FooBazListPage </controller> <parent> wcf.user.menu.foo </parent> <permissions> user.foo.canBaz </permissions> <options> module_foo_bar </options> </usermenuitem> </import> </data>","title":"Example"},{"location":"package/pip/user-notification-event/","text":"User Notification Event Package Installation Plugin # Registers new user notification events. Components # Each package installation plugin is described as an <event> element with the mandatory child <name> . <objectType> # The (name, objectType) pair must be unique. The given object type must implement the com.woltlab.wcf.notification.objectType definition. <classname> # The name of the class providing the event's behaviour, the class has to implement the wcf\\system\\user\\notification\\event\\IUserNotificationEvent interface. <preset> # Defines whether this event is enabled by default. <presetmailnotificationtype> # Avoid using this option, as sending unsolicited mail can be seen as spamming. One of instant or daily . Defines whether this type of email notifications is enabled by default. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the notification type to be available. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the notification type to be available. Example # userNotificationEvent.xml 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userNotificationEvent.xsd\" > <import> <event> <name> like </name> <objecttype> com.woltlab.example.comment.like.notification </objecttype> <classname> wcf\\system\\user\\notification\\event\\ExampleCommentLikeUserNotificationEvent </classname> <preset> 1 </preset> <options> module_like </options> </event> </import> </data>","title":"userNotificationEvent"},{"location":"package/pip/user-notification-event/#user-notification-event-package-installation-plugin","text":"Registers new user notification events.","title":"User Notification Event Package Installation Plugin"},{"location":"package/pip/user-notification-event/#components","text":"Each package installation plugin is described as an <event> element with the mandatory child <name> .","title":"Components"},{"location":"package/pip/user-notification-event/#objecttype","text":"The (name, objectType) pair must be unique. The given object type must implement the com.woltlab.wcf.notification.objectType definition.","title":"<objectType>"},{"location":"package/pip/user-notification-event/#classname","text":"The name of the class providing the event's behaviour, the class has to implement the wcf\\system\\user\\notification\\event\\IUserNotificationEvent interface.","title":"<classname>"},{"location":"package/pip/user-notification-event/#preset","text":"Defines whether this event is enabled by default.","title":"<preset>"},{"location":"package/pip/user-notification-event/#presetmailnotificationtype","text":"Avoid using this option, as sending unsolicited mail can be seen as spamming. One of instant or daily . Defines whether this type of email notifications is enabled by default.","title":"<presetmailnotificationtype>"},{"location":"package/pip/user-notification-event/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the notification type to be available.","title":"<options>"},{"location":"package/pip/user-notification-event/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the notification type to be available.","title":"<permissions>"},{"location":"package/pip/user-notification-event/#example","text":"userNotificationEvent.xml 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userNotificationEvent.xsd\" > <import> <event> <name> like </name> <objecttype> com.woltlab.example.comment.like.notification </objecttype> <classname> wcf\\system\\user\\notification\\event\\ExampleCommentLikeUserNotificationEvent </classname> <preset> 1 </preset> <options> module_like </options> </event> </import> </data>","title":"Example"},{"location":"package/pip/user-option/","text":"User Option Package Installation Plugin # Registers new user options (profile fields / user settings). The behaviour of this package installation plugin closely follows the option PIP. Category Components # The category definition works exactly like the option PIP. Option Components # The fields hidden , supporti18n and requirei18n do not apply. The following extra fields are defined: <required> # Requires that a value is provided. <askduringregistration> # If set to 1 the field is shown during user registration in the frontend. <editable> # Bitfield with the following options (constants in wcf\\data\\user\\option\\UserOption ) Name Value EDITABILITY_OWNER 1 EDITABILITY_ADMINISTRATOR 2 EDITABILITY_OWNER_DURING_REGISTRATION 4 <visible> # Bitfield with the following options (constants in wcf\\data\\user\\option\\UserOption ) Name Value VISIBILITY_OWNER 1 VISIBILITY_ADMINISTRATOR 2 VISIBILITY_REGISTERED 4 VISIBILITY_GUEST 8 <searchable> # If set to 1 the field is searchable. <outputclass> # PHP class responsible for output formatting of this field. the class has to implement the wcf\\system\\option\\user\\IUserOptionOutput interface. Language Items # All relevant language items have to be put into the wcf.user.option language item category. Categories # If you install a category named example , you have to provide the language item wcf.user.option.category.example , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.user.option.category.example.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level. Options # If you install an option named exampleOption , you have to provide the language item wcf.user.option.exampleOption , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.user.option.exampleOption.description .","title":"userOption"},{"location":"package/pip/user-option/#user-option-package-installation-plugin","text":"Registers new user options (profile fields / user settings). The behaviour of this package installation plugin closely follows the option PIP.","title":"User Option Package Installation Plugin"},{"location":"package/pip/user-option/#category-components","text":"The category definition works exactly like the option PIP.","title":"Category Components"},{"location":"package/pip/user-option/#option-components","text":"The fields hidden , supporti18n and requirei18n do not apply. The following extra fields are defined:","title":"Option Components"},{"location":"package/pip/user-option/#required","text":"Requires that a value is provided.","title":"<required>"},{"location":"package/pip/user-option/#askduringregistration","text":"If set to 1 the field is shown during user registration in the frontend.","title":"<askduringregistration>"},{"location":"package/pip/user-option/#editable","text":"Bitfield with the following options (constants in wcf\\data\\user\\option\\UserOption ) Name Value EDITABILITY_OWNER 1 EDITABILITY_ADMINISTRATOR 2 EDITABILITY_OWNER_DURING_REGISTRATION 4","title":"<editable>"},{"location":"package/pip/user-option/#visible","text":"Bitfield with the following options (constants in wcf\\data\\user\\option\\UserOption ) Name Value VISIBILITY_OWNER 1 VISIBILITY_ADMINISTRATOR 2 VISIBILITY_REGISTERED 4 VISIBILITY_GUEST 8","title":"<visible>"},{"location":"package/pip/user-option/#searchable","text":"If set to 1 the field is searchable.","title":"<searchable>"},{"location":"package/pip/user-option/#outputclass","text":"PHP class responsible for output formatting of this field. the class has to implement the wcf\\system\\option\\user\\IUserOptionOutput interface.","title":"<outputclass>"},{"location":"package/pip/user-option/#language-items","text":"All relevant language items have to be put into the wcf.user.option language item category.","title":"Language Items"},{"location":"package/pip/user-option/#categories","text":"If you install a category named example , you have to provide the language item wcf.user.option.category.example , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.user.option.category.example.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level.","title":"Categories"},{"location":"package/pip/user-option/#options","text":"If you install an option named exampleOption , you have to provide the language item wcf.user.option.exampleOption , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.user.option.exampleOption.description .","title":"Options"},{"location":"package/pip/user-profile-menu/","text":"User Profile Menu Package Installation Plugin # Registers new user profile tabs. Components # Each tab is described as an <userprofilemenuitem> element with the mandatory attribute name . <classname> # The name of the class providing the tab\u2019s behaviour, the class has to implement the wcf\\system\\menu\\user\\profile\\content\\IUserProfileMenuContent interface. <showorder> # Optional Determines at which position of the tab list the tab is shown. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the tab to be shown. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the tab to be shown. Example # userProfileMenu.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"utf-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userProfileMenu.xsd\" > <import> <userprofilemenuitem name= \"example\" > <classname> wcf\\system\\menu\\user\\profile\\content\\ExampleProfileMenuContent </classname> <showorder> 3 </showorder> <options> module_example </options> </userprofilemenuitem> </import> </data>","title":"userProfileMenu"},{"location":"package/pip/user-profile-menu/#user-profile-menu-package-installation-plugin","text":"Registers new user profile tabs.","title":"User Profile Menu Package Installation Plugin"},{"location":"package/pip/user-profile-menu/#components","text":"Each tab is described as an <userprofilemenuitem> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/user-profile-menu/#classname","text":"The name of the class providing the tab\u2019s behaviour, the class has to implement the wcf\\system\\menu\\user\\profile\\content\\IUserProfileMenuContent interface.","title":"<classname>"},{"location":"package/pip/user-profile-menu/#showorder","text":"Optional Determines at which position of the tab list the tab is shown.","title":"<showorder>"},{"location":"package/pip/user-profile-menu/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the tab to be shown.","title":"<options>"},{"location":"package/pip/user-profile-menu/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the tab to be shown.","title":"<permissions>"},{"location":"package/pip/user-profile-menu/#example","text":"userProfileMenu.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"utf-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userProfileMenu.xsd\" > <import> <userprofilemenuitem name= \"example\" > <classname> wcf\\system\\menu\\user\\profile\\content\\ExampleProfileMenuContent </classname> <showorder> 3 </showorder> <options> module_example </options> </userprofilemenuitem> </import> </data>","title":"Example"},{"location":"php/apps/","text":"Apps for WoltLab Suite # Introduction # Apps are among the most powerful components in WoltLab Suite. Unlike plugins that extend an existing functionality and pages, apps have their own frontend with a dedicated namespace, database table prefixes and template locations. However, apps are meant to be a logical (and to some extent physical) separation from other parts of the framework, including other installed apps. They offer an additional layer of isolation and enable you to re-use class and template names that are already in use by the Core itself. If you've come here, thinking about the question if your next package should be an app instead of a regular plugin, the result is almost always: No. Differences to Plugins # Apps do offer a couple of unique features that are not available to plugins and there are valid reasons to use one instead of a plugin, but they also increase both the code and system complexity. There is a performance penalty for each installed app, regardless if it is actively used in a request or not, simplying being there forces the Core to include it in many places, for example, class resolution or even simple tasks such as constructing a link. Unique Namespace # Each app has its own unique namespace that is entirely separated from the Core and any other installed apps. The namespace is derived from the last part of the package identifier, for example, com.example.foo will yield the namespace foo . The namespace is always relative to the installation directory of the app, it doesn't matter if the app is installed on example.com/foo/ or in example.com/bar/ , the namespace will always resolve to the right directory. This app namespace is also used for ACP templates, frontend templates and files: 1 2 <!-- somewhere in the package.xml --> <instructions type= \"file\" application= \"foo\" /> Unique Database Table Prefix # All database tables make use of a generic prefix that is derived from one of the installed apps, including wcf which resolves to the Core itself. Following the aforementioned example, the new prefix fooN_ will be automatically registered and recognized in any generated statement. Any DatabaseObject that uses the app's namespace is automatically assumed to use the app's database prefix. For instance, foo\\data\\bar\\Bar is implicitly mapped to the database table fooN_bar . The app prefix is recognized in SQL-PIPs and statements that reference one of its database tables are automatically rewritten to use the Core's instance number. Separate Domain and Path Configuration # Any controller that is provided by a plugin is served from the configured domain and path of the corresponding app, such as plugins for the Core are always served from the Core's directory. Apps are different and use their own domain and/or path to present their content, additionally, this allows the app to re-use a controller name that is already provided by the Core or any other app itself. Creating an App # This is a non-reversible operation! Once a package has been installed, its type cannot be changed without uninstalling and reinstalling the entire package, an app will always be an app and vice versa. package.xml # The package.xml supports two additional elements in the <packageinformation> block that are unique to applications. <isapplication>1</isapplication> # This element is responsible to flag a package as an app. <applicationdirectory>example</applicationdirectory> # Sets the suggested name of the application directory when installing it, the path result in <path-to-the-core>/example/ . If you leave this element out, the app identifier ( com.example.foo -> foo ) will be used instead. Minimum Required Files # An example project with the source code can be found on GitHub , it includes everything that is required for a basic app.","title":"Apps"},{"location":"php/apps/#apps-for-woltlab-suite","text":"","title":"Apps for WoltLab Suite"},{"location":"php/apps/#introduction","text":"Apps are among the most powerful components in WoltLab Suite. Unlike plugins that extend an existing functionality and pages, apps have their own frontend with a dedicated namespace, database table prefixes and template locations. However, apps are meant to be a logical (and to some extent physical) separation from other parts of the framework, including other installed apps. They offer an additional layer of isolation and enable you to re-use class and template names that are already in use by the Core itself. If you've come here, thinking about the question if your next package should be an app instead of a regular plugin, the result is almost always: No.","title":"Introduction"},{"location":"php/apps/#differences-to-plugins","text":"Apps do offer a couple of unique features that are not available to plugins and there are valid reasons to use one instead of a plugin, but they also increase both the code and system complexity. There is a performance penalty for each installed app, regardless if it is actively used in a request or not, simplying being there forces the Core to include it in many places, for example, class resolution or even simple tasks such as constructing a link.","title":"Differences to Plugins"},{"location":"php/apps/#unique-namespace","text":"Each app has its own unique namespace that is entirely separated from the Core and any other installed apps. The namespace is derived from the last part of the package identifier, for example, com.example.foo will yield the namespace foo . The namespace is always relative to the installation directory of the app, it doesn't matter if the app is installed on example.com/foo/ or in example.com/bar/ , the namespace will always resolve to the right directory. This app namespace is also used for ACP templates, frontend templates and files: 1 2 <!-- somewhere in the package.xml --> <instructions type= \"file\" application= \"foo\" />","title":"Unique Namespace"},{"location":"php/apps/#unique-database-table-prefix","text":"All database tables make use of a generic prefix that is derived from one of the installed apps, including wcf which resolves to the Core itself. Following the aforementioned example, the new prefix fooN_ will be automatically registered and recognized in any generated statement. Any DatabaseObject that uses the app's namespace is automatically assumed to use the app's database prefix. For instance, foo\\data\\bar\\Bar is implicitly mapped to the database table fooN_bar . The app prefix is recognized in SQL-PIPs and statements that reference one of its database tables are automatically rewritten to use the Core's instance number.","title":"Unique Database Table Prefix"},{"location":"php/apps/#separate-domain-and-path-configuration","text":"Any controller that is provided by a plugin is served from the configured domain and path of the corresponding app, such as plugins for the Core are always served from the Core's directory. Apps are different and use their own domain and/or path to present their content, additionally, this allows the app to re-use a controller name that is already provided by the Core or any other app itself.","title":"Separate Domain and Path Configuration"},{"location":"php/apps/#creating-an-app","text":"This is a non-reversible operation! Once a package has been installed, its type cannot be changed without uninstalling and reinstalling the entire package, an app will always be an app and vice versa.","title":"Creating an App"},{"location":"php/apps/#packagexml","text":"The package.xml supports two additional elements in the <packageinformation> block that are unique to applications.","title":"package.xml"},{"location":"php/apps/#isapplication1isapplication","text":"This element is responsible to flag a package as an app.","title":"<isapplication>1</isapplication>"},{"location":"php/apps/#applicationdirectoryexampleapplicationdirectory","text":"Sets the suggested name of the application directory when installing it, the path result in <path-to-the-core>/example/ . If you leave this element out, the app identifier ( com.example.foo -> foo ) will be used instead.","title":"<applicationdirectory>example</applicationdirectory>"},{"location":"php/apps/#minimum-required-files","text":"An example project with the source code can be found on GitHub , it includes everything that is required for a basic app.","title":"Minimum Required Files"},{"location":"php/code-style-documentation/","text":"Documentation # The following documentation conventions are used by us for our own packages. While you do not have to follow every rule, you are encouraged to do so. Database Objects # Database Table Columns as Properties # As the database table columns are not explicit properties of the classes extending wcf\\data\\DatabaseObject but rather stored in DatabaseObject::$data and accessible via DatabaseObject::__get($name) , the IDE we use, PhpStorm, is neither able to autocomplete such property access nor to interfere the type of the property. To solve this problem, @property-read tags must be added to the class documentation which registers the database table columns as public read-only properties: 1 * @property-read propertyType $propertyName property description The properties have to be in the same order as the order in the database table. The following table provides templates for common description texts so that similar database table columns have similar description texts. property description template and example unique object id unique id of the {object name} example: unique id of the acl option id of the delivering package id of the package which delivers the {object name} example: id of the package which delivers the acl option show order for nested structure position of the {object name} in relation to its siblings example: position of the ACP menu item in relation to its siblings show order within different object position of the {object name} in relation to the other {object name}s in the {parent object name} example: position of the label in relation to the other labels in the label group required permissions comma separated list of user group permissions of which the active user needs to have at least one to see (access, \u2026) the {object name} example: comma separated list of user group permissions of which the active user needs to have at least one to see the ACP menu item required options comma separated list of options of which at least one needs to be enabled for the {object name} to be shown (accessible, \u2026) example: comma separated list of options of which at least one needs to be enabled for the ACP menu item to be shown id of the user who has created the object id of the user who created (wrote, \u2026) the {object name} (or `null` if the user does not exist anymore (or if the {object name} has been created by a guest)) example: id of the user who wrote the comment or `null` if the user does not exist anymore or if the comment has been written by a guest name of the user who has created the object name of the user (or guest) who created (wrote, \u2026) the {object name} example: name of the user or guest who wrote the comment additional data array with additional data of the {object name} example: array with additional data of the user activity event time-related columns timestamp at which the {object name} has been created (written, \u2026) example: timestamp at which the comment has been written boolean options is `1` (or `0`) if the {object name} \u2026 (and thus \u2026), otherwise `0` (or `1`) example: is `1` if the ad is disabled and thus not shown, otherwise `0` $cumulativeLikes cumulative result of likes (counting `+1`) and dislikes (counting `-1`) for the {object name} example: cumulative result of likes (counting `+1`) and dislikes (counting `-1`) for the article $comments number of comments on the {object name} example: number of comments on the article $views number of times the {object name} has been viewed example: number of times the article has been viewed text field with potential language item name as value {text type} of the {object name} or name of language item which contains the {text type} example: description of the cronjob or name of language item which contains the description $objectTypeID id of the `{object type definition name}` object type example: id of the `com.woltlab.wcf.modifiableContent` object type Database Object Editors # Class Tags # Any database object editor class comment must have to following tags to properly support autocompletion by IDEs: 1 2 3 4 5 6 /** * \u2026 * @method static {DBO class name} create(array $parameters = []) * @method {DBO class name} getDecoratedObject() * @mixin {DBO class name} */ The only exception to this rule is if the class overwrites the create() method which itself has to be properly documentation then. The first and second line makes sure that when calling the create() or getDecoratedObject() method, the return value is correctly recognized and not just a general DatabaseObject instance. The third line tells the IDE (if @mixin is supported) that the database object editor decorates the database object and therefore offers autocompletion for properties and methods from the database object class itself. Runtime Caches # Class Tags # Any class implementing the IRuntimeCache interface must have the following class tags: 1 2 3 4 5 6 /** * \u2026 * @method {DBO class name}[] getCachedObjects() * @method {DBO class name} getObject($objectID) * @method {DBO class name}[] getObjects(array $objectIDs) */ These tags ensure that when calling any of the mentioned methods, the return value refers to the concrete database object and not just generically to DatabaseObject .","title":"Documentation"},{"location":"php/code-style-documentation/#documentation","text":"The following documentation conventions are used by us for our own packages. While you do not have to follow every rule, you are encouraged to do so.","title":"Documentation"},{"location":"php/code-style-documentation/#database-objects","text":"","title":"Database Objects"},{"location":"php/code-style-documentation/#database-table-columns-as-properties","text":"As the database table columns are not explicit properties of the classes extending wcf\\data\\DatabaseObject but rather stored in DatabaseObject::$data and accessible via DatabaseObject::__get($name) , the IDE we use, PhpStorm, is neither able to autocomplete such property access nor to interfere the type of the property. To solve this problem, @property-read tags must be added to the class documentation which registers the database table columns as public read-only properties: 1 * @property-read propertyType $propertyName property description The properties have to be in the same order as the order in the database table. The following table provides templates for common description texts so that similar database table columns have similar description texts. property description template and example unique object id unique id of the {object name} example: unique id of the acl option id of the delivering package id of the package which delivers the {object name} example: id of the package which delivers the acl option show order for nested structure position of the {object name} in relation to its siblings example: position of the ACP menu item in relation to its siblings show order within different object position of the {object name} in relation to the other {object name}s in the {parent object name} example: position of the label in relation to the other labels in the label group required permissions comma separated list of user group permissions of which the active user needs to have at least one to see (access, \u2026) the {object name} example: comma separated list of user group permissions of which the active user needs to have at least one to see the ACP menu item required options comma separated list of options of which at least one needs to be enabled for the {object name} to be shown (accessible, \u2026) example: comma separated list of options of which at least one needs to be enabled for the ACP menu item to be shown id of the user who has created the object id of the user who created (wrote, \u2026) the {object name} (or `null` if the user does not exist anymore (or if the {object name} has been created by a guest)) example: id of the user who wrote the comment or `null` if the user does not exist anymore or if the comment has been written by a guest name of the user who has created the object name of the user (or guest) who created (wrote, \u2026) the {object name} example: name of the user or guest who wrote the comment additional data array with additional data of the {object name} example: array with additional data of the user activity event time-related columns timestamp at which the {object name} has been created (written, \u2026) example: timestamp at which the comment has been written boolean options is `1` (or `0`) if the {object name} \u2026 (and thus \u2026), otherwise `0` (or `1`) example: is `1` if the ad is disabled and thus not shown, otherwise `0` $cumulativeLikes cumulative result of likes (counting `+1`) and dislikes (counting `-1`) for the {object name} example: cumulative result of likes (counting `+1`) and dislikes (counting `-1`) for the article $comments number of comments on the {object name} example: number of comments on the article $views number of times the {object name} has been viewed example: number of times the article has been viewed text field with potential language item name as value {text type} of the {object name} or name of language item which contains the {text type} example: description of the cronjob or name of language item which contains the description $objectTypeID id of the `{object type definition name}` object type example: id of the `com.woltlab.wcf.modifiableContent` object type","title":"Database Table Columns as Properties"},{"location":"php/code-style-documentation/#database-object-editors","text":"","title":"Database Object Editors"},{"location":"php/code-style-documentation/#class-tags","text":"Any database object editor class comment must have to following tags to properly support autocompletion by IDEs: 1 2 3 4 5 6 /** * \u2026 * @method static {DBO class name} create(array $parameters = []) * @method {DBO class name} getDecoratedObject() * @mixin {DBO class name} */ The only exception to this rule is if the class overwrites the create() method which itself has to be properly documentation then. The first and second line makes sure that when calling the create() or getDecoratedObject() method, the return value is correctly recognized and not just a general DatabaseObject instance. The third line tells the IDE (if @mixin is supported) that the database object editor decorates the database object and therefore offers autocompletion for properties and methods from the database object class itself.","title":"Class Tags"},{"location":"php/code-style-documentation/#runtime-caches","text":"","title":"Runtime Caches"},{"location":"php/code-style-documentation/#class-tags_1","text":"Any class implementing the IRuntimeCache interface must have the following class tags: 1 2 3 4 5 6 /** * \u2026 * @method {DBO class name}[] getCachedObjects() * @method {DBO class name} getObject($objectID) * @method {DBO class name}[] getObjects(array $objectIDs) */ These tags ensure that when calling any of the mentioned methods, the return value refers to the concrete database object and not just generically to DatabaseObject .","title":"Class Tags"},{"location":"php/code-style/","text":"Code Style # The following code style conventions are used by us for our own packages. While you do not have to follow every rule, you are encouraged to do so. For information about how to document your code, please refer to the documentation page . General Code Style # Naming conventions # The relevant naming conventions are: Upper camel case : The first letters of all compound words are written in upper case. Lower camel case : The first letters of compound words are written in upper case, except for the first letter which is written in lower case. Screaming snake case : All letters are written in upper case and compound words are separated by underscores. Type Convention Example Variable lower camel case $variableName Class upper camel case class UserGroupEditor Properties lower camel case public $propertyName Method lower camel case public function getObjectByName() Constant screaming snake case MODULE_USER_THING Arrays # For arrays, use the short array syntax introduced with PHP 5.4. The following example illustrates the different cases that can occur when working with arrays and how to format them: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $empty = []; $oneElement = [ 1 ]; $multipleElements = [ 1 , 2 , 3 ]; $oneElementWithKey = [ 'firstElement' => 1 ]; $multipleElementsWithKey = [ 'firstElement' => 1 , 'secondElement' => 2 , 'thirdElement' => 3 ]; Ternary Operator # The ternary operator can be used for short conditioned assignments: 1 2 3 <? php $name = isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ; The condition and the values should be short so that the code does not result in a very long line which thus decreases the readability compared to an if-else statement. Parentheses may only be used around the condition and not around the whole statement: 1 2 3 4 <? php // do not do it like this $name = ( isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ); Parentheses around the conditions may not be used to wrap simple function calls: 1 2 3 4 <? php // do not do it like this $name = ( isset ( $tagArgs [ 'name' ])) ? $tagArgs [ 'name' ] : 'default' ; but have to be used for comparisons or other binary operators: 1 2 3 <? php $value = ( $otherValue > $upperLimit ) ? $additionalValue : $otherValue ; If you need to use more than one binary operator, use an if-else statement. The same rules apply to assigning array values: 1 2 3 4 5 6 7 <? php $values = [ 'first' => $firstValue , 'second' => $secondToggle ? $secondValueA : $secondValueB , 'third' => ( $thirdToogle > 13 ) ? $thirdToogleA : $thirdToogleB ]; or return values: 1 2 3 <? php return isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ; Whitespaces # You have to put a whitespace in front of the following things: equal sign in assignments: $x = 1; comparison operators: $x == 1 opening bracket of a block public function test() { You have to put a whitespace behind the following things: equal sign in assignments: $x = 1; comparison operators: $x == 1 comma in a function/method parameter list if the comma is not followed by a line break: public function test($a, $b) { if , for , foreach , while : if ($x == 1) Classes # Referencing Class Names # If you have to reference a class name inside a php file, you have to use the class keyword. 1 2 3 4 5 6 7 8 <? php // not like this $className = 'wcf\\data\\example\\Example' ; // like this use wcf\\data\\example\\Example ; $className = Example :: class ; Static Getters (of DatabaseObject Classes) # Some database objects provide static getters, either if they are decorators or for a unique combination of database table columns, like wcf\\data\\box\\Box::getBoxByIdentifier() : files/lib/data/box/Box.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <? php namespace wcf\\data\\box ; use wcf\\data\\DatabaseObject ; use wcf\\system\\WCF ; class Box extends DatabaseObject { /** * Returns the box with the given identifier. * * @param string $identifier * @return Box|null */ public static function getBoxByIdentifier ( $identifier ) { $sql = \"SELECT * FROM wcf\" . WCF_N . \"_box WHERE identifier = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ([ $identifier ]); return $statement -> fetchObject ( self :: class ); } } Such methods should always either return the desired object or null if the object does not exist. wcf\\system\\database\\statement\\PreparedStatement::fetchObject() already takes care of this distinction so that its return value can simply be returned by such methods. The name of such getters should generally follow the convention get{object type}By{column or other description} . Long method calls # In some instances, methods with many argument have to be called which can result in lines of code like this one: 1 2 3 <? php \\wcf\\system\\search\\SearchIndexManager :: getInstance () -> set ( 'com.woltlab.wcf.article' , $articleContent -> articleContentID , $articleContent -> content , $articleContent -> title , $articles [ $articleContent -> articleID ] -> time , $articles [ $articleContent -> articleID ] -> userID , $articles [ $articleContent -> articleID ] -> username , $articleContent -> languageID , $articleContent -> teaser ); which is hardly readable. Therefore, the line must be split into multiple lines with each argument in a separate line: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php \\wcf\\system\\search\\SearchIndexManager :: getInstance () -> set ( 'com.woltlab.wcf.article' , $articleContent -> articleContentID , $articleContent -> content , $articleContent -> title , $articles [ $articleContent -> articleID ] -> time , $articles [ $articleContent -> articleID ] -> userID , $articles [ $articleContent -> articleID ] -> username , $articleContent -> languageID , $articleContent -> teaser ); In general, this rule applies to the following methods: wcf\\system\\edit\\EditHistoryManager::add() wcf\\system\\message\\quote\\MessageQuoteManager::addQuote() wcf\\system\\message\\quote\\MessageQuoteManager::getQuoteID() wcf\\system\\search\\SearchIndexManager::set() wcf\\system\\user\\object\\watch\\UserObjectWatchHandler::updateObject() wcf\\system\\user\\notification\\UserNotificationHandler::fireEvent()","title":"Code Style"},{"location":"php/code-style/#code-style","text":"The following code style conventions are used by us for our own packages. While you do not have to follow every rule, you are encouraged to do so. For information about how to document your code, please refer to the documentation page .","title":"Code Style"},{"location":"php/code-style/#general-code-style","text":"","title":"General Code Style"},{"location":"php/code-style/#naming-conventions","text":"The relevant naming conventions are: Upper camel case : The first letters of all compound words are written in upper case. Lower camel case : The first letters of compound words are written in upper case, except for the first letter which is written in lower case. Screaming snake case : All letters are written in upper case and compound words are separated by underscores. Type Convention Example Variable lower camel case $variableName Class upper camel case class UserGroupEditor Properties lower camel case public $propertyName Method lower camel case public function getObjectByName() Constant screaming snake case MODULE_USER_THING","title":"Naming conventions"},{"location":"php/code-style/#arrays","text":"For arrays, use the short array syntax introduced with PHP 5.4. The following example illustrates the different cases that can occur when working with arrays and how to format them: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $empty = []; $oneElement = [ 1 ]; $multipleElements = [ 1 , 2 , 3 ]; $oneElementWithKey = [ 'firstElement' => 1 ]; $multipleElementsWithKey = [ 'firstElement' => 1 , 'secondElement' => 2 , 'thirdElement' => 3 ];","title":"Arrays"},{"location":"php/code-style/#ternary-operator","text":"The ternary operator can be used for short conditioned assignments: 1 2 3 <? php $name = isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ; The condition and the values should be short so that the code does not result in a very long line which thus decreases the readability compared to an if-else statement. Parentheses may only be used around the condition and not around the whole statement: 1 2 3 4 <? php // do not do it like this $name = ( isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ); Parentheses around the conditions may not be used to wrap simple function calls: 1 2 3 4 <? php // do not do it like this $name = ( isset ( $tagArgs [ 'name' ])) ? $tagArgs [ 'name' ] : 'default' ; but have to be used for comparisons or other binary operators: 1 2 3 <? php $value = ( $otherValue > $upperLimit ) ? $additionalValue : $otherValue ; If you need to use more than one binary operator, use an if-else statement. The same rules apply to assigning array values: 1 2 3 4 5 6 7 <? php $values = [ 'first' => $firstValue , 'second' => $secondToggle ? $secondValueA : $secondValueB , 'third' => ( $thirdToogle > 13 ) ? $thirdToogleA : $thirdToogleB ]; or return values: 1 2 3 <? php return isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ;","title":"Ternary Operator"},{"location":"php/code-style/#whitespaces","text":"You have to put a whitespace in front of the following things: equal sign in assignments: $x = 1; comparison operators: $x == 1 opening bracket of a block public function test() { You have to put a whitespace behind the following things: equal sign in assignments: $x = 1; comparison operators: $x == 1 comma in a function/method parameter list if the comma is not followed by a line break: public function test($a, $b) { if , for , foreach , while : if ($x == 1)","title":"Whitespaces"},{"location":"php/code-style/#classes","text":"","title":"Classes"},{"location":"php/code-style/#referencing-class-names","text":"If you have to reference a class name inside a php file, you have to use the class keyword. 1 2 3 4 5 6 7 8 <? php // not like this $className = 'wcf\\data\\example\\Example' ; // like this use wcf\\data\\example\\Example ; $className = Example :: class ;","title":"Referencing Class Names"},{"location":"php/code-style/#static-getters-of-databaseobject-classes","text":"Some database objects provide static getters, either if they are decorators or for a unique combination of database table columns, like wcf\\data\\box\\Box::getBoxByIdentifier() : files/lib/data/box/Box.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <? php namespace wcf\\data\\box ; use wcf\\data\\DatabaseObject ; use wcf\\system\\WCF ; class Box extends DatabaseObject { /** * Returns the box with the given identifier. * * @param string $identifier * @return Box|null */ public static function getBoxByIdentifier ( $identifier ) { $sql = \"SELECT * FROM wcf\" . WCF_N . \"_box WHERE identifier = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ([ $identifier ]); return $statement -> fetchObject ( self :: class ); } } Such methods should always either return the desired object or null if the object does not exist. wcf\\system\\database\\statement\\PreparedStatement::fetchObject() already takes care of this distinction so that its return value can simply be returned by such methods. The name of such getters should generally follow the convention get{object type}By{column or other description} .","title":"Static Getters (of DatabaseObject Classes)"},{"location":"php/code-style/#long-method-calls","text":"In some instances, methods with many argument have to be called which can result in lines of code like this one: 1 2 3 <? php \\wcf\\system\\search\\SearchIndexManager :: getInstance () -> set ( 'com.woltlab.wcf.article' , $articleContent -> articleContentID , $articleContent -> content , $articleContent -> title , $articles [ $articleContent -> articleID ] -> time , $articles [ $articleContent -> articleID ] -> userID , $articles [ $articleContent -> articleID ] -> username , $articleContent -> languageID , $articleContent -> teaser ); which is hardly readable. Therefore, the line must be split into multiple lines with each argument in a separate line: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php \\wcf\\system\\search\\SearchIndexManager :: getInstance () -> set ( 'com.woltlab.wcf.article' , $articleContent -> articleContentID , $articleContent -> content , $articleContent -> title , $articles [ $articleContent -> articleID ] -> time , $articles [ $articleContent -> articleID ] -> userID , $articles [ $articleContent -> articleID ] -> username , $articleContent -> languageID , $articleContent -> teaser ); In general, this rule applies to the following methods: wcf\\system\\edit\\EditHistoryManager::add() wcf\\system\\message\\quote\\MessageQuoteManager::addQuote() wcf\\system\\message\\quote\\MessageQuoteManager::getQuoteID() wcf\\system\\search\\SearchIndexManager::set() wcf\\system\\user\\object\\watch\\UserObjectWatchHandler::updateObject() wcf\\system\\user\\notification\\UserNotificationHandler::fireEvent()","title":"Long method calls"},{"location":"php/database-access/","text":"Database Access # Database Objects provide a convenient and object-oriented approach to work with the database, but there can be use-cases that require raw access including writing methods for model classes. This section assumes that you have either used prepared statements before or at least understand how it works. The PreparedStatement Object # The database access is designed around PreparedStatement , built on top of PHP's PDOStatement so that you call all of PDOStatement 's methods, and each query requires you to obtain a statement object. 1 2 3 4 5 6 <? php $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( \"SELECT * FROM wcf\" . WCF_N . \"_example\" ); $statement -> execute (); while ( $row = $statement -> fetchArray ()) { // handle result } Query Parameters # The example below illustrates the usage of parameters where each value is replaced with the generic ? -placeholder. Values are provided by calling $statement->execute() with a continuous, one-dimensional array that exactly match the number of question marks. 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example WHERE exampleID = ? OR bar IN (?, ?, ?, ?, ?)\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ([ $exampleID , $list , $of , $values , $for , $bar ]); while ( $row = $statement -> fetchArray ()) { // handle result } Fetching a Single Result # Do not attempt to use fetchSingleRow() or fetchSingleColumn() if the result contains more than one row. You can opt-in to retrieve only a single row from database and make use of shortcut methods to reduce the code that you have to write. 1 2 3 4 5 6 7 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql , 1 ); $statement -> execute ([ $exampleID ]); $row = $statement -> fetchSingleRow (); There are two distinct differences when comparing with the example on query parameters above: The method prepareStatement() receives a secondary parameter that will be appended to the query as LIMIT 1 . Data is read using fetchSingleRow() instead of fetchArray() or similar methods, that will read one result and close the cursor. Fetch by Column # There is no way to return another column from the same row if you use fetchColumn() to retrieve data. Fetching an array is only useful if there is going to be more than one column per result row, otherwise accessing the column directly is much more convenient and increases the code readability. 1 2 3 4 5 6 7 8 9 <? php $sql = \"SELECT bar FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); while ( $bar = $statement -> fetchColumn ()) { // handle result } $bar = $statement -> fetchSingleColumn (); Similar to fetching a single row, you can also issue a query that will select a single row, but reads only one column from the result row. 1 2 3 4 5 6 7 <? php $sql = \"SELECT bar FROM wcf\" . WCF_N . \"_example WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql , 1 ); $statement -> execute ([ $exampleID ]); $bar = $statement -> fetchSingleColumn (); Fetching All Results # If you want to fetch all results of a query but only store them in an array without directly processing them, in most cases, you can rely on built-in methods. To fetch all rows of query, you can use PDOStatement::fetchAll() with \\PDO::FETCH_ASSOC as the first parameter: 1 2 3 4 5 6 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $rows = $statement -> fetchAll ( \\PDO :: FETCH_ASSOC ); As a result, you get an array containing associative arrays with the rows of the wcf{WCF_N}_example database table as content. If you only want to fetch a list of the values of a certain column, you can use \\PDO::FETCH_COLUMN as the first parameter: 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $exampleIDs = $statement -> fetchAll ( \\PDO :: FETCH_COLUMN ); As a result, you get an array with all exampleID values. The PreparedStatement class adds an additional methods that covers another common use case in our code: Fetching two columns and using the first column's value as the array key and the second column's value as the array value. This case is covered by PreparedStatement::fetchMap() : 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID, userID FROM wcf\" . WCF_N . \"_example_mapping\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $map = $statement -> fetchMap ( 'exampleID' , 'userID' ); $map is a one-dimensional array where each exampleID value maps to the corresponding userID value. If there are multiple entries for a certain exampleID value with different userID values, the existing entry in the array will be overwritten and contain the last read value from the database table. Therefore, this method should generally only be used for unique combinations. If you do not have a combination of columns with unique pairs of values, but you want to get a list of userID values with the same exampleID , you can set the third parameter of fetchMap() to false and get a list: 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID, userID FROM wcf\" . WCF_N . \"_example_mapping\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $map = $statement -> fetchMap ( 'exampleID' , 'userID' , false ); Now, as a result, you get a two-dimensional array with the array keys being the exampleID values and the array values being arrays with all userID values from rows with the respective exampleID value. Building Complex Conditions # Building conditional conditions can turn out to be a real mess and it gets even worse with SQL's IN (\u2026) which requires as many placeholders as there will be values. The solutions is PreparedStatementConditionBuilder , a simple but useful helper class with a bulky name, it is also the class used when accessing DatabaseObjecList::getConditionBuilder() . 1 2 3 4 5 6 <? php $conditions = new \\wcf\\system\\database\\util\\PreparedStatementConditionBuilder (); $conditions -> add ( \"exampleID = ?\" , [ $exampleID ]); if ( ! empty ( $valuesForBar )) { $conditions -> add ( \"(bar IN (?) OR baz = ?)\" , [ $valuesForBar , $baz ]); } The IN (?) in the example above is automatically expanded to match the number of items contained in $valuesForBar . Be aware that the method will generate an invalid query if $valuesForBar is empty! INSERT or UPDATE in Bulk # Prepared statements not only protect against SQL injection by separating the logical query and the actual data, but also provides the ability to reuse the same query with different values. This leads to a performance improvement as the code does not have to transmit the query with for every data set and only has to parse and analyze the query once. 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $data = [ 'abc' , 'def' , 'ghi' ]; $sql = \"INSERT INTO wcf\" . WCF_N . \"_example (bar) VALUES (?)\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); \\wcf\\system\\WCF :: getDB () -> beginTransaction (); foreach ( $data as $bar ) { $statement -> execute ([ $bar ]); } \\wcf\\system\\WCF :: getDB () -> commitTransaction (); It is generally advised to wrap bulk operations in a transaction as it allows the database to optimize the process, including fewer I/O operations. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <? php $data = [ 1 => 'abc' , 3 => 'def' , 4 => 'ghi' ]; $sql = \"UPDATE wcf\" . WCF_N . \"_example SET bar = ? WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); \\wcf\\system\\WCF :: getDB () -> beginTransaction (); foreach ( $data as $exampleID => $bar ) { $statement -> execute ([ $bar , $exampleID ]); } \\wcf\\system\\WCF :: getDB () -> commitTransaction ();","title":"Database Access"},{"location":"php/database-access/#database-access","text":"Database Objects provide a convenient and object-oriented approach to work with the database, but there can be use-cases that require raw access including writing methods for model classes. This section assumes that you have either used prepared statements before or at least understand how it works.","title":"Database Access"},{"location":"php/database-access/#the-preparedstatement-object","text":"The database access is designed around PreparedStatement , built on top of PHP's PDOStatement so that you call all of PDOStatement 's methods, and each query requires you to obtain a statement object. 1 2 3 4 5 6 <? php $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( \"SELECT * FROM wcf\" . WCF_N . \"_example\" ); $statement -> execute (); while ( $row = $statement -> fetchArray ()) { // handle result }","title":"The PreparedStatement Object"},{"location":"php/database-access/#query-parameters","text":"The example below illustrates the usage of parameters where each value is replaced with the generic ? -placeholder. Values are provided by calling $statement->execute() with a continuous, one-dimensional array that exactly match the number of question marks. 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example WHERE exampleID = ? OR bar IN (?, ?, ?, ?, ?)\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ([ $exampleID , $list , $of , $values , $for , $bar ]); while ( $row = $statement -> fetchArray ()) { // handle result }","title":"Query Parameters"},{"location":"php/database-access/#fetching-a-single-result","text":"Do not attempt to use fetchSingleRow() or fetchSingleColumn() if the result contains more than one row. You can opt-in to retrieve only a single row from database and make use of shortcut methods to reduce the code that you have to write. 1 2 3 4 5 6 7 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql , 1 ); $statement -> execute ([ $exampleID ]); $row = $statement -> fetchSingleRow (); There are two distinct differences when comparing with the example on query parameters above: The method prepareStatement() receives a secondary parameter that will be appended to the query as LIMIT 1 . Data is read using fetchSingleRow() instead of fetchArray() or similar methods, that will read one result and close the cursor.","title":"Fetching a Single Result"},{"location":"php/database-access/#fetch-by-column","text":"There is no way to return another column from the same row if you use fetchColumn() to retrieve data. Fetching an array is only useful if there is going to be more than one column per result row, otherwise accessing the column directly is much more convenient and increases the code readability. 1 2 3 4 5 6 7 8 9 <? php $sql = \"SELECT bar FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); while ( $bar = $statement -> fetchColumn ()) { // handle result } $bar = $statement -> fetchSingleColumn (); Similar to fetching a single row, you can also issue a query that will select a single row, but reads only one column from the result row. 1 2 3 4 5 6 7 <? php $sql = \"SELECT bar FROM wcf\" . WCF_N . \"_example WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql , 1 ); $statement -> execute ([ $exampleID ]); $bar = $statement -> fetchSingleColumn ();","title":"Fetch by Column"},{"location":"php/database-access/#fetching-all-results","text":"If you want to fetch all results of a query but only store them in an array without directly processing them, in most cases, you can rely on built-in methods. To fetch all rows of query, you can use PDOStatement::fetchAll() with \\PDO::FETCH_ASSOC as the first parameter: 1 2 3 4 5 6 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $rows = $statement -> fetchAll ( \\PDO :: FETCH_ASSOC ); As a result, you get an array containing associative arrays with the rows of the wcf{WCF_N}_example database table as content. If you only want to fetch a list of the values of a certain column, you can use \\PDO::FETCH_COLUMN as the first parameter: 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $exampleIDs = $statement -> fetchAll ( \\PDO :: FETCH_COLUMN ); As a result, you get an array with all exampleID values. The PreparedStatement class adds an additional methods that covers another common use case in our code: Fetching two columns and using the first column's value as the array key and the second column's value as the array value. This case is covered by PreparedStatement::fetchMap() : 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID, userID FROM wcf\" . WCF_N . \"_example_mapping\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $map = $statement -> fetchMap ( 'exampleID' , 'userID' ); $map is a one-dimensional array where each exampleID value maps to the corresponding userID value. If there are multiple entries for a certain exampleID value with different userID values, the existing entry in the array will be overwritten and contain the last read value from the database table. Therefore, this method should generally only be used for unique combinations. If you do not have a combination of columns with unique pairs of values, but you want to get a list of userID values with the same exampleID , you can set the third parameter of fetchMap() to false and get a list: 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID, userID FROM wcf\" . WCF_N . \"_example_mapping\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $map = $statement -> fetchMap ( 'exampleID' , 'userID' , false ); Now, as a result, you get a two-dimensional array with the array keys being the exampleID values and the array values being arrays with all userID values from rows with the respective exampleID value.","title":"Fetching All Results"},{"location":"php/database-access/#building-complex-conditions","text":"Building conditional conditions can turn out to be a real mess and it gets even worse with SQL's IN (\u2026) which requires as many placeholders as there will be values. The solutions is PreparedStatementConditionBuilder , a simple but useful helper class with a bulky name, it is also the class used when accessing DatabaseObjecList::getConditionBuilder() . 1 2 3 4 5 6 <? php $conditions = new \\wcf\\system\\database\\util\\PreparedStatementConditionBuilder (); $conditions -> add ( \"exampleID = ?\" , [ $exampleID ]); if ( ! empty ( $valuesForBar )) { $conditions -> add ( \"(bar IN (?) OR baz = ?)\" , [ $valuesForBar , $baz ]); } The IN (?) in the example above is automatically expanded to match the number of items contained in $valuesForBar . Be aware that the method will generate an invalid query if $valuesForBar is empty!","title":"Building Complex Conditions"},{"location":"php/database-access/#insert-or-update-in-bulk","text":"Prepared statements not only protect against SQL injection by separating the logical query and the actual data, but also provides the ability to reuse the same query with different values. This leads to a performance improvement as the code does not have to transmit the query with for every data set and only has to parse and analyze the query once. 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $data = [ 'abc' , 'def' , 'ghi' ]; $sql = \"INSERT INTO wcf\" . WCF_N . \"_example (bar) VALUES (?)\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); \\wcf\\system\\WCF :: getDB () -> beginTransaction (); foreach ( $data as $bar ) { $statement -> execute ([ $bar ]); } \\wcf\\system\\WCF :: getDB () -> commitTransaction (); It is generally advised to wrap bulk operations in a transaction as it allows the database to optimize the process, including fewer I/O operations. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <? php $data = [ 1 => 'abc' , 3 => 'def' , 4 => 'ghi' ]; $sql = \"UPDATE wcf\" . WCF_N . \"_example SET bar = ? WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); \\wcf\\system\\WCF :: getDB () -> beginTransaction (); foreach ( $data as $exampleID => $bar ) { $statement -> execute ([ $bar , $exampleID ]); } \\wcf\\system\\WCF :: getDB () -> commitTransaction ();","title":"INSERT or UPDATE in Bulk"},{"location":"php/database-objects/","text":"Database Objects # WoltLab Suite uses a unified interface to work with database rows using an object based approach instead of using native arrays holding arbitrary data. Each database table is mapped to a model class that is designed to hold a single record from that table and expose methods to work with the stored data, for example providing assistance when working with normalized datasets. Developers are required to provide the proper DatabaseObject implementations themselves, they're not automatically generated, all though the actual code that needs to be written is rather small. The following examples assume the fictional database table wcf1_example , exampleID as the auto-incrementing primary key and the column bar to store some text. DatabaseObject # The basic model derives from wcf\\data\\DatabaseObject and provides a convenient constructor to fetch a single row or construct an instance using pre-loaded rows. files/lib/data/example/Example.class.php 1 2 3 4 5 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObject ; class Example extends DatabaseObject {} The class is intended to be empty by default and there only needs to be code if you want to add additional logic to your model. Both the class name and primary key are determined by DatabaseObject using the namespace and class name of the derived class. The example above uses the namespace wcf\\\u2026 which is used as table prefix and the class name Example is converted into exampleID , resulting in the database table name wcfN_example with the primary key exampleID . You can prevent this automatic guessing by setting the class properties $databaseTableName and $databaseTableIndexName manually. DatabaseObjectDecorator # If you already have a DatabaseObject class and would like to extend it with additional data or methods, for example by providing a class ViewableExample which features view-related changes without polluting the original object, you can use DatabaseObjectDecorator which a default implementation of a decorator for database objects. files/lib/data/example/ViewableExample.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectDecorator ; class ViewableExample extends DatabaseObjectDecorator { protected static $baseClass = Example :: class ; public function getOutput () { $output = '' ; // [determine output] return $output ; } } It is mandatory to set the static $baseClass property to the name of the decorated class. Like for any decorator, you can directly access the decorated object's properties and methods for a decorated object by accessing the property or calling the method on the decorated object. You can access the decorated objects directly via DatabaseObjectDecorator::getDecoratedObject() . DatabaseObjectEditor # This is the low-level interface to manipulate data rows, it is recommended to use AbstractDatabaseObjectAction . Adding, editing and deleting models is done using the DatabaseObjectEditor class that decorates a DatabaseObject and uses its data to perform the actions. files/lib/data/example/ExampleEditor.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectEditor ; class ExampleEditor extends DatabaseObjectEditor { protected static $baseClass = Example :: class ; } The editor class requires you to provide the fully qualified name of the model, that is the class name including the complete namespace. Database table name and index key will be pulled directly from the model. Create a new row # Inserting a new row into the database table is provided through DatabaseObjectEditor::create() which yields a DatabaseObject instance after creation. 1 2 3 4 5 6 7 <? php $example = \\wcf\\data\\example\\ExampleEditor :: create ([ 'bar' => 'Hello World!' ]); // output: Hello World! echo $example -> bar ; Updating an existing row # The internal state of the decorated DatabaseObject is not altered at any point, the values will still be the same after editing or deleting the represented row. If you need an object with the latest data, you'll have to discard the current object and refetch the data from database. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php $example = new \\wcf\\data\\example\\Example ( $id ); $exampleEditor = new \\wcf\\data\\example\\ExampleEditor ( $example ); $exampleEditor -> update ([ 'bar' => 'baz' ]); // output: Hello World! echo $example -> bar ; // re-creating the object will query the database again and retrieve the updated value $example = new \\wcf\\data\\example\\Example ( $example -> id ); // output: baz echo $example -> bar ; Deleting a row # Similar to the update process, the decorated DatabaseObject is not altered and will then point to an inexistent row. 1 2 3 4 <? php $example = new \\wcf\\data\\example\\Example ( $id ); $exampleEditor = new \\wcf\\data\\example\\ExampleEditor ( $example ); $exampleEditor -> delete (); DatabaseObjectList # Every row is represented as a single instance of the model, but the instance creation deals with single rows only. Retrieving larger sets of rows would be quite inefficient due to the large amount of queries that will be dispatched. This is solved with the DatabaseObjectList object that exposes an interface to query the database table using arbitrary conditions for data selection. All rows will be fetched using a single query and the resulting rows are automatically loaded into separate models. files/lib/data/example/ExampleList.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectList ; class ExampleList extends DatabaseObjectList { public $className = Example :: class ; } The following code listing illustrates loading a large set of examples and iterating over the list to retrieve the objects. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php $exampleList = new \\wcf\\data\\example\\ExampleList (); // add constraints using the condition builder $exampleList -> getConditionBuilder () -> add ( 'bar IN (?)' , [[ 'Hello World!' , 'bar' , 'baz' ]]); // actually read the rows $exampleList -> readObjects (); foreach ( $exampleList as $example ) { echo $example -> bar ; } // retrieve the models directly instead of iterating over them $examples = $exampleList -> getObjects (); // just retrieve the number of rows $exampleCount = $exampleList -> countObjects (); DatabaseObjectList implements both SeekableIterator and Countable . Additionally, DatabaseObjectList objects has the following three public properties that are useful when fetching data with lists: $sqlLimit determines how many rows are fetched. If its value is 0 (which is the default value), all results are fetched. So be careful when dealing with large tables and you only want a limited number of rows: Set $sqlLimit to a value larger than zero! $sqlOffset : Paginated pages like a thread list use this feature a lot, it allows you to skip a given number of results. Imagine you want to display 20 threads per page but there are a total of 60 threads available. In this case you would specify $sqlLimit = 20 and $sqlOffset = 20 which will skip the first 20 threads, effectively displaying thread 21 to 40. $sqlOrderBy determines by which column(s) the rows are sorted in which order. Using our example in $sqlOffset you might want to display the 20 most recent threads on page 1, thus you should specify the order field and its direction, e.g. $sqlOrderBy = 'thread.lastPostTime DESC' which returns the most recent thread first. For more advanced usage, there two additional fields that deal with the type of objects returned. First, let's go into a bit more detail what setting the $className property actually does: It is the type of database object in which the rows are wrapped. It determines which database table is actually queried and which index is used (see the $databaseTableName and $databaseTableIndexName properties of DatabaseObject ). Sometimes you might use the database table of some database object but wrap the rows in another database object. This can be achieved by setting the $objectClassName property to the desired class name. In other cases, you might want to wrap the created objects in a database object decorator which can be done by setting the $decoratorClassName property to the desired class name: 1 2 3 <? php $exampleList = new \\wcf\\data\\example\\ExampleList (); $exampleList -> decoratorClassName = \\wcf\\data\\example\\ViewableExample :: class ; Of course, you do not have to set the property after creating the list object, you can also set it by creating a dedicated class: files/lib/data/example/ViewableExampleList.class.php 1 2 3 4 5 6 <? php namespace wcf\\data\\example ; class ViewableExampleList extends ExampleList { public $decoratorClassName = ViewableExample :: class ; } AbstractDatabaseObjectAction # Row creation and manipulation can be performed using the aforementioned DatabaseObjectEditor class, but this approach has two major issues: Row creation, update and deletion takes place silently without notifying any other components. Data is passed to the database adapter without any further processing. The AbstractDatabaseObjectAction solves both problems by wrapping around the editor class and thus provide an additional layer between the action that should be taken and the actual process. The first problem is solved by a fixed set of events being fired, the second issue is addressed by having a single entry point for all data editing. files/lib/data/example/ExampleAction.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\AbstractDatabaseObjectAction ; class ExampleAction extends AbstractDatabaseObjectAction { public $className = ExampleEditor :: class ; } Executing an Action # The method AbstractDatabaseObjectAction::validateAction() is internally used for AJAX method invocation and must not be called programmatically. The next example represents the same functionality as seen for DatabaseObjectEditor : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <? php use wcf\\data\\example\\ExampleAction ; // create a row $exampleAction = new ExampleAction ([], 'create' , [ 'data' => [ 'bar' => 'Hello World' ] ]); $example = $exampleAction -> executeAction ()[ 'returnValues' ]; // update a row using the id $exampleAction = new ExampleAction ([ 1 ], 'update' , [ 'data' => [ 'bar' => 'baz' ] ]); $exampleAction -> executeAction (); // delete a row using a model $exampleAction = new ExampleAction ([ $example ], 'delete' ); $exampleAction -> executeAction (); You can access the return values both by storing the return value of executeAction() or by retrieving it via getReturnValues() . Events initializeAction , validateAction and finalizeAction Custom Method with AJAX Support # This section is about adding the method baz() to ExampleAction and calling it via AJAX. AJAX Validation # Methods of an action cannot be called via AJAX, unless they have a validation method. This means that ExampleAction must define both a public function baz() and public function validateBaz() , the name for the validation method is constructed by upper-casing the first character of the method name and prepending validate . The lack of the companion validate* method will cause the AJAX proxy to deny the request instantaneously. Do not add a validation method if you don't want it to be callable via AJAX ever! create, update and delete # The methods create , update and delete are available for all classes deriving from AbstractDatabaseObjectAction and directly pass the input data to the DatabaseObjectEditor . These methods deny access to them via AJAX by default, unless you explicitly enable access. Depending on your case, there are two different strategies to enable AJAX access to them. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <? php namespace wcf\\data\\example ; use wcf\\data\\AbstractDatabaseObjectAction ; class ExampleAction extends AbstractDatabaseObjectAction { // `create()` can now be called via AJAX if the requesting user posses the listed permissions protected $permissionsCreate = [ 'admin.example.canManageExample' ]; public function validateUpdate () { // your very own validation logic that does not make use of the // built-in `$permissionsUpdate` property // you can still invoke the built-in permissions check if you like to parent :: validateUpdate (); } } Allow Invokation by Guests # Invoking methods is restricted to logged-in users by default and the only way to override this behavior is to alter the property $allowGuestAccess . It is a simple string array that is expected to hold all methods that should be accessible by users, excluding their companion validation methods. ACP Access Only # Method access is usually limited by permissions, but sometimes there might be the need for some added security to avoid mistakes. The $requireACP property works similar to $allowGuestAccess , but enforces the request to originate from the ACP together with a valid ACP session, ensuring that only users able to access the ACP can actually invoke these methods.","title":"Database Objects"},{"location":"php/database-objects/#database-objects","text":"WoltLab Suite uses a unified interface to work with database rows using an object based approach instead of using native arrays holding arbitrary data. Each database table is mapped to a model class that is designed to hold a single record from that table and expose methods to work with the stored data, for example providing assistance when working with normalized datasets. Developers are required to provide the proper DatabaseObject implementations themselves, they're not automatically generated, all though the actual code that needs to be written is rather small. The following examples assume the fictional database table wcf1_example , exampleID as the auto-incrementing primary key and the column bar to store some text.","title":"Database Objects"},{"location":"php/database-objects/#databaseobject","text":"The basic model derives from wcf\\data\\DatabaseObject and provides a convenient constructor to fetch a single row or construct an instance using pre-loaded rows. files/lib/data/example/Example.class.php 1 2 3 4 5 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObject ; class Example extends DatabaseObject {} The class is intended to be empty by default and there only needs to be code if you want to add additional logic to your model. Both the class name and primary key are determined by DatabaseObject using the namespace and class name of the derived class. The example above uses the namespace wcf\\\u2026 which is used as table prefix and the class name Example is converted into exampleID , resulting in the database table name wcfN_example with the primary key exampleID . You can prevent this automatic guessing by setting the class properties $databaseTableName and $databaseTableIndexName manually.","title":"DatabaseObject"},{"location":"php/database-objects/#databaseobjectdecorator","text":"If you already have a DatabaseObject class and would like to extend it with additional data or methods, for example by providing a class ViewableExample which features view-related changes without polluting the original object, you can use DatabaseObjectDecorator which a default implementation of a decorator for database objects. files/lib/data/example/ViewableExample.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectDecorator ; class ViewableExample extends DatabaseObjectDecorator { protected static $baseClass = Example :: class ; public function getOutput () { $output = '' ; // [determine output] return $output ; } } It is mandatory to set the static $baseClass property to the name of the decorated class. Like for any decorator, you can directly access the decorated object's properties and methods for a decorated object by accessing the property or calling the method on the decorated object. You can access the decorated objects directly via DatabaseObjectDecorator::getDecoratedObject() .","title":"DatabaseObjectDecorator"},{"location":"php/database-objects/#databaseobjecteditor","text":"This is the low-level interface to manipulate data rows, it is recommended to use AbstractDatabaseObjectAction . Adding, editing and deleting models is done using the DatabaseObjectEditor class that decorates a DatabaseObject and uses its data to perform the actions. files/lib/data/example/ExampleEditor.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectEditor ; class ExampleEditor extends DatabaseObjectEditor { protected static $baseClass = Example :: class ; } The editor class requires you to provide the fully qualified name of the model, that is the class name including the complete namespace. Database table name and index key will be pulled directly from the model.","title":"DatabaseObjectEditor"},{"location":"php/database-objects/#create-a-new-row","text":"Inserting a new row into the database table is provided through DatabaseObjectEditor::create() which yields a DatabaseObject instance after creation. 1 2 3 4 5 6 7 <? php $example = \\wcf\\data\\example\\ExampleEditor :: create ([ 'bar' => 'Hello World!' ]); // output: Hello World! echo $example -> bar ;","title":"Create a new row"},{"location":"php/database-objects/#updating-an-existing-row","text":"The internal state of the decorated DatabaseObject is not altered at any point, the values will still be the same after editing or deleting the represented row. If you need an object with the latest data, you'll have to discard the current object and refetch the data from database. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php $example = new \\wcf\\data\\example\\Example ( $id ); $exampleEditor = new \\wcf\\data\\example\\ExampleEditor ( $example ); $exampleEditor -> update ([ 'bar' => 'baz' ]); // output: Hello World! echo $example -> bar ; // re-creating the object will query the database again and retrieve the updated value $example = new \\wcf\\data\\example\\Example ( $example -> id ); // output: baz echo $example -> bar ;","title":"Updating an existing row"},{"location":"php/database-objects/#deleting-a-row","text":"Similar to the update process, the decorated DatabaseObject is not altered and will then point to an inexistent row. 1 2 3 4 <? php $example = new \\wcf\\data\\example\\Example ( $id ); $exampleEditor = new \\wcf\\data\\example\\ExampleEditor ( $example ); $exampleEditor -> delete ();","title":"Deleting a row"},{"location":"php/database-objects/#databaseobjectlist","text":"Every row is represented as a single instance of the model, but the instance creation deals with single rows only. Retrieving larger sets of rows would be quite inefficient due to the large amount of queries that will be dispatched. This is solved with the DatabaseObjectList object that exposes an interface to query the database table using arbitrary conditions for data selection. All rows will be fetched using a single query and the resulting rows are automatically loaded into separate models. files/lib/data/example/ExampleList.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectList ; class ExampleList extends DatabaseObjectList { public $className = Example :: class ; } The following code listing illustrates loading a large set of examples and iterating over the list to retrieve the objects. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php $exampleList = new \\wcf\\data\\example\\ExampleList (); // add constraints using the condition builder $exampleList -> getConditionBuilder () -> add ( 'bar IN (?)' , [[ 'Hello World!' , 'bar' , 'baz' ]]); // actually read the rows $exampleList -> readObjects (); foreach ( $exampleList as $example ) { echo $example -> bar ; } // retrieve the models directly instead of iterating over them $examples = $exampleList -> getObjects (); // just retrieve the number of rows $exampleCount = $exampleList -> countObjects (); DatabaseObjectList implements both SeekableIterator and Countable . Additionally, DatabaseObjectList objects has the following three public properties that are useful when fetching data with lists: $sqlLimit determines how many rows are fetched. If its value is 0 (which is the default value), all results are fetched. So be careful when dealing with large tables and you only want a limited number of rows: Set $sqlLimit to a value larger than zero! $sqlOffset : Paginated pages like a thread list use this feature a lot, it allows you to skip a given number of results. Imagine you want to display 20 threads per page but there are a total of 60 threads available. In this case you would specify $sqlLimit = 20 and $sqlOffset = 20 which will skip the first 20 threads, effectively displaying thread 21 to 40. $sqlOrderBy determines by which column(s) the rows are sorted in which order. Using our example in $sqlOffset you might want to display the 20 most recent threads on page 1, thus you should specify the order field and its direction, e.g. $sqlOrderBy = 'thread.lastPostTime DESC' which returns the most recent thread first. For more advanced usage, there two additional fields that deal with the type of objects returned. First, let's go into a bit more detail what setting the $className property actually does: It is the type of database object in which the rows are wrapped. It determines which database table is actually queried and which index is used (see the $databaseTableName and $databaseTableIndexName properties of DatabaseObject ). Sometimes you might use the database table of some database object but wrap the rows in another database object. This can be achieved by setting the $objectClassName property to the desired class name. In other cases, you might want to wrap the created objects in a database object decorator which can be done by setting the $decoratorClassName property to the desired class name: 1 2 3 <? php $exampleList = new \\wcf\\data\\example\\ExampleList (); $exampleList -> decoratorClassName = \\wcf\\data\\example\\ViewableExample :: class ; Of course, you do not have to set the property after creating the list object, you can also set it by creating a dedicated class: files/lib/data/example/ViewableExampleList.class.php 1 2 3 4 5 6 <? php namespace wcf\\data\\example ; class ViewableExampleList extends ExampleList { public $decoratorClassName = ViewableExample :: class ; }","title":"DatabaseObjectList"},{"location":"php/database-objects/#abstractdatabaseobjectaction","text":"Row creation and manipulation can be performed using the aforementioned DatabaseObjectEditor class, but this approach has two major issues: Row creation, update and deletion takes place silently without notifying any other components. Data is passed to the database adapter without any further processing. The AbstractDatabaseObjectAction solves both problems by wrapping around the editor class and thus provide an additional layer between the action that should be taken and the actual process. The first problem is solved by a fixed set of events being fired, the second issue is addressed by having a single entry point for all data editing. files/lib/data/example/ExampleAction.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\AbstractDatabaseObjectAction ; class ExampleAction extends AbstractDatabaseObjectAction { public $className = ExampleEditor :: class ; }","title":"AbstractDatabaseObjectAction"},{"location":"php/database-objects/#executing-an-action","text":"The method AbstractDatabaseObjectAction::validateAction() is internally used for AJAX method invocation and must not be called programmatically. The next example represents the same functionality as seen for DatabaseObjectEditor : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <? php use wcf\\data\\example\\ExampleAction ; // create a row $exampleAction = new ExampleAction ([], 'create' , [ 'data' => [ 'bar' => 'Hello World' ] ]); $example = $exampleAction -> executeAction ()[ 'returnValues' ]; // update a row using the id $exampleAction = new ExampleAction ([ 1 ], 'update' , [ 'data' => [ 'bar' => 'baz' ] ]); $exampleAction -> executeAction (); // delete a row using a model $exampleAction = new ExampleAction ([ $example ], 'delete' ); $exampleAction -> executeAction (); You can access the return values both by storing the return value of executeAction() or by retrieving it via getReturnValues() . Events initializeAction , validateAction and finalizeAction","title":"Executing an Action"},{"location":"php/database-objects/#custom-method-with-ajax-support","text":"This section is about adding the method baz() to ExampleAction and calling it via AJAX.","title":"Custom Method with AJAX Support"},{"location":"php/database-objects/#ajax-validation","text":"Methods of an action cannot be called via AJAX, unless they have a validation method. This means that ExampleAction must define both a public function baz() and public function validateBaz() , the name for the validation method is constructed by upper-casing the first character of the method name and prepending validate . The lack of the companion validate* method will cause the AJAX proxy to deny the request instantaneously. Do not add a validation method if you don't want it to be callable via AJAX ever!","title":"AJAX Validation"},{"location":"php/database-objects/#create-update-and-delete","text":"The methods create , update and delete are available for all classes deriving from AbstractDatabaseObjectAction and directly pass the input data to the DatabaseObjectEditor . These methods deny access to them via AJAX by default, unless you explicitly enable access. Depending on your case, there are two different strategies to enable AJAX access to them. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <? php namespace wcf\\data\\example ; use wcf\\data\\AbstractDatabaseObjectAction ; class ExampleAction extends AbstractDatabaseObjectAction { // `create()` can now be called via AJAX if the requesting user posses the listed permissions protected $permissionsCreate = [ 'admin.example.canManageExample' ]; public function validateUpdate () { // your very own validation logic that does not make use of the // built-in `$permissionsUpdate` property // you can still invoke the built-in permissions check if you like to parent :: validateUpdate (); } }","title":"create, update and delete"},{"location":"php/database-objects/#allow-invokation-by-guests","text":"Invoking methods is restricted to logged-in users by default and the only way to override this behavior is to alter the property $allowGuestAccess . It is a simple string array that is expected to hold all methods that should be accessible by users, excluding their companion validation methods.","title":"Allow Invokation by Guests"},{"location":"php/database-objects/#acp-access-only","text":"Method access is usually limited by permissions, but sometimes there might be the need for some added security to avoid mistakes. The $requireACP property works similar to $allowGuestAccess , but enforces the request to originate from the ACP together with a valid ACP session, ensuring that only users able to access the ACP can actually invoke these methods.","title":"ACP Access Only"},{"location":"php/exceptions/","text":"Exceptions # SPL Exceptions # The Standard PHP Library (SPL) provides some exceptions that should be used whenever possible. Custom Exceptions # Do not use wcf\\system\\exception\\SystemException anymore, use specific exception classes! The following table contains a list of custom exceptions that are commonly used. All of the exceptions are found in the wcf\\system\\exception namespace. Class name (examples) when to use IllegalLinkException access to a page that belongs to a non-existing object, executing actions on specific non-existing objects (is shown as http 404 error to the user) ImplementationException a class does not implement an expected interface InvalidObjectArgument 5.4+ API method support generic objects but specific implementation requires objects of specific (sub)class and different object is given InvalidObjectTypeException object type is not of an expected object type definition InvalidSecurityTokenException given security token does not match the security token of the active user's session ParentClassException a class does not extend an expected (parent) class PermissionDeniedException page access without permission, action execution without permission (is shown as http 403 error to the user) UserInputException user input does not pass validation Sensitive Arguments in Stack Traces # Sometimes sensitive values are passed as a function or method argument. If the callee throws an Exception, these values will be part of the Exception\u2019s stack trace and logged, unless the Exception is caught and ignored. WoltLab Suite will automatically suppress the values of parameters named like they might contain sensitive values, namely arguments matching the regular expression /(?:^(?:password|passphrase|secret)|(?:Password|Passphrase|Secret))/ . If you need to suppress additional arguments from appearing in the stack trace, you can add the \\wcf\\SensitiveArgument attribute to such parameters. Arguments are only supported as of PHP 8 and ignored as comments in lower PHP versions. In PHP 7, such arguments will not be suppressed, but the code will continue to work. Make sure to insert a linebreak between the attribute and the parameter name. Example: wcfsetup/install/files/lib/data/user/User.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php namespace wcf\\data\\user ; // \u2026 final class User extends DatabaseObject implements IPopoverObject , IRouteController , IUserContent { // \u2026 public function checkPassword ( #[\\wcf\\SensitiveArgument()] $password ) { // \u2026 } // \u2026 }","title":"Exceptions"},{"location":"php/exceptions/#exceptions","text":"","title":"Exceptions"},{"location":"php/exceptions/#spl-exceptions","text":"The Standard PHP Library (SPL) provides some exceptions that should be used whenever possible.","title":"SPL Exceptions"},{"location":"php/exceptions/#custom-exceptions","text":"Do not use wcf\\system\\exception\\SystemException anymore, use specific exception classes! The following table contains a list of custom exceptions that are commonly used. All of the exceptions are found in the wcf\\system\\exception namespace. Class name (examples) when to use IllegalLinkException access to a page that belongs to a non-existing object, executing actions on specific non-existing objects (is shown as http 404 error to the user) ImplementationException a class does not implement an expected interface InvalidObjectArgument 5.4+ API method support generic objects but specific implementation requires objects of specific (sub)class and different object is given InvalidObjectTypeException object type is not of an expected object type definition InvalidSecurityTokenException given security token does not match the security token of the active user's session ParentClassException a class does not extend an expected (parent) class PermissionDeniedException page access without permission, action execution without permission (is shown as http 403 error to the user) UserInputException user input does not pass validation","title":"Custom Exceptions"},{"location":"php/exceptions/#sensitive-arguments-in-stack-traces","text":"Sometimes sensitive values are passed as a function or method argument. If the callee throws an Exception, these values will be part of the Exception\u2019s stack trace and logged, unless the Exception is caught and ignored. WoltLab Suite will automatically suppress the values of parameters named like they might contain sensitive values, namely arguments matching the regular expression /(?:^(?:password|passphrase|secret)|(?:Password|Passphrase|Secret))/ . If you need to suppress additional arguments from appearing in the stack trace, you can add the \\wcf\\SensitiveArgument attribute to such parameters. Arguments are only supported as of PHP 8 and ignored as comments in lower PHP versions. In PHP 7, such arguments will not be suppressed, but the code will continue to work. Make sure to insert a linebreak between the attribute and the parameter name. Example: wcfsetup/install/files/lib/data/user/User.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php namespace wcf\\data\\user ; // \u2026 final class User extends DatabaseObject implements IPopoverObject , IRouteController , IUserContent { // \u2026 public function checkPassword ( #[\\wcf\\SensitiveArgument()] $password ) { // \u2026 } // \u2026 }","title":"Sensitive Arguments in Stack Traces"},{"location":"php/gdpr/","text":"General Data Protection Regulation (GDPR) # Introduction # The General Data Protection Regulation (GDPR) of the European Union enters into force on May 25, 2018. It comes with a set of restrictions when handling users' personal data as well as to provide an interface to export this data on demand. If you're looking for a guide on the implications of the GDPR and what you will need or consider to do, please read the article Implementation of the GDPR on woltlab.com. Including Data in the Export # The wcf\\acp\\action\\UserExportGdprAction already includes WoltLab Suite Core itself as well as all official apps, but you'll need to include any personal data stored for your plugin or app by yourself. The event export is fired before any data is sent out, but after any Core data has been dumped to the $data property. Example code # files/lib/system/event/listener/MyUserExportGdprActionListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\action\\UserExportGdprAction ; use wcf\\data\\user\\UserProfile ; class MyUserExportGdprActionListener implements IParameterizedEventListener { public function execute ( /** @var UserExportGdprAction $eventObj */ $eventObj , $className , $eventName , array & $parameters ) { /** @var UserProfile $user */ $user = $eventObj -> user ; $eventObj -> data [ 'my.fancy.plugin' ] = [ 'superPersonalData' => \"This text is super personal and should be included in the output\" , 'weirdIpAddresses' => $eventObj -> exportIpAddresses ( 'app' . WCF_N . '_non_standard_column_names_for_ip_addresses' , 'ipAddressColumnName' , 'timeColumnName' , 'userIDColumnName' ) ]; $eventObj -> exportUserProperties [] = 'shouldAlwaysExportThisField' ; $eventObj -> exportUserPropertiesIfNotEmpty [] = 'myFancyField' ; $eventObj -> exportUserOptionSettings [] = 'thisSettingIsAlwaysExported' ; $eventObj -> exportUserOptionSettingsIfNotEmpty [] = 'someSettingContainingPersonalData' ; $eventObj -> ipAddresses [ 'my.fancy.plugin' ] = [ 'wcf' . WCF_N . '_my_fancy_table' , 'wcf' . WCF_N . '_i_also_store_ipaddresses_here' ]; $eventObj -> skipUserOptions [] = 'thisLooksLikePersonalDataButItIsNot' ; $eventObj -> skipUserOptions [] = 'thisIsAlsoNotPersonalDataPleaseIgnoreIt' ; } } $data # Contains the entire data that will be included in the exported JSON file, some fields may already exist (such as 'com.woltlab.wcf' ) and while you may add or edit any fields within, you should restrict yourself to only append data from your plugin or app. $exportUserProperties # Only a whitelist of columns in wcfN_user is exported by default, if your plugin or app adds one or more columns to this table that do hold personal data, then you will have to append it to this array. The listed properties will always be included regardless of their content. $exportUserPropertiesIfNotEmpty # Only a whitelist of columns in wcfN_user is exported by default, if your plugin or app adds one or more columns to this table that do hold personal data, then you will have to append it to this array. Empty values will not be added to the output. $exportUserOptionSettings # Any user option that exists within a settings.* category is automatically excluded from the export, with the notable exception of the timezone option. You can opt-in to include your setting by appending to this array, if it contains any personal data. The listed settings are always included regardless of their content. $exportUserOptionSettingsIfNotEmpty # Any user option that exists within a settings.* category is automatically excluded from the export, with the notable exception of the timezone option. You can opt-in to include your setting by appending to this array, if it contains any personal data. $ipAddresses # List of database table names per package identifier that contain ip addresses. The contained ip addresses will be exported when the ip logging module is enabled. It expects the database table to use the column names ipAddress , time and userID . If your table does not match this pattern for whatever reason, you'll need to manually probe for LOG_IP_ADDRESS and then call exportIpAddresses() to retrieve the list. Afterwards you are responsible to append these ip addresses to the $data array to have it exported. $skipUserOptions # All user options are included in the export by default, unless they start with can* or admin* , or are blacklisted using this array. You should append any of your plugin's or app's user option that should not be exported, for example because it does not contain personal data, such as internal data.","title":"GDPR"},{"location":"php/gdpr/#general-data-protection-regulation-gdpr","text":"","title":"General Data Protection Regulation (GDPR)"},{"location":"php/gdpr/#introduction","text":"The General Data Protection Regulation (GDPR) of the European Union enters into force on May 25, 2018. It comes with a set of restrictions when handling users' personal data as well as to provide an interface to export this data on demand. If you're looking for a guide on the implications of the GDPR and what you will need or consider to do, please read the article Implementation of the GDPR on woltlab.com.","title":"Introduction"},{"location":"php/gdpr/#including-data-in-the-export","text":"The wcf\\acp\\action\\UserExportGdprAction already includes WoltLab Suite Core itself as well as all official apps, but you'll need to include any personal data stored for your plugin or app by yourself. The event export is fired before any data is sent out, but after any Core data has been dumped to the $data property.","title":"Including Data in the Export"},{"location":"php/gdpr/#example-code","text":"files/lib/system/event/listener/MyUserExportGdprActionListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\action\\UserExportGdprAction ; use wcf\\data\\user\\UserProfile ; class MyUserExportGdprActionListener implements IParameterizedEventListener { public function execute ( /** @var UserExportGdprAction $eventObj */ $eventObj , $className , $eventName , array & $parameters ) { /** @var UserProfile $user */ $user = $eventObj -> user ; $eventObj -> data [ 'my.fancy.plugin' ] = [ 'superPersonalData' => \"This text is super personal and should be included in the output\" , 'weirdIpAddresses' => $eventObj -> exportIpAddresses ( 'app' . WCF_N . '_non_standard_column_names_for_ip_addresses' , 'ipAddressColumnName' , 'timeColumnName' , 'userIDColumnName' ) ]; $eventObj -> exportUserProperties [] = 'shouldAlwaysExportThisField' ; $eventObj -> exportUserPropertiesIfNotEmpty [] = 'myFancyField' ; $eventObj -> exportUserOptionSettings [] = 'thisSettingIsAlwaysExported' ; $eventObj -> exportUserOptionSettingsIfNotEmpty [] = 'someSettingContainingPersonalData' ; $eventObj -> ipAddresses [ 'my.fancy.plugin' ] = [ 'wcf' . WCF_N . '_my_fancy_table' , 'wcf' . WCF_N . '_i_also_store_ipaddresses_here' ]; $eventObj -> skipUserOptions [] = 'thisLooksLikePersonalDataButItIsNot' ; $eventObj -> skipUserOptions [] = 'thisIsAlsoNotPersonalDataPleaseIgnoreIt' ; } }","title":"Example code"},{"location":"php/gdpr/#data","text":"Contains the entire data that will be included in the exported JSON file, some fields may already exist (such as 'com.woltlab.wcf' ) and while you may add or edit any fields within, you should restrict yourself to only append data from your plugin or app.","title":"$data"},{"location":"php/gdpr/#exportuserproperties","text":"Only a whitelist of columns in wcfN_user is exported by default, if your plugin or app adds one or more columns to this table that do hold personal data, then you will have to append it to this array. The listed properties will always be included regardless of their content.","title":"$exportUserProperties"},{"location":"php/gdpr/#exportuserpropertiesifnotempty","text":"Only a whitelist of columns in wcfN_user is exported by default, if your plugin or app adds one or more columns to this table that do hold personal data, then you will have to append it to this array. Empty values will not be added to the output.","title":"$exportUserPropertiesIfNotEmpty"},{"location":"php/gdpr/#exportuseroptionsettings","text":"Any user option that exists within a settings.* category is automatically excluded from the export, with the notable exception of the timezone option. You can opt-in to include your setting by appending to this array, if it contains any personal data. The listed settings are always included regardless of their content.","title":"$exportUserOptionSettings"},{"location":"php/gdpr/#exportuseroptionsettingsifnotempty","text":"Any user option that exists within a settings.* category is automatically excluded from the export, with the notable exception of the timezone option. You can opt-in to include your setting by appending to this array, if it contains any personal data.","title":"$exportUserOptionSettingsIfNotEmpty"},{"location":"php/gdpr/#ipaddresses","text":"List of database table names per package identifier that contain ip addresses. The contained ip addresses will be exported when the ip logging module is enabled. It expects the database table to use the column names ipAddress , time and userID . If your table does not match this pattern for whatever reason, you'll need to manually probe for LOG_IP_ADDRESS and then call exportIpAddresses() to retrieve the list. Afterwards you are responsible to append these ip addresses to the $data array to have it exported.","title":"$ipAddresses"},{"location":"php/gdpr/#skipuseroptions","text":"All user options are included in the export by default, unless they start with can* or admin* , or are blacklisted using this array. You should append any of your plugin's or app's user option that should not be exported, for example because it does not contain personal data, such as internal data.","title":"$skipUserOptions"},{"location":"php/pages/","text":"Page Types # AbstractPage # The default implementation for pages to present any sort of content, but are designed to handle GET requests only. They usually follow a fixed method chain that will be invoked one after another, adding logical sections to the request flow. Method Chain # __run() # This is the only method being invoked from the outside and starts the whole chain. readParameters() # Reads and sanitizes request parameters, this should be the only method to ever read user-supplied input. Read data should be stored in class properties to be accessible at a later point, allowing your code to safely assume that the data has been sanitized and is safe to work with. A typical example is the board page from the forum app that reads the id and attempts to identify the request forum. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) $this -> boardID = intval ( $_REQUEST [ 'id' ]); $this -> board = BoardCache :: getInstance () -> getBoard ( $this -> boardID ); if ( $this -> board === null ) { throw new IllegalLinkException (); } // check permissions if ( ! $this -> board -> canEnter ()) { throw new PermissionDeniedException (); } } Events readParameters show() # Used to be the method of choice to handle permissions and module option checks, but has been used almost entirely as an internal method since the introduction of the properties $loginRequired , $neededModules and $neededPermissions . Events checkModules , checkPermissions and show readData() # Central method for data retrieval based on class properties including those populated with user data in readParameters() . It is strongly recommended to use this method to read data in order to properly separate the business logic present in your class. Events readData assignVariables() # Last method call before the template engine kicks in and renders the template. All though some properties are bound to the template automatically, you still need to pass any custom variables and class properties to the engine to make them available in templates. Following the example in readParameters() , the code below adds the board data to the template. 1 2 3 4 5 6 7 8 public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'board' => $this -> board , 'boardID' => $this -> boardID ]); } Events assignVariables AbstractForm # Extends the AbstractPage implementation with additional methods designed to handle form submissions properly. Method Chain # __run() # Inherited from AbstractPage. readParameters() # Inherited from AbstractPage. show() # Inherited from AbstractPage. submit() # The methods submit() up until save() are only invoked if either $_POST or $_FILES are not empty, otherwise they won't be invoked and the execution will continue with readData() . This is an internal method that is responsible of input processing and validation. Events submit readFormParameters() # This method is quite similar to readParameters() that is being called earlier, but is designed around reading form data submitted through POST requests. You should avoid accessing $_GET or $_REQUEST in this context to avoid mixing up parameters evaluated when retrieving the page on first load and when submitting to it. Events readFormParameters validate() # Deals with input validation and automatically catches exceptions deriving from wcf\\system\\exception\\UserInputException , resulting in a clean and consistent error handling for the user. Events validate save() # Saves the processed data to database or any other source of your choice. Please keep in mind to invoke $this->saved() before resetting the form data. Events save saved() # This method is not called automatically and must be invoked manually by executing $this->saved() inside save() . The only purpose of this method is to fire the event saved that signals that the form data has been processed successfully and data has been saved. It is somewhat special as it is dispatched after the data has been saved, but before the data is purged during form reset. This is by default the last event that has access to the processed data. Events saved readData() # Inherited from AbstractPage. assignVariables() # Inherited from AbstractPage.","title":"Pages"},{"location":"php/pages/#page-types","text":"","title":"Page Types"},{"location":"php/pages/#abstractpage","text":"The default implementation for pages to present any sort of content, but are designed to handle GET requests only. They usually follow a fixed method chain that will be invoked one after another, adding logical sections to the request flow.","title":"AbstractPage"},{"location":"php/pages/#method-chain","text":"","title":"Method Chain"},{"location":"php/pages/#__run","text":"This is the only method being invoked from the outside and starts the whole chain.","title":"__run()"},{"location":"php/pages/#readparameters","text":"Reads and sanitizes request parameters, this should be the only method to ever read user-supplied input. Read data should be stored in class properties to be accessible at a later point, allowing your code to safely assume that the data has been sanitized and is safe to work with. A typical example is the board page from the forum app that reads the id and attempts to identify the request forum. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) $this -> boardID = intval ( $_REQUEST [ 'id' ]); $this -> board = BoardCache :: getInstance () -> getBoard ( $this -> boardID ); if ( $this -> board === null ) { throw new IllegalLinkException (); } // check permissions if ( ! $this -> board -> canEnter ()) { throw new PermissionDeniedException (); } } Events readParameters","title":"readParameters()"},{"location":"php/pages/#show","text":"Used to be the method of choice to handle permissions and module option checks, but has been used almost entirely as an internal method since the introduction of the properties $loginRequired , $neededModules and $neededPermissions . Events checkModules , checkPermissions and show","title":"show()"},{"location":"php/pages/#readdata","text":"Central method for data retrieval based on class properties including those populated with user data in readParameters() . It is strongly recommended to use this method to read data in order to properly separate the business logic present in your class. Events readData","title":"readData()"},{"location":"php/pages/#assignvariables","text":"Last method call before the template engine kicks in and renders the template. All though some properties are bound to the template automatically, you still need to pass any custom variables and class properties to the engine to make them available in templates. Following the example in readParameters() , the code below adds the board data to the template. 1 2 3 4 5 6 7 8 public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'board' => $this -> board , 'boardID' => $this -> boardID ]); } Events assignVariables","title":"assignVariables()"},{"location":"php/pages/#abstractform","text":"Extends the AbstractPage implementation with additional methods designed to handle form submissions properly.","title":"AbstractForm"},{"location":"php/pages/#method-chain_1","text":"","title":"Method Chain"},{"location":"php/pages/#__run_1","text":"Inherited from AbstractPage.","title":"__run()"},{"location":"php/pages/#readparameters_1","text":"Inherited from AbstractPage.","title":"readParameters()"},{"location":"php/pages/#show_1","text":"Inherited from AbstractPage.","title":"show()"},{"location":"php/pages/#submit","text":"The methods submit() up until save() are only invoked if either $_POST or $_FILES are not empty, otherwise they won't be invoked and the execution will continue with readData() . This is an internal method that is responsible of input processing and validation. Events submit","title":"submit()"},{"location":"php/pages/#readformparameters","text":"This method is quite similar to readParameters() that is being called earlier, but is designed around reading form data submitted through POST requests. You should avoid accessing $_GET or $_REQUEST in this context to avoid mixing up parameters evaluated when retrieving the page on first load and when submitting to it. Events readFormParameters","title":"readFormParameters()"},{"location":"php/pages/#validate","text":"Deals with input validation and automatically catches exceptions deriving from wcf\\system\\exception\\UserInputException , resulting in a clean and consistent error handling for the user. Events validate","title":"validate()"},{"location":"php/pages/#save","text":"Saves the processed data to database or any other source of your choice. Please keep in mind to invoke $this->saved() before resetting the form data. Events save","title":"save()"},{"location":"php/pages/#saved","text":"This method is not called automatically and must be invoked manually by executing $this->saved() inside save() . The only purpose of this method is to fire the event saved that signals that the form data has been processed successfully and data has been saved. It is somewhat special as it is dispatched after the data has been saved, but before the data is purged during form reset. This is by default the last event that has access to the processed data. Events saved","title":"saved()"},{"location":"php/pages/#readdata_1","text":"Inherited from AbstractPage.","title":"readData()"},{"location":"php/pages/#assignvariables_1","text":"Inherited from AbstractPage.","title":"assignVariables()"},{"location":"php/api/caches/","text":"Caches # WoltLab Suite offers two distinct types of caches: Persistent caches created by cache builders whose data can be stored using different cache sources. Runtime caches store objects for the duration of a single request. Understanding Caching # Every so often, plugins make use of cache builders or runtime caches to store their data, even if there is absolutely no need for them to do so. Usually, this involves a strong opinion about the total number of SQL queries on a page, including but not limited to some magic treshold numbers, which should not be exceeded for \"performance reasons\". This misconception can easily lead into thinking that SQL queries should be avoided or at least written to a cache, so that it doesn't need to be executed so often. Unfortunately, this completely ignores the fact that both a single query can take down your app (e. g. full table scan on millions of rows), but 10 queries using a primary key on a table with a few hundred rows will not slow down your page. There are some queries that should go into caches by design, but most of the cache builders weren't initially there, but instead have been added because they were required to reduce the load significantly . You need to understand that caches always come at a cost, even a runtime cache does! In particular, they will always consume memory that is not released over the duration of the request lifecycle and potentially even leak memory by holding references to objects and data structures that are no longer required. Caching should always be a solution for a problem. When to Use a Cache # It's difficult to provide a definite answer or checklist when to use a cache and why it is required at this point, because the answer is: It depends. The permission cache for user groups is a good example for a valid cache, where we can achieve significant performance improvement compared to processing this data on every request. Its caches are build for each permutation of user group memberships that are encountered for a page request. Building this data is an expensive process that involves both inheritance and specific rules in regards to when a value for a permission overrules another value. The added benefit of this cache is that one cache usually serves a large number of users with the same group memberships and by computing these permissions once, we can serve many different requests. Also, the permissions are rather static values that change very rarely and thus we can expect a very high cache lifetime before it gets rebuild. When not to Use a Cache # I remember, a few years ago, there was a plugin that displayed a user's character from an online video game. The character sheet not only included a list of basic statistics, but also displayed the items that this character was wearing and or holding at the time. The data for these items were downloaded in bulk from the game's vendor servers and stored in a persistent cache file that periodically gets renewed. There is nothing wrong with the idea of caching the data on your own server rather than requesting them everytime from the vendor's servers - not only because they imposed a limit on the number of requests per hour. Unfortunately, the character sheet had a sub-par performance and the users were upset by the significant loading times compared to literally every other page on the same server. The author of the plugin was working hard to resolve this issue and was evaluating all kind of methods to improve the page performance, including deep-diving into the realm of micro-optimizations to squeeze out every last bit of performance that is possible. The real problem was the cache file itself, it turns out that it was holding the data for several thousand items with a total file size of about 13 megabytes. It doesn't look that much at first glance, after all this isn't the '90s anymore, but unserializing a 13 megabyte array is really slow and looking up items in such a large array isn't exactly fast either. The solution was rather simple, the data that was fetched from the vendor's API was instead written into a separate database table. Next, the persistent cache was removed and the character sheet would now request the item data for that specific character straight from the database. Previously, the character sheet took several seconds to load and after the change it was done in a fraction of a second. Although quite extreme, this illustrates a situation where the cache file was introduced in the design process, without evaluating if the cache - at least how it was implemented - was really necessary. Caching should always be a solution for a problem. Not the other way around.","title":"Overview"},{"location":"php/api/caches/#caches","text":"WoltLab Suite offers two distinct types of caches: Persistent caches created by cache builders whose data can be stored using different cache sources. Runtime caches store objects for the duration of a single request.","title":"Caches"},{"location":"php/api/caches/#understanding-caching","text":"Every so often, plugins make use of cache builders or runtime caches to store their data, even if there is absolutely no need for them to do so. Usually, this involves a strong opinion about the total number of SQL queries on a page, including but not limited to some magic treshold numbers, which should not be exceeded for \"performance reasons\". This misconception can easily lead into thinking that SQL queries should be avoided or at least written to a cache, so that it doesn't need to be executed so often. Unfortunately, this completely ignores the fact that both a single query can take down your app (e. g. full table scan on millions of rows), but 10 queries using a primary key on a table with a few hundred rows will not slow down your page. There are some queries that should go into caches by design, but most of the cache builders weren't initially there, but instead have been added because they were required to reduce the load significantly . You need to understand that caches always come at a cost, even a runtime cache does! In particular, they will always consume memory that is not released over the duration of the request lifecycle and potentially even leak memory by holding references to objects and data structures that are no longer required. Caching should always be a solution for a problem.","title":"Understanding Caching"},{"location":"php/api/caches/#when-to-use-a-cache","text":"It's difficult to provide a definite answer or checklist when to use a cache and why it is required at this point, because the answer is: It depends. The permission cache for user groups is a good example for a valid cache, where we can achieve significant performance improvement compared to processing this data on every request. Its caches are build for each permutation of user group memberships that are encountered for a page request. Building this data is an expensive process that involves both inheritance and specific rules in regards to when a value for a permission overrules another value. The added benefit of this cache is that one cache usually serves a large number of users with the same group memberships and by computing these permissions once, we can serve many different requests. Also, the permissions are rather static values that change very rarely and thus we can expect a very high cache lifetime before it gets rebuild.","title":"When to Use a Cache"},{"location":"php/api/caches/#when-not-to-use-a-cache","text":"I remember, a few years ago, there was a plugin that displayed a user's character from an online video game. The character sheet not only included a list of basic statistics, but also displayed the items that this character was wearing and or holding at the time. The data for these items were downloaded in bulk from the game's vendor servers and stored in a persistent cache file that periodically gets renewed. There is nothing wrong with the idea of caching the data on your own server rather than requesting them everytime from the vendor's servers - not only because they imposed a limit on the number of requests per hour. Unfortunately, the character sheet had a sub-par performance and the users were upset by the significant loading times compared to literally every other page on the same server. The author of the plugin was working hard to resolve this issue and was evaluating all kind of methods to improve the page performance, including deep-diving into the realm of micro-optimizations to squeeze out every last bit of performance that is possible. The real problem was the cache file itself, it turns out that it was holding the data for several thousand items with a total file size of about 13 megabytes. It doesn't look that much at first glance, after all this isn't the '90s anymore, but unserializing a 13 megabyte array is really slow and looking up items in such a large array isn't exactly fast either. The solution was rather simple, the data that was fetched from the vendor's API was instead written into a separate database table. Next, the persistent cache was removed and the character sheet would now request the item data for that specific character straight from the database. Previously, the character sheet took several seconds to load and after the change it was done in a fraction of a second. Although quite extreme, this illustrates a situation where the cache file was introduced in the design process, without evaluating if the cache - at least how it was implemented - was really necessary. Caching should always be a solution for a problem. Not the other way around.","title":"When not to Use a Cache"},{"location":"php/api/caches_persistent-caches/","text":"Persistent Caches # Relational databases are designed around the principle of normalized data that is organized across clearly separated tables with defined releations between data rows. While this enables you to quickly access and modify individual rows and columns, it can create the problem that re-assembling this data into a more complex structure can be quite expensive. For example, the user group permissions are stored for each user group and each permissions separately, but in order to be applied, they need to be fetched and the cumulative values across all user groups of an user have to be calculated. These repetitive tasks on barely ever changing data make them an excellent target for caching, where all sub-sequent requests are accelerated because they no longer have to perform the same expensive calculations every time. It is easy to get lost in the realm of caching, especially when it comes to the decision if you should use a cache or not. When in doubt, you should opt to not use them, because they also come at a hidden cost that cannot be expressed through simple SQL query counts. If you haven't already, it is recommended that you read the introduction article on caching first, it provides a bit of background on caches and examples that should help you in your decision. AbstractCacheBuilder # Every cache builder should derive from the base class AbstractCacheBuilder that already implements the mandatory interface ICacheBuilder . files/lib/system/cache/builder/ExampleCacheBuilder.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php namespace wcf\\system\\cache\\builder ; class ExampleCacheBuilder extends AbstractCacheBuilder { // 3600 = 1hr protected $maxLifetime = 3600 ; public function rebuild ( array $parameters ) { $data = []; // fetch and process your data and assign it to `$data` return $data ; } } Reading data from your cache builder is quite simple and follows a consistent pattern. The callee only needs to know the name of the cache builder, which parameters it requires and how the returned data looks like. It does not need to know how the data is retrieve, where it was stored, nor if it had to be rebuild due to the maximum lifetime. 1 2 3 4 <? php use wcf\\system\\cache\\builder\\ExampleCacheBuilder ; $data = ExampleCacheBuilder :: getInstance () -> getData ( $parameters ); getData(array $parameters = [], string $arrayIndex = ''): array # Retrieves the data from the cache builder, the $parameters array is automatically sorted to allow sub-sequent requests for the same parameters to be recognized, even if their parameters are mixed. For example, getData([1, 2]) and getData([2, 1]) will have the same exact result. The optional $arrayIndex will instruct the cache builder to retrieve the data and examine if the returned data is an array that has the index $arrayIndex . If it is set, the potion below this index is returned instead. getMaxLifetime(): int # Returns the maximum lifetime of a cache in seconds. It can be controlled through the protected $maxLifetime property which defaults to 0 . Any cache that has a lifetime greater than 0 is automatically discarded when exceeding this age, otherwise it will remain forever until it is explicitly removed or invalidated. reset(array $parameters = []): void # Invalidates a cache, the $parameters array will again be ordered using the same rules that are applied for getData() . rebuild(array $parameters): array # This method is protected. This is the only method that a cache builder deriving from AbstractCacheBuilder has to implement and it will be invoked whenever the cache is required to be rebuild for whatever reason.","title":"Persistent Caches"},{"location":"php/api/caches_persistent-caches/#persistent-caches","text":"Relational databases are designed around the principle of normalized data that is organized across clearly separated tables with defined releations between data rows. While this enables you to quickly access and modify individual rows and columns, it can create the problem that re-assembling this data into a more complex structure can be quite expensive. For example, the user group permissions are stored for each user group and each permissions separately, but in order to be applied, they need to be fetched and the cumulative values across all user groups of an user have to be calculated. These repetitive tasks on barely ever changing data make them an excellent target for caching, where all sub-sequent requests are accelerated because they no longer have to perform the same expensive calculations every time. It is easy to get lost in the realm of caching, especially when it comes to the decision if you should use a cache or not. When in doubt, you should opt to not use them, because they also come at a hidden cost that cannot be expressed through simple SQL query counts. If you haven't already, it is recommended that you read the introduction article on caching first, it provides a bit of background on caches and examples that should help you in your decision.","title":"Persistent Caches"},{"location":"php/api/caches_persistent-caches/#abstractcachebuilder","text":"Every cache builder should derive from the base class AbstractCacheBuilder that already implements the mandatory interface ICacheBuilder . files/lib/system/cache/builder/ExampleCacheBuilder.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php namespace wcf\\system\\cache\\builder ; class ExampleCacheBuilder extends AbstractCacheBuilder { // 3600 = 1hr protected $maxLifetime = 3600 ; public function rebuild ( array $parameters ) { $data = []; // fetch and process your data and assign it to `$data` return $data ; } } Reading data from your cache builder is quite simple and follows a consistent pattern. The callee only needs to know the name of the cache builder, which parameters it requires and how the returned data looks like. It does not need to know how the data is retrieve, where it was stored, nor if it had to be rebuild due to the maximum lifetime. 1 2 3 4 <? php use wcf\\system\\cache\\builder\\ExampleCacheBuilder ; $data = ExampleCacheBuilder :: getInstance () -> getData ( $parameters );","title":"AbstractCacheBuilder"},{"location":"php/api/caches_persistent-caches/#getdataarray-parameters-string-arrayindex-array","text":"Retrieves the data from the cache builder, the $parameters array is automatically sorted to allow sub-sequent requests for the same parameters to be recognized, even if their parameters are mixed. For example, getData([1, 2]) and getData([2, 1]) will have the same exact result. The optional $arrayIndex will instruct the cache builder to retrieve the data and examine if the returned data is an array that has the index $arrayIndex . If it is set, the potion below this index is returned instead.","title":"getData(array $parameters = [], string $arrayIndex = ''): array"},{"location":"php/api/caches_persistent-caches/#getmaxlifetime-int","text":"Returns the maximum lifetime of a cache in seconds. It can be controlled through the protected $maxLifetime property which defaults to 0 . Any cache that has a lifetime greater than 0 is automatically discarded when exceeding this age, otherwise it will remain forever until it is explicitly removed or invalidated.","title":"getMaxLifetime(): int"},{"location":"php/api/caches_persistent-caches/#resetarray-parameters-void","text":"Invalidates a cache, the $parameters array will again be ordered using the same rules that are applied for getData() .","title":"reset(array $parameters = []): void"},{"location":"php/api/caches_persistent-caches/#rebuildarray-parameters-array","text":"This method is protected. This is the only method that a cache builder deriving from AbstractCacheBuilder has to implement and it will be invoked whenever the cache is required to be rebuild for whatever reason.","title":"rebuild(array $parameters): array"},{"location":"php/api/caches_runtime-caches/","text":"Runtime Caches # Runtime caches store objects created during the runtime of the script and are automatically discarded after the script terminates. Runtime caches are especially useful when objects are fetched by different APIs, each requiring separate requests. By using a runtime cache, you have two advantages: If the API allows it, you can delay fetching the actual objects and initially only tell the runtime cache that at some point in the future of the current request, you need the objects with the given ids. If multiple APIs do this one after another, all objects can be fetched using only one query instead of each API querying the database on its own. If an object with the same ID has already been fetched from database, this object is simply returned and can be reused instead of being fetched from database again. IRuntimeCache # Every runtime cache has to implement the IRuntimeCache interface. It is recommended, however, that you extend AbstractRuntimeCache , the default implementation of the runtime cache interface. In most instances, you only need to set the AbstractRuntimeCache::$listClassName property to the name of database object list class which fetches the cached objects from database (see example ). Usage # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <? php use wcf\\system\\cache\\runtime\\UserRuntimeCache ; $userIDs = [ 1 , 2 ]; // first (optional) step: tell runtime cache to remember user ids UserRuntimeCache :: getInstance () -> cacheObjectIDs ( $userIDs ); // [\u2026] // second step: fetch the objects from database $users = UserRuntimeCache :: getInstance () -> getObjects ( $userIDs ); // somewhere else: fetch only one user $userID = 1 ; UserRuntimeCache :: getInstance () -> cacheObjectID ( $userID ); // [\u2026] // get user without the cache actually fetching it from database because it has already been loaded $user = UserRuntimeCache :: getInstance () -> getObject ( $userID ); // somewhere else: fetch users directly without caching user ids first $users = UserRuntimeCache :: getInstance () -> getObjects ([ 3 , 4 ]); Example # files/lib/system/cache/runtime/UserRuntimeCache.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? php namespace wcf\\system\\cache\\runtime ; use wcf\\data\\user\\User ; use wcf\\data\\user\\UserList ; /** * Runtime cache implementation for users. * * @author Matthias Schmidt * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cache\\Runtime * @since 3.0 * * @method User[] getCachedObjects() * @method User getObject($objectID) * @method User[] getObjects(array $objectIDs) */ class UserRuntimeCache extends AbstractRuntimeCache { /** * @inheritDoc */ protected $listClassName = UserList :: class ; }","title":"Runtime Caches"},{"location":"php/api/caches_runtime-caches/#runtime-caches","text":"Runtime caches store objects created during the runtime of the script and are automatically discarded after the script terminates. Runtime caches are especially useful when objects are fetched by different APIs, each requiring separate requests. By using a runtime cache, you have two advantages: If the API allows it, you can delay fetching the actual objects and initially only tell the runtime cache that at some point in the future of the current request, you need the objects with the given ids. If multiple APIs do this one after another, all objects can be fetched using only one query instead of each API querying the database on its own. If an object with the same ID has already been fetched from database, this object is simply returned and can be reused instead of being fetched from database again.","title":"Runtime Caches"},{"location":"php/api/caches_runtime-caches/#iruntimecache","text":"Every runtime cache has to implement the IRuntimeCache interface. It is recommended, however, that you extend AbstractRuntimeCache , the default implementation of the runtime cache interface. In most instances, you only need to set the AbstractRuntimeCache::$listClassName property to the name of database object list class which fetches the cached objects from database (see example ).","title":"IRuntimeCache"},{"location":"php/api/caches_runtime-caches/#usage","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <? php use wcf\\system\\cache\\runtime\\UserRuntimeCache ; $userIDs = [ 1 , 2 ]; // first (optional) step: tell runtime cache to remember user ids UserRuntimeCache :: getInstance () -> cacheObjectIDs ( $userIDs ); // [\u2026] // second step: fetch the objects from database $users = UserRuntimeCache :: getInstance () -> getObjects ( $userIDs ); // somewhere else: fetch only one user $userID = 1 ; UserRuntimeCache :: getInstance () -> cacheObjectID ( $userID ); // [\u2026] // get user without the cache actually fetching it from database because it has already been loaded $user = UserRuntimeCache :: getInstance () -> getObject ( $userID ); // somewhere else: fetch users directly without caching user ids first $users = UserRuntimeCache :: getInstance () -> getObjects ([ 3 , 4 ]);","title":"Usage"},{"location":"php/api/caches_runtime-caches/#example","text":"files/lib/system/cache/runtime/UserRuntimeCache.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? php namespace wcf\\system\\cache\\runtime ; use wcf\\data\\user\\User ; use wcf\\data\\user\\UserList ; /** * Runtime cache implementation for users. * * @author Matthias Schmidt * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cache\\Runtime * @since 3.0 * * @method User[] getCachedObjects() * @method User getObject($objectID) * @method User[] getObjects(array $objectIDs) */ class UserRuntimeCache extends AbstractRuntimeCache { /** * @inheritDoc */ protected $listClassName = UserList :: class ; }","title":"Example"},{"location":"php/api/comments/","text":"Comments # User Group Options # You need to create the following permissions: user group type permission type naming user creating comments user.foo.canAddComment user editing own comments user.foo.canEditComment user deleting own comments user.foo.canDeleteComment moderator moderating comments mod.foo.canModerateComment moderator editing comments mod.foo.canEditComment moderator deleting comments mod.foo.canDeleteComment Within their respective user group option category, the options should be listed in the same order as in the table above. Language Items # User Group Options # The language items for the comment-related user group options generally have the same values: wcf.acp.group.option.user.foo.canAddComment German: Kann Kommentare erstellen English: Can create comments wcf.acp.group.option.user.foo.canEditComment German: Kann eigene Kommentare bearbeiten English: Can edit their comments wcf.acp.group.option.user.foo.canDeleteComment German: Kann eigene Kommentare l\u00f6schen English: Can delete their comments wcf.acp.group.option.mod.foo.canModerateComment German: Kann Kommentare moderieren English: Can moderate comments wcf.acp.group.option.mod.foo.canEditComment German: Kann Kommentare bearbeiten English: Can edit comments wcf.acp.group.option.mod.foo.canDeleteComment German: Kann Kommentare l\u00f6schen English: Can delete comments","title":"Comments"},{"location":"php/api/comments/#comments","text":"","title":"Comments"},{"location":"php/api/comments/#user-group-options","text":"You need to create the following permissions: user group type permission type naming user creating comments user.foo.canAddComment user editing own comments user.foo.canEditComment user deleting own comments user.foo.canDeleteComment moderator moderating comments mod.foo.canModerateComment moderator editing comments mod.foo.canEditComment moderator deleting comments mod.foo.canDeleteComment Within their respective user group option category, the options should be listed in the same order as in the table above.","title":"User Group Options"},{"location":"php/api/comments/#language-items","text":"","title":"Language Items"},{"location":"php/api/comments/#user-group-options_1","text":"The language items for the comment-related user group options generally have the same values: wcf.acp.group.option.user.foo.canAddComment German: Kann Kommentare erstellen English: Can create comments wcf.acp.group.option.user.foo.canEditComment German: Kann eigene Kommentare bearbeiten English: Can edit their comments wcf.acp.group.option.user.foo.canDeleteComment German: Kann eigene Kommentare l\u00f6schen English: Can delete their comments wcf.acp.group.option.mod.foo.canModerateComment German: Kann Kommentare moderieren English: Can moderate comments wcf.acp.group.option.mod.foo.canEditComment German: Kann Kommentare bearbeiten English: Can edit comments wcf.acp.group.option.mod.foo.canDeleteComment German: Kann Kommentare l\u00f6schen English: Can delete comments","title":"User Group Options"},{"location":"php/api/cronjobs/","text":"Cronjobs # Cronjobs offer an easy way to execute actions periodically, like cleaning up the database. The execution of cronjobs is not guaranteed but requires someone to access the page with JavaScript enabled. This page focuses on the technical aspects of cronjobs, the cronjob package installation plugin page covers how you can actually register a cronjob. Example # files/lib/system/cronjob/LastActivityCronjob.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <? php namespace wcf\\system\\cronjob ; use wcf\\data\\cronjob\\Cronjob ; use wcf\\system\\WCF ; /** * Updates the last activity timestamp in the user table. * * @author Marcel Werk * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cronjob */ class LastActivityCronjob extends AbstractCronjob { /** * @inheritDoc */ public function execute ( Cronjob $cronjob ) { parent :: execute ( $cronjob ); $sql = \"UPDATE wcf\" . WCF_N . \"_user user_table, wcf\" . WCF_N . \"_session session SET user_table.lastActivityTime = session.lastActivityTime WHERE user_table.userID = session.userID AND session.userID <> 0\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); } } ICronjob Interface # Every cronjob needs to implement the wcf\\system\\cronjob\\ICronjob interface which requires the execute(Cronjob $cronjob) method to be implemented. This method is called by wcf\\system\\cronjob\\CronjobScheduler when executing the cronjobs. In practice, however, you should extend the AbstractCronjob class and also call the AbstractCronjob::execute() method as it fires an event which makes cronjobs extendable by plugins (see event documentation ). Executing Cronjobs Through CLI # Cronjobs can be executed through the command-line interface (CLI): 1 2 3 4 5 php /path/to/wcf/cli.php << 'EOT' USERNAME PASSWORD cronjob execute EOT","title":"Cronjobs"},{"location":"php/api/cronjobs/#cronjobs","text":"Cronjobs offer an easy way to execute actions periodically, like cleaning up the database. The execution of cronjobs is not guaranteed but requires someone to access the page with JavaScript enabled. This page focuses on the technical aspects of cronjobs, the cronjob package installation plugin page covers how you can actually register a cronjob.","title":"Cronjobs"},{"location":"php/api/cronjobs/#example","text":"files/lib/system/cronjob/LastActivityCronjob.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <? php namespace wcf\\system\\cronjob ; use wcf\\data\\cronjob\\Cronjob ; use wcf\\system\\WCF ; /** * Updates the last activity timestamp in the user table. * * @author Marcel Werk * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cronjob */ class LastActivityCronjob extends AbstractCronjob { /** * @inheritDoc */ public function execute ( Cronjob $cronjob ) { parent :: execute ( $cronjob ); $sql = \"UPDATE wcf\" . WCF_N . \"_user user_table, wcf\" . WCF_N . \"_session session SET user_table.lastActivityTime = session.lastActivityTime WHERE user_table.userID = session.userID AND session.userID <> 0\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); } }","title":"Example"},{"location":"php/api/cronjobs/#icronjob-interface","text":"Every cronjob needs to implement the wcf\\system\\cronjob\\ICronjob interface which requires the execute(Cronjob $cronjob) method to be implemented. This method is called by wcf\\system\\cronjob\\CronjobScheduler when executing the cronjobs. In practice, however, you should extend the AbstractCronjob class and also call the AbstractCronjob::execute() method as it fires an event which makes cronjobs extendable by plugins (see event documentation ).","title":"ICronjob Interface"},{"location":"php/api/cronjobs/#executing-cronjobs-through-cli","text":"Cronjobs can be executed through the command-line interface (CLI): 1 2 3 4 5 php /path/to/wcf/cli.php << 'EOT' USERNAME PASSWORD cronjob execute EOT","title":"Executing Cronjobs Through CLI"},{"location":"php/api/event_list/","text":"Event List # Events whose name is marked with an asterisk are called from a static method and thus do not provide any object, just the class name. WoltLab Suite Core # Class Event Name wcf\\acp\\action\\UserExportGdprAction export wcf\\acp\\form\\StyleAddForm setVariables wcf\\acp\\form\\UserSearchForm search wcf\\action\\AbstractAction checkModules wcf\\action\\AbstractAction checkPermissions wcf\\action\\AbstractAction execute wcf\\action\\AbstractAction executed wcf\\action\\AbstractAction readParameters wcf\\data\\attachment\\AttachmentAction generateThumbnail wcf\\data\\session\\SessionAction keepAlive wcf\\data\\session\\SessionAction poll wcf\\data\\trophy\\Trophy renderTrophy wcf\\data\\user\\online\\UserOnline getBrowser wcf\\data\\user\\online\\UserOnlineList isVisible wcf\\data\\user\\trophy\\UserTrophy getReplacements wcf\\data\\user\\UserAction beforeFindUsers wcf\\data\\user\\UserAction rename wcf\\data\\user\\UserProfile getAvatar wcf\\data\\user\\UserProfile isAccessible wcf\\data\\AbstractDatabaseObjectAction finalizeAction wcf\\data\\AbstractDatabaseObjectAction initializeAction wcf\\data\\AbstractDatabaseObjectAction validateAction wcf\\data\\DatabaseObjectList init wcf\\form\\AbstractForm readFormParameters wcf\\form\\AbstractForm save wcf\\form\\AbstractForm saved wcf\\form\\AbstractForm submit wcf\\form\\AbstractForm validate wcf\\form\\AbstractModerationForm prepareSave wcf\\page\\AbstractPage assignVariables wcf\\page\\AbstractPage checkModules wcf\\page\\AbstractPage checkPermissions wcf\\page\\AbstractPage readData wcf\\page\\AbstractPage readParameters wcf\\page\\AbstractPage show wcf\\page\\MultipleLinkPage beforeReadObjects wcf\\page\\MultipleLinkPage calculateNumberOfPages wcf\\page\\MultipleLinkPage countItems wcf\\page\\SortablePage validateSortField wcf\\page\\SortablePage validateSortOrder wcf\\system\\bbcode\\MessageParser afterParsing wcf\\system\\bbcode\\MessageParser beforeParsing wcf\\system\\bbcode\\SimpleMessageParser afterParsing wcf\\system\\bbcode\\SimpleMessageParser beforeParsing wcf\\system\\box\\AbstractBoxController __construct wcf\\system\\box\\AbstractBoxController afterLoadContent wcf\\system\\box\\AbstractBoxController beforeLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController afterLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController beforeLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController hasContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController readObjects wcf\\system\\cronjob\\AbstractCronjob execute wcf\\system\\email\\Email getJobs wcf\\system\\form\\builder\\container\\wysiwyg\\WysiwygFormContainer populate wcf\\system\\html\\input\\filter\\MessageHtmlInputFilter setAttributeDefinitions wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor afterProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor beforeEmbeddedProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor beforeProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor convertPlainLinks wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor getTextContent wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor parseEmbeddedContent wcf\\system\\html\\input\\node\\HtmlInputNodeWoltlabMetacodeMarker filterGroups wcf\\system\\html\\output\\node\\HtmlOutputNodePre selectHighlighter wcf\\system\\html\\output\\node\\HtmlOutputNodeProcessor beforeProcess wcf\\system\\image\\adapter\\ImagickImageAdapter getResizeFilter wcf\\system\\menu\\user\\profile\\UserProfileMenu init wcf\\system\\menu\\user\\profile\\UserProfileMenu loadCache wcf\\system\\menu\\TreeMenu init wcf\\system\\menu\\TreeMenu loadCache wcf\\system\\message\\QuickReplyManager addFullQuote wcf\\system\\message\\QuickReplyManager allowedDataParameters wcf\\system\\message\\QuickReplyManager beforeRenderQuote wcf\\system\\message\\QuickReplyManager createMessage wcf\\system\\message\\QuickReplyManager createdMessage wcf\\system\\message\\QuickReplyManager getMessage wcf\\system\\message\\QuickReplyManager validateParameters wcf\\system\\option\\OptionHandler afterReadCache wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin construct wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin hasUninstall wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin install wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin uninstall wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin update wcf\\system\\package\\plugin\\ObjectTypePackageInstallationPlugin addConditionFields wcf\\system\\package\\PackageInstallationDispatcher postInstall wcf\\system\\package\\PackageUninstallationDispatcher postUninstall wcf\\system\\reaction\\ReactionHandler getDataAttributes wcf\\system\\request\\RouteHandler didInit wcf\\system\\session\\ACPSessionFactory afterInit wcf\\system\\session\\ACPSessionFactory beforeInit wcf\\system\\session\\SessionHandler afterChangeUser wcf\\system\\session\\SessionHandler beforeChangeUser wcf\\system\\style\\StyleCompiler compile wcf\\system\\template\\TemplateEngine afterDisplay wcf\\system\\template\\TemplateEngine beforeDisplay wcf\\system\\upload\\DefaultUploadFileSaveStrategy generateThumbnails wcf\\system\\upload\\DefaultUploadFileSaveStrategy save wcf\\system\\user\\authentication\\UserAuthenticationFactory init wcf\\system\\user\\notification\\UserNotificationHandler createdNotification wcf\\system\\user\\notification\\UserNotificationHandler fireEvent wcf\\system\\user\\notification\\UserNotificationHandler markAsConfirmed wcf\\system\\user\\notification\\UserNotificationHandler markAsConfirmedByIDs wcf\\system\\user\\notification\\UserNotificationHandler removeNotifications wcf\\system\\user\\notification\\UserNotificationHandler updateTriggerCount wcf\\system\\user\\UserBirthdayCache loadMonth wcf\\system\\worker\\AbstractRebuildDataWorker execute wcf\\system\\CLIWCF afterArgumentParsing wcf\\system\\CLIWCF beforeArgumentParsing wcf\\system\\WCF initialized wcf\\util\\HeaderUtil parseOutput * WoltLab Suite Forum # Class Event Name wbb\\data\\board\\BoardAction cloneBoard wbb\\data\\post\\PostAction quickReplyShouldMerge wbb\\system\\thread\\ThreadHandler didInit","title":"Event List"},{"location":"php/api/event_list/#event-list","text":"Events whose name is marked with an asterisk are called from a static method and thus do not provide any object, just the class name.","title":"Event List"},{"location":"php/api/event_list/#woltlab-suite-core","text":"Class Event Name wcf\\acp\\action\\UserExportGdprAction export wcf\\acp\\form\\StyleAddForm setVariables wcf\\acp\\form\\UserSearchForm search wcf\\action\\AbstractAction checkModules wcf\\action\\AbstractAction checkPermissions wcf\\action\\AbstractAction execute wcf\\action\\AbstractAction executed wcf\\action\\AbstractAction readParameters wcf\\data\\attachment\\AttachmentAction generateThumbnail wcf\\data\\session\\SessionAction keepAlive wcf\\data\\session\\SessionAction poll wcf\\data\\trophy\\Trophy renderTrophy wcf\\data\\user\\online\\UserOnline getBrowser wcf\\data\\user\\online\\UserOnlineList isVisible wcf\\data\\user\\trophy\\UserTrophy getReplacements wcf\\data\\user\\UserAction beforeFindUsers wcf\\data\\user\\UserAction rename wcf\\data\\user\\UserProfile getAvatar wcf\\data\\user\\UserProfile isAccessible wcf\\data\\AbstractDatabaseObjectAction finalizeAction wcf\\data\\AbstractDatabaseObjectAction initializeAction wcf\\data\\AbstractDatabaseObjectAction validateAction wcf\\data\\DatabaseObjectList init wcf\\form\\AbstractForm readFormParameters wcf\\form\\AbstractForm save wcf\\form\\AbstractForm saved wcf\\form\\AbstractForm submit wcf\\form\\AbstractForm validate wcf\\form\\AbstractModerationForm prepareSave wcf\\page\\AbstractPage assignVariables wcf\\page\\AbstractPage checkModules wcf\\page\\AbstractPage checkPermissions wcf\\page\\AbstractPage readData wcf\\page\\AbstractPage readParameters wcf\\page\\AbstractPage show wcf\\page\\MultipleLinkPage beforeReadObjects wcf\\page\\MultipleLinkPage calculateNumberOfPages wcf\\page\\MultipleLinkPage countItems wcf\\page\\SortablePage validateSortField wcf\\page\\SortablePage validateSortOrder wcf\\system\\bbcode\\MessageParser afterParsing wcf\\system\\bbcode\\MessageParser beforeParsing wcf\\system\\bbcode\\SimpleMessageParser afterParsing wcf\\system\\bbcode\\SimpleMessageParser beforeParsing wcf\\system\\box\\AbstractBoxController __construct wcf\\system\\box\\AbstractBoxController afterLoadContent wcf\\system\\box\\AbstractBoxController beforeLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController afterLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController beforeLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController hasContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController readObjects wcf\\system\\cronjob\\AbstractCronjob execute wcf\\system\\email\\Email getJobs wcf\\system\\form\\builder\\container\\wysiwyg\\WysiwygFormContainer populate wcf\\system\\html\\input\\filter\\MessageHtmlInputFilter setAttributeDefinitions wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor afterProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor beforeEmbeddedProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor beforeProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor convertPlainLinks wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor getTextContent wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor parseEmbeddedContent wcf\\system\\html\\input\\node\\HtmlInputNodeWoltlabMetacodeMarker filterGroups wcf\\system\\html\\output\\node\\HtmlOutputNodePre selectHighlighter wcf\\system\\html\\output\\node\\HtmlOutputNodeProcessor beforeProcess wcf\\system\\image\\adapter\\ImagickImageAdapter getResizeFilter wcf\\system\\menu\\user\\profile\\UserProfileMenu init wcf\\system\\menu\\user\\profile\\UserProfileMenu loadCache wcf\\system\\menu\\TreeMenu init wcf\\system\\menu\\TreeMenu loadCache wcf\\system\\message\\QuickReplyManager addFullQuote wcf\\system\\message\\QuickReplyManager allowedDataParameters wcf\\system\\message\\QuickReplyManager beforeRenderQuote wcf\\system\\message\\QuickReplyManager createMessage wcf\\system\\message\\QuickReplyManager createdMessage wcf\\system\\message\\QuickReplyManager getMessage wcf\\system\\message\\QuickReplyManager validateParameters wcf\\system\\option\\OptionHandler afterReadCache wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin construct wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin hasUninstall wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin install wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin uninstall wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin update wcf\\system\\package\\plugin\\ObjectTypePackageInstallationPlugin addConditionFields wcf\\system\\package\\PackageInstallationDispatcher postInstall wcf\\system\\package\\PackageUninstallationDispatcher postUninstall wcf\\system\\reaction\\ReactionHandler getDataAttributes wcf\\system\\request\\RouteHandler didInit wcf\\system\\session\\ACPSessionFactory afterInit wcf\\system\\session\\ACPSessionFactory beforeInit wcf\\system\\session\\SessionHandler afterChangeUser wcf\\system\\session\\SessionHandler beforeChangeUser wcf\\system\\style\\StyleCompiler compile wcf\\system\\template\\TemplateEngine afterDisplay wcf\\system\\template\\TemplateEngine beforeDisplay wcf\\system\\upload\\DefaultUploadFileSaveStrategy generateThumbnails wcf\\system\\upload\\DefaultUploadFileSaveStrategy save wcf\\system\\user\\authentication\\UserAuthenticationFactory init wcf\\system\\user\\notification\\UserNotificationHandler createdNotification wcf\\system\\user\\notification\\UserNotificationHandler fireEvent wcf\\system\\user\\notification\\UserNotificationHandler markAsConfirmed wcf\\system\\user\\notification\\UserNotificationHandler markAsConfirmedByIDs wcf\\system\\user\\notification\\UserNotificationHandler removeNotifications wcf\\system\\user\\notification\\UserNotificationHandler updateTriggerCount wcf\\system\\user\\UserBirthdayCache loadMonth wcf\\system\\worker\\AbstractRebuildDataWorker execute wcf\\system\\CLIWCF afterArgumentParsing wcf\\system\\CLIWCF beforeArgumentParsing wcf\\system\\WCF initialized wcf\\util\\HeaderUtil parseOutput *","title":"WoltLab Suite Core"},{"location":"php/api/event_list/#woltlab-suite-forum","text":"Class Event Name wbb\\data\\board\\BoardAction cloneBoard wbb\\data\\post\\PostAction quickReplyShouldMerge wbb\\system\\thread\\ThreadHandler didInit","title":"WoltLab Suite Forum"},{"location":"php/api/events/","text":"Events # WoltLab Suite's event system allows manipulation of program flows and data without having to change any of the original source code. At many locations throughout the PHP code of WoltLab Suite Core and mainly through inheritance also in the applications and plugins, so called events are fired which trigger registered event listeners that get access to the object firing the event (or at least the class name if the event has been fired in a static method). This page focuses on the technical aspects of events and event listeners, the eventListener package installation plugin page covers how you can actually register an event listener. A comprehensive list of all available events is provided here . Introductory Example # Let's start with a simple example to illustrate how the event system works. Consider this pre-existing class: files/lib/system/example/ExampleComponent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleComponent { public $var = 1 ; public function getVar () { EventHandler :: getInstance () -> fireAction ( $this , 'getVar' ); return $this -> var ; } } where an event with event name getVar is fired in the getVar() method. If you create an object of this class and call the getVar() method, the return value will be 1 , of course: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php $example = new wcf\\system\\example\\ExampleComponent (); if ( $example -> getVar () == 1 ) { echo \"var is 1!\" ; } else if ( $example -> getVar () == 2 ) { echo \"var is 2!\" ; } else { echo \"No, var is neither 1 nor 2.\" ; } // output: var is 1! Now, consider that we have registered the following event listener to this event: files/lib/system/event/listener/ExampleEventListener.class.php 1 2 3 4 5 6 7 8 <? php namespace wcf\\system\\event\\listener ; class ExampleEventListener implements IParameterizedEventListener { public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $eventObj -> var = 2 ; } } Whenever the event in the getVar() method is called, this method (of the same event listener object) is called. In this case, the value of the method's first parameter is the ExampleComponent object passed as the first argument of the EventHandler::fireAction() call in ExampleComponent::getVar() . As ExampleComponent::$var is a public property, the event listener code can change it and set it to 2 . If you now execute the example code from above again, the output will change from var is 1! to var is 2! because prior to returning the value, the event listener code changes the value from 1 to 2 . This introductory example illustrates how event listeners can change data in a non-intrusive way. Program flow can be changed, for example, by throwing a wcf\\system\\exception\\PermissionDeniedException if some additional constraint to access a page is not fulfilled. Listening to Events # In order to listen to events, you need to register the event listener and the event listener itself needs to implement the interface wcf\\system\\event\\listener\\IParameterizedEventListener which only contains the execute method (see example above). The first parameter $eventObj of the method contains the passed object where the event is fired or the name of the class in which the event is fired if it is fired from a static method. The second parameter $className always contains the name of the class where the event has been fired. The third parameter $eventName provides the name of the event within a class to uniquely identify the exact location in the class where the event has been fired. The last parameter $parameters is a reference to the array which contains additional data passed by the method firing the event. If no additional data is passed, $parameters is empty. Firing Events # If you write code and want plugins to have access at certain points, you can fire an event on your own. The only thing to do is to call the wcf\\system\\event\\EventHandler::fireAction($eventObj, $eventName, array &$parameters = []) method and pass the following parameters: $eventObj should be $this if you fire from an object context, otherwise pass the class name static::class . $eventName identifies the event within the class and generally has the same name as the method. In cases, were you might fire more than one event in a method, for example before and after a certain piece of code, you can use the prefixes before* and after* in your event names. $parameters is an optional array which allows you to pass additional data to the event listeners without having to make this data accessible via a property explicitly only created for this purpose. This additional data can either be just additional information for the event listeners about the context of the method call or allow the event listener to manipulate local data if the code, where the event has been fired, uses the passed data afterwards. Example: Using $parameters argument # Consider the following method which gets some text that the methods parses. files/lib/system/example/ExampleParser.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleParser { public function parse ( $text ) { // [some parsing done by default] $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'parse' , $parameters ); return $parameters [ 'text' ]; } } After the default parsing by the method itself, the author wants to enable plugins to do additional parsing and thus fires an event and passes the parsed text as an additional parameter. Then, a plugin can deliver the following event listener files/lib/system/event/listener/ExampleParserEventListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 <? php namespace wcf\\system\\event\\listener ; class ExampleParserEventListener implements IParameterizedEventListener { public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $text = $parameters [ 'text' ]; // [some additional parsing which changes $text] $parameters [ 'text' ] = $text ; } } which can access the text via $parameters['text'] . This example can also be perfectly used to illustrate how to name multiple events in the same method. Let's assume that the author wants to enable plugins to change the text before and after the method does its own parsing and thus fires two events: files/lib/system/example/ExampleParser.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleParser { public function parse ( $text ) { $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'beforeParsing' , $parameters ); $text = $parameters [ 'text' ]; // [some parsing done by default] $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'afterParsing' , $parameters ); return $parameters [ 'text' ]; } } Advanced Example: Additional Form Field # One common reason to use event listeners is to add an additional field to a pre-existing form (in combination with template listeners, which we will not cover here). We will assume that users are able to do both, create and edit the objects via this form. The points in the program flow of AbstractForm that are relevant here are: adding object (after the form has been submitted): reading the value of the field validating the read value saving the additional value after successful validation and resetting locally stored value or assigning the current value of the field to the template after unsuccessful validation editing object: on initial form request: reading the pre-existing value of the edited object assigning the field value to the template after the form has been submitted: reading the value of the field validating the read value saving the additional value after successful validation assigning the current value of the field to the template All of these cases can be covered the by following code in which we assume that wcf\\form\\ExampleAddForm is the form to create example objects and that wcf\\form\\ExampleEditForm extends wcf\\form\\ExampleAddForm and is used for editing existing example objects. files/lib/system/event/listener/ExampleAddFormListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <? php namespace wcf\\system\\event\\listener ; use wcf\\form\\ExampleAddForm ; use wcf\\form\\ExampleEditForm ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\WCF ; class ExampleAddFormListener implements IParameterizedEventListener { protected $var = 0 ; public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $this -> $eventName ( $eventObj ); } protected function assignVariables () { WCF :: getTPL () -> assign ( 'var' , $this -> var ); } protected function readData ( ExampleEditForm $eventObj ) { if ( empty ( $_POST )) { $this -> var = $eventObj -> example -> var ; } } protected function readFormParameters () { if ( isset ( $_POST [ 'var' ])) $this -> var = intval ( $_POST [ 'var' ]); } protected function save ( ExampleAddForm $eventObj ) { $eventObj -> additionalFields = array_merge ( $eventObj -> additionalFields , [ 'var' => $this -> var ]); } protected function saved () { $this -> var = 0 ; } protected function validate () { if ( $this -> var < 0 ) { throw new UserInputException ( 'var' , 'isNegative' ); } } } The execute method in this example just delegates the call to a method with the same name as the event so that this class mimics the structure of a form class itself. The form object is passed to the methods but is only given in the method signatures as a parameter here whenever the form object is actually used. Furthermore, the type-hinting of the parameter illustrates in which contexts the method is actually called which will become clear in the following discussion of the individual methods: assignVariables() is called for the add and the edit form and simply assigns the current value of the variable to the template. readData() reads the pre-existing value of $var if the form has not been submitted and thus is only relevant when editing objects which is illustrated by the explicit type-hint of ExampleEditForm . readFormParameters() reads the value for both, the add and the edit form. save() is, of course, also relevant in both cases but requires the form object to store the additional value in the wcf\\form\\AbstractForm::$additionalFields array which can be used if a var column has been added to the database table in which the example objects are stored. saved() is only called for the add form as it clears the internal value so that in the assignVariables() call, the default value will be assigned to the template to create an \"empty\" form. During edits, this current value is the actual value that should be shown. validate() also needs to be called in both cases as the input data always has to be validated. Lastly, the following XML file has to be used to register the event listeners (you can find more information about how to register event listeners on the eventListener package installation plugin page ): eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/eventListener.xsd\" > <import> <eventlistener name= \"exampleAddInherited\" > <eventclassname> wcf\\form\\ExampleAddForm </eventclassname> <eventname> assignVariables,readFormParameters,save,validate </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> <eventlistener name= \"exampleAdd\" > <eventclassname> wcf\\form\\ExampleAddForm </eventclassname> <eventname> saved </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> </eventlistener> <eventlistener name= \"exampleEdit\" > <eventclassname> wcf\\form\\ExampleEditForm </eventclassname> <eventname> readData </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> </eventlistener> </import> </data>","title":"Events"},{"location":"php/api/events/#events","text":"WoltLab Suite's event system allows manipulation of program flows and data without having to change any of the original source code. At many locations throughout the PHP code of WoltLab Suite Core and mainly through inheritance also in the applications and plugins, so called events are fired which trigger registered event listeners that get access to the object firing the event (or at least the class name if the event has been fired in a static method). This page focuses on the technical aspects of events and event listeners, the eventListener package installation plugin page covers how you can actually register an event listener. A comprehensive list of all available events is provided here .","title":"Events"},{"location":"php/api/events/#introductory-example","text":"Let's start with a simple example to illustrate how the event system works. Consider this pre-existing class: files/lib/system/example/ExampleComponent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleComponent { public $var = 1 ; public function getVar () { EventHandler :: getInstance () -> fireAction ( $this , 'getVar' ); return $this -> var ; } } where an event with event name getVar is fired in the getVar() method. If you create an object of this class and call the getVar() method, the return value will be 1 , of course: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php $example = new wcf\\system\\example\\ExampleComponent (); if ( $example -> getVar () == 1 ) { echo \"var is 1!\" ; } else if ( $example -> getVar () == 2 ) { echo \"var is 2!\" ; } else { echo \"No, var is neither 1 nor 2.\" ; } // output: var is 1! Now, consider that we have registered the following event listener to this event: files/lib/system/event/listener/ExampleEventListener.class.php 1 2 3 4 5 6 7 8 <? php namespace wcf\\system\\event\\listener ; class ExampleEventListener implements IParameterizedEventListener { public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $eventObj -> var = 2 ; } } Whenever the event in the getVar() method is called, this method (of the same event listener object) is called. In this case, the value of the method's first parameter is the ExampleComponent object passed as the first argument of the EventHandler::fireAction() call in ExampleComponent::getVar() . As ExampleComponent::$var is a public property, the event listener code can change it and set it to 2 . If you now execute the example code from above again, the output will change from var is 1! to var is 2! because prior to returning the value, the event listener code changes the value from 1 to 2 . This introductory example illustrates how event listeners can change data in a non-intrusive way. Program flow can be changed, for example, by throwing a wcf\\system\\exception\\PermissionDeniedException if some additional constraint to access a page is not fulfilled.","title":"Introductory Example"},{"location":"php/api/events/#listening-to-events","text":"In order to listen to events, you need to register the event listener and the event listener itself needs to implement the interface wcf\\system\\event\\listener\\IParameterizedEventListener which only contains the execute method (see example above). The first parameter $eventObj of the method contains the passed object where the event is fired or the name of the class in which the event is fired if it is fired from a static method. The second parameter $className always contains the name of the class where the event has been fired. The third parameter $eventName provides the name of the event within a class to uniquely identify the exact location in the class where the event has been fired. The last parameter $parameters is a reference to the array which contains additional data passed by the method firing the event. If no additional data is passed, $parameters is empty.","title":"Listening to Events"},{"location":"php/api/events/#firing-events","text":"If you write code and want plugins to have access at certain points, you can fire an event on your own. The only thing to do is to call the wcf\\system\\event\\EventHandler::fireAction($eventObj, $eventName, array &$parameters = []) method and pass the following parameters: $eventObj should be $this if you fire from an object context, otherwise pass the class name static::class . $eventName identifies the event within the class and generally has the same name as the method. In cases, were you might fire more than one event in a method, for example before and after a certain piece of code, you can use the prefixes before* and after* in your event names. $parameters is an optional array which allows you to pass additional data to the event listeners without having to make this data accessible via a property explicitly only created for this purpose. This additional data can either be just additional information for the event listeners about the context of the method call or allow the event listener to manipulate local data if the code, where the event has been fired, uses the passed data afterwards.","title":"Firing Events"},{"location":"php/api/events/#example-using-parameters-argument","text":"Consider the following method which gets some text that the methods parses. files/lib/system/example/ExampleParser.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleParser { public function parse ( $text ) { // [some parsing done by default] $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'parse' , $parameters ); return $parameters [ 'text' ]; } } After the default parsing by the method itself, the author wants to enable plugins to do additional parsing and thus fires an event and passes the parsed text as an additional parameter. Then, a plugin can deliver the following event listener files/lib/system/event/listener/ExampleParserEventListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 <? php namespace wcf\\system\\event\\listener ; class ExampleParserEventListener implements IParameterizedEventListener { public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $text = $parameters [ 'text' ]; // [some additional parsing which changes $text] $parameters [ 'text' ] = $text ; } } which can access the text via $parameters['text'] . This example can also be perfectly used to illustrate how to name multiple events in the same method. Let's assume that the author wants to enable plugins to change the text before and after the method does its own parsing and thus fires two events: files/lib/system/example/ExampleParser.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleParser { public function parse ( $text ) { $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'beforeParsing' , $parameters ); $text = $parameters [ 'text' ]; // [some parsing done by default] $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'afterParsing' , $parameters ); return $parameters [ 'text' ]; } }","title":"Example: Using $parameters argument"},{"location":"php/api/events/#advanced-example-additional-form-field","text":"One common reason to use event listeners is to add an additional field to a pre-existing form (in combination with template listeners, which we will not cover here). We will assume that users are able to do both, create and edit the objects via this form. The points in the program flow of AbstractForm that are relevant here are: adding object (after the form has been submitted): reading the value of the field validating the read value saving the additional value after successful validation and resetting locally stored value or assigning the current value of the field to the template after unsuccessful validation editing object: on initial form request: reading the pre-existing value of the edited object assigning the field value to the template after the form has been submitted: reading the value of the field validating the read value saving the additional value after successful validation assigning the current value of the field to the template All of these cases can be covered the by following code in which we assume that wcf\\form\\ExampleAddForm is the form to create example objects and that wcf\\form\\ExampleEditForm extends wcf\\form\\ExampleAddForm and is used for editing existing example objects. files/lib/system/event/listener/ExampleAddFormListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <? php namespace wcf\\system\\event\\listener ; use wcf\\form\\ExampleAddForm ; use wcf\\form\\ExampleEditForm ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\WCF ; class ExampleAddFormListener implements IParameterizedEventListener { protected $var = 0 ; public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $this -> $eventName ( $eventObj ); } protected function assignVariables () { WCF :: getTPL () -> assign ( 'var' , $this -> var ); } protected function readData ( ExampleEditForm $eventObj ) { if ( empty ( $_POST )) { $this -> var = $eventObj -> example -> var ; } } protected function readFormParameters () { if ( isset ( $_POST [ 'var' ])) $this -> var = intval ( $_POST [ 'var' ]); } protected function save ( ExampleAddForm $eventObj ) { $eventObj -> additionalFields = array_merge ( $eventObj -> additionalFields , [ 'var' => $this -> var ]); } protected function saved () { $this -> var = 0 ; } protected function validate () { if ( $this -> var < 0 ) { throw new UserInputException ( 'var' , 'isNegative' ); } } } The execute method in this example just delegates the call to a method with the same name as the event so that this class mimics the structure of a form class itself. The form object is passed to the methods but is only given in the method signatures as a parameter here whenever the form object is actually used. Furthermore, the type-hinting of the parameter illustrates in which contexts the method is actually called which will become clear in the following discussion of the individual methods: assignVariables() is called for the add and the edit form and simply assigns the current value of the variable to the template. readData() reads the pre-existing value of $var if the form has not been submitted and thus is only relevant when editing objects which is illustrated by the explicit type-hint of ExampleEditForm . readFormParameters() reads the value for both, the add and the edit form. save() is, of course, also relevant in both cases but requires the form object to store the additional value in the wcf\\form\\AbstractForm::$additionalFields array which can be used if a var column has been added to the database table in which the example objects are stored. saved() is only called for the add form as it clears the internal value so that in the assignVariables() call, the default value will be assigned to the template to create an \"empty\" form. During edits, this current value is the actual value that should be shown. validate() also needs to be called in both cases as the input data always has to be validated. Lastly, the following XML file has to be used to register the event listeners (you can find more information about how to register event listeners on the eventListener package installation plugin page ): eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/eventListener.xsd\" > <import> <eventlistener name= \"exampleAddInherited\" > <eventclassname> wcf\\form\\ExampleAddForm </eventclassname> <eventname> assignVariables,readFormParameters,save,validate </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> <eventlistener name= \"exampleAdd\" > <eventclassname> wcf\\form\\ExampleAddForm </eventclassname> <eventname> saved </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> </eventlistener> <eventlistener name= \"exampleEdit\" > <eventclassname> wcf\\form\\ExampleEditForm </eventclassname> <eventname> readData </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> </eventlistener> </import> </data>","title":"Advanced Example: Additional Form Field"},{"location":"php/api/package_installation_plugins/","text":"Package Installation Plugins # A package installation plugin (PIP) defines the behavior to handle a specific instruction during package installation, update or uninstallation. AbstractPackageInstallationPlugin # Any package installation plugin has to implement the IPackageInstallationPlugin interface. It is recommended however, to extend the abstract implementation AbstractPackageInstallationPlugin of this interface instead of directly implementing the interface. The abstract implementation will always provide sane methods in case of any API changes. Class Members # Package Installation Plugins have a few notable class members easing your work: $installation # This member contains an instance of PackageInstallationDispatcher which provides you with all meta data related to the current package being processed. The most common usage is the retrieval of the package ID via $this->installation->getPackageID() . $application # Represents the abbreviation of the target application, e.g. wbb (default value: wcf ), used for the name of database table in which the installed data is stored. AbstractXMLPackageInstallationPlugin # AbstractPackageInstallationPlugin is the default implementation for all package installation plugins based upon a single XML document. It handles the evaluation of the document and provide you an object-orientated approach to handle its data. Class Members # $className # Value must be the qualified name of a class deriving from DatabaseObjectEditor which is used to create and update objects. $tagName # Specifies the tag name within a <import> or <delete> section of the XML document used for each installed object. prepareImport(array $data) # The passed array $data contains the parsed value from each evaluated tag in the <import> section: $data['elements'] contains a list of tag names and their value. $data['attributes'] contains a list of attributes present on the tag identified by $tagName . This method should return an one-dimensional array, where each key maps to the corresponding database column name (key names are case-sensitive). It will be passed to either DatabaseObjectEditor::create() or DatabaseObjectEditor::update() . Example: 1 2 3 4 5 6 <? php return [ 'environment' => $data [ 'elements' ][ 'environment' ], 'eventName' => $data [ 'elements' ][ 'eventname' ], 'name' => $data [ 'attributes' ][ 'name' ] ]; validateImport(array $data) # The passed array $data equals the data returned by prepareImport() . This method has no return value, instead you should throw an exception if the passed data is invalid. findExistingItem(array $data) # The passed array $data equals the data returned by prepareImport() . This method is expected to return an array with two keys: sql contains the SQL query with placeholders. parameters contains an array with values used for the SQL query. Example # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_\" . $this -> tableName . \" WHERE packageID = ? AND name = ? AND templateName = ? AND eventName = ? AND environment = ?\" ; $parameters = [ $this -> installation -> getPackageID (), $data [ 'name' ], $data [ 'templateName' ], $data [ 'eventName' ], $data [ 'environment' ] ]; return [ 'sql' => $sql , 'parameters' => $parameters ]; handleDelete(array $items) # The passed array $items contains the original node data, similar to prepareImport() . You should make use of this data to remove the matching element from database. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php $sql = \"DELETE FROM wcf\" . WCF_N . \"_\" . $this -> tableName . \" WHERE packageID = ? AND environment = ? AND eventName = ? AND name = ? AND templateName = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); foreach ( $items as $item ) { $statement -> execute ([ $this -> installation -> getPackageID (), $item [ 'elements' ][ 'environment' ], $item [ 'elements' ][ 'eventname' ], $item [ 'attributes' ][ 'name' ], $item [ 'elements' ][ 'templatename' ] ]); } postImport() # Allows you to (optionally) run additionally actions after all elements were processed. AbstractOptionPackageInstallationPlugin # AbstractOptionPackageInstallationPlugin is an abstract implementation for options, used for: ACL Options Options User Options User Group Options Differences to AbstractXMLPackageInstallationPlugin # $reservedTags # $reservedTags is a list of reserved tag names so that any tag encountered but not listed here will be added to the database column additionalData . This allows options to store arbitrary data which can be accessed but were not initially part of the PIP specifications.","title":"Package Installation Plugins"},{"location":"php/api/package_installation_plugins/#package-installation-plugins","text":"A package installation plugin (PIP) defines the behavior to handle a specific instruction during package installation, update or uninstallation.","title":"Package Installation Plugins"},{"location":"php/api/package_installation_plugins/#abstractpackageinstallationplugin","text":"Any package installation plugin has to implement the IPackageInstallationPlugin interface. It is recommended however, to extend the abstract implementation AbstractPackageInstallationPlugin of this interface instead of directly implementing the interface. The abstract implementation will always provide sane methods in case of any API changes.","title":"AbstractPackageInstallationPlugin"},{"location":"php/api/package_installation_plugins/#class-members","text":"Package Installation Plugins have a few notable class members easing your work:","title":"Class Members"},{"location":"php/api/package_installation_plugins/#installation","text":"This member contains an instance of PackageInstallationDispatcher which provides you with all meta data related to the current package being processed. The most common usage is the retrieval of the package ID via $this->installation->getPackageID() .","title":"$installation"},{"location":"php/api/package_installation_plugins/#application","text":"Represents the abbreviation of the target application, e.g. wbb (default value: wcf ), used for the name of database table in which the installed data is stored.","title":"$application"},{"location":"php/api/package_installation_plugins/#abstractxmlpackageinstallationplugin","text":"AbstractPackageInstallationPlugin is the default implementation for all package installation plugins based upon a single XML document. It handles the evaluation of the document and provide you an object-orientated approach to handle its data.","title":"AbstractXMLPackageInstallationPlugin"},{"location":"php/api/package_installation_plugins/#class-members_1","text":"","title":"Class Members"},{"location":"php/api/package_installation_plugins/#classname","text":"Value must be the qualified name of a class deriving from DatabaseObjectEditor which is used to create and update objects.","title":"$className"},{"location":"php/api/package_installation_plugins/#tagname","text":"Specifies the tag name within a <import> or <delete> section of the XML document used for each installed object.","title":"$tagName"},{"location":"php/api/package_installation_plugins/#prepareimportarray-data","text":"The passed array $data contains the parsed value from each evaluated tag in the <import> section: $data['elements'] contains a list of tag names and their value. $data['attributes'] contains a list of attributes present on the tag identified by $tagName . This method should return an one-dimensional array, where each key maps to the corresponding database column name (key names are case-sensitive). It will be passed to either DatabaseObjectEditor::create() or DatabaseObjectEditor::update() . Example: 1 2 3 4 5 6 <? php return [ 'environment' => $data [ 'elements' ][ 'environment' ], 'eventName' => $data [ 'elements' ][ 'eventname' ], 'name' => $data [ 'attributes' ][ 'name' ] ];","title":"prepareImport(array $data)"},{"location":"php/api/package_installation_plugins/#validateimportarray-data","text":"The passed array $data equals the data returned by prepareImport() . This method has no return value, instead you should throw an exception if the passed data is invalid.","title":"validateImport(array $data)"},{"location":"php/api/package_installation_plugins/#findexistingitemarray-data","text":"The passed array $data equals the data returned by prepareImport() . This method is expected to return an array with two keys: sql contains the SQL query with placeholders. parameters contains an array with values used for the SQL query.","title":"findExistingItem(array $data)"},{"location":"php/api/package_installation_plugins/#example","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_\" . $this -> tableName . \" WHERE packageID = ? AND name = ? AND templateName = ? AND eventName = ? AND environment = ?\" ; $parameters = [ $this -> installation -> getPackageID (), $data [ 'name' ], $data [ 'templateName' ], $data [ 'eventName' ], $data [ 'environment' ] ]; return [ 'sql' => $sql , 'parameters' => $parameters ];","title":"Example"},{"location":"php/api/package_installation_plugins/#handledeletearray-items","text":"The passed array $items contains the original node data, similar to prepareImport() . You should make use of this data to remove the matching element from database. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php $sql = \"DELETE FROM wcf\" . WCF_N . \"_\" . $this -> tableName . \" WHERE packageID = ? AND environment = ? AND eventName = ? AND name = ? AND templateName = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); foreach ( $items as $item ) { $statement -> execute ([ $this -> installation -> getPackageID (), $item [ 'elements' ][ 'environment' ], $item [ 'elements' ][ 'eventname' ], $item [ 'attributes' ][ 'name' ], $item [ 'elements' ][ 'templatename' ] ]); }","title":"handleDelete(array $items)"},{"location":"php/api/package_installation_plugins/#postimport","text":"Allows you to (optionally) run additionally actions after all elements were processed.","title":"postImport()"},{"location":"php/api/package_installation_plugins/#abstractoptionpackageinstallationplugin","text":"AbstractOptionPackageInstallationPlugin is an abstract implementation for options, used for: ACL Options Options User Options User Group Options","title":"AbstractOptionPackageInstallationPlugin"},{"location":"php/api/package_installation_plugins/#differences-to-abstractxmlpackageinstallationplugin","text":"","title":"Differences to AbstractXMLPackageInstallationPlugin"},{"location":"php/api/package_installation_plugins/#reservedtags","text":"$reservedTags is a list of reserved tag names so that any tag encountered but not listed here will be added to the database column additionalData . This allows options to store arbitrary data which can be accessed but were not initially part of the PIP specifications.","title":"$reservedTags"},{"location":"php/api/sitemaps/","text":"Sitemaps # WoltLab Suite is capable of automatically creating a sitemap. This sitemap contains all static pages registered via the page package installation plugin and which may be indexed by search engines (checking the allowSpidersToIndex parameter and page permissions) and do not expect an object ID. Other pages have to be added to the sitemap as a separate object. The only prerequisite for sitemap objects is that the objects are instances of wcf\\data\\DatabaseObject and that there is a wcf\\data\\DatabaseObjectList implementation. First, we implement the PHP class, which provides us all database objects and optionally checks the permissions for a single object. The class must implement the interface wcf\\system\\sitemap\\object\\ISitemapObjectObjectType . However, in order to have some methods already implemented and ensure backwards compatibility, you should use the abstract class wcf\\system\\sitemap\\object\\AbstractSitemapObjectObjectType . The abstract class takes care of generating the DatabaseObjectList class name and list directly and implements optional methods with the default values. The only method that you have to implement yourself is the getObjectClass() method which returns the fully qualified name of the DatabaseObject class. The DatabaseObject class must implement the interface wcf\\data\\ILinkableObject . Other optional methods are: The getLastModifiedColumn() method returns the name of the column in the database where the last modification date is stored. If there is none, this method must return null . The canView() method checks whether the passed DatabaseObject is visible to the current user with the current user always being a guest. The getObjectListClass() method returns a non-standard DatabaseObjectList class name. The getObjectList() method returns the DatabaseObjectList instance. You can, for example, specify additional query conditions in the method. As an example, the implementation for users looks like this: files/lib/system/sitemap/object/UserSitemapObject.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\system\\sitemap\\object ; use wcf\\data\\user\\User ; use wcf\\data\\DatabaseObject ; use wcf\\system\\WCF ; /** * User sitemap implementation. * * @author Joshua Ruesweg * @copyright 2001-2017 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Sitemap\\Object * @since 3.1 */ class UserSitemapObject extends AbstractSitemapObjectObjectType { /** * @inheritDoc */ public function getObjectClass () { return User :: class ; } /** * @inheritDoc */ public function getLastModifiedColumn () { return 'lastActivityTime' ; } /** * @inheritDoc */ public function canView ( DatabaseObject $object ) { return WCF :: getSession () -> getPermission ( 'user.profile.canViewUserProfile' ); } } Next, the sitemap object must be registered as an object type: 1 2 3 4 5 6 7 8 <type> <name> com.example.plugin.sitemap.object.user </name> <definitionname> com.woltlab.wcf.sitemap.object </definitionname> <classname> wcf\\system\\sitemap\\object\\UserSitemapObject </classname> <priority> 0.5 </priority> <changeFreq> monthly </changeFreq> <rebuildTime> 259200 </rebuildTime> </type> In addition to the fully qualified class name, the object type definition com.woltlab.wcf.sitemap.object and the object type name, the parameters priority , changeFreq and rebuildTime must also be specified. priority ( https://www.sitemaps.org/protocol.html#prioritydef ) and changeFreq ( https://www.sitemaps.org/protocol.html#changefreqdef ) are specifications in the sitemaps protocol and can be changed by the user in the ACP. The priority should be 0.5 by default, unless there is an important reason to change it. The parameter rebuildTime specifies the number of seconds after which the sitemap should be regenerated. Finally, you have to create the language variable for the sitemap object. The language variable follows the pattern wcf.acp.sitemap.objectType.{objectTypeName} and is in the category wcf.acp.sitemap .","title":"Sitemaps"},{"location":"php/api/sitemaps/#sitemaps","text":"WoltLab Suite is capable of automatically creating a sitemap. This sitemap contains all static pages registered via the page package installation plugin and which may be indexed by search engines (checking the allowSpidersToIndex parameter and page permissions) and do not expect an object ID. Other pages have to be added to the sitemap as a separate object. The only prerequisite for sitemap objects is that the objects are instances of wcf\\data\\DatabaseObject and that there is a wcf\\data\\DatabaseObjectList implementation. First, we implement the PHP class, which provides us all database objects and optionally checks the permissions for a single object. The class must implement the interface wcf\\system\\sitemap\\object\\ISitemapObjectObjectType . However, in order to have some methods already implemented and ensure backwards compatibility, you should use the abstract class wcf\\system\\sitemap\\object\\AbstractSitemapObjectObjectType . The abstract class takes care of generating the DatabaseObjectList class name and list directly and implements optional methods with the default values. The only method that you have to implement yourself is the getObjectClass() method which returns the fully qualified name of the DatabaseObject class. The DatabaseObject class must implement the interface wcf\\data\\ILinkableObject . Other optional methods are: The getLastModifiedColumn() method returns the name of the column in the database where the last modification date is stored. If there is none, this method must return null . The canView() method checks whether the passed DatabaseObject is visible to the current user with the current user always being a guest. The getObjectListClass() method returns a non-standard DatabaseObjectList class name. The getObjectList() method returns the DatabaseObjectList instance. You can, for example, specify additional query conditions in the method. As an example, the implementation for users looks like this: files/lib/system/sitemap/object/UserSitemapObject.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\system\\sitemap\\object ; use wcf\\data\\user\\User ; use wcf\\data\\DatabaseObject ; use wcf\\system\\WCF ; /** * User sitemap implementation. * * @author Joshua Ruesweg * @copyright 2001-2017 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Sitemap\\Object * @since 3.1 */ class UserSitemapObject extends AbstractSitemapObjectObjectType { /** * @inheritDoc */ public function getObjectClass () { return User :: class ; } /** * @inheritDoc */ public function getLastModifiedColumn () { return 'lastActivityTime' ; } /** * @inheritDoc */ public function canView ( DatabaseObject $object ) { return WCF :: getSession () -> getPermission ( 'user.profile.canViewUserProfile' ); } } Next, the sitemap object must be registered as an object type: 1 2 3 4 5 6 7 8 <type> <name> com.example.plugin.sitemap.object.user </name> <definitionname> com.woltlab.wcf.sitemap.object </definitionname> <classname> wcf\\system\\sitemap\\object\\UserSitemapObject </classname> <priority> 0.5 </priority> <changeFreq> monthly </changeFreq> <rebuildTime> 259200 </rebuildTime> </type> In addition to the fully qualified class name, the object type definition com.woltlab.wcf.sitemap.object and the object type name, the parameters priority , changeFreq and rebuildTime must also be specified. priority ( https://www.sitemaps.org/protocol.html#prioritydef ) and changeFreq ( https://www.sitemaps.org/protocol.html#changefreqdef ) are specifications in the sitemaps protocol and can be changed by the user in the ACP. The priority should be 0.5 by default, unless there is an important reason to change it. The parameter rebuildTime specifies the number of seconds after which the sitemap should be regenerated. Finally, you have to create the language variable for the sitemap object. The language variable follows the pattern wcf.acp.sitemap.objectType.{objectTypeName} and is in the category wcf.acp.sitemap .","title":"Sitemaps"},{"location":"php/api/user_activity_points/","text":"User Activity Points # Users get activity points whenever they create content to award them for their contribution. Activity points are used to determine the rank of a user and can also be used for user conditions, for example for automatic user group assignments. To integrate activity points into your package, you have to register an object type for the defintion com.woltlab.wcf.user.activityPointEvent and specify a default number of points: 1 2 3 4 5 <type> <name> com.example.foo.activityPointEvent.bar </name> <definitionname> com.woltlab.wcf.user.activityPointEvent </definitionname> <points> 10 </points> </type> The number of points awarded for this type of activity point event can be changed by the administrator in the admin control panel. For this form and the user activity point list shown in the frontend, you have to provide the language item 1 wcf.user.activityPoint.objectType.com.example.foo.activityPointEvent.bar that contains the name of the content for which the activity points are awarded. If a relevant object is created, you have to use UserActivityPointHandler::fireEvent() which expects the name of the activity point event object type, the id of the object for which the points are awarded (though the object id is not used at the moment) and the user who gets the points: 1 2 3 4 5 UserActivityPointHandler :: getInstance () -> fireEvent ( 'com.example.foo.activityPointEvent.bar' , $bar -> barID , $bar -> userID ); To remove activity points once objects are deleted, you have to use UserActivityPointHandler::removeEvents() which also expects the name of the activity point event object type and additionally an array mapping the id of the user whose activity points will be reduced to the number of objects that are removed for the relevant user: 1 2 3 4 5 6 7 UserActivityPointHandler :: getInstance () -> removeEvents ( 'com.example.foo.activityPointEvent.bar' , [ 1 => 1 , // remove points for one object for user with id `1` 4 => 2 // remove points for two objects for user with id `4` ] );","title":"User Activity Points"},{"location":"php/api/user_activity_points/#user-activity-points","text":"Users get activity points whenever they create content to award them for their contribution. Activity points are used to determine the rank of a user and can also be used for user conditions, for example for automatic user group assignments. To integrate activity points into your package, you have to register an object type for the defintion com.woltlab.wcf.user.activityPointEvent and specify a default number of points: 1 2 3 4 5 <type> <name> com.example.foo.activityPointEvent.bar </name> <definitionname> com.woltlab.wcf.user.activityPointEvent </definitionname> <points> 10 </points> </type> The number of points awarded for this type of activity point event can be changed by the administrator in the admin control panel. For this form and the user activity point list shown in the frontend, you have to provide the language item 1 wcf.user.activityPoint.objectType.com.example.foo.activityPointEvent.bar that contains the name of the content for which the activity points are awarded. If a relevant object is created, you have to use UserActivityPointHandler::fireEvent() which expects the name of the activity point event object type, the id of the object for which the points are awarded (though the object id is not used at the moment) and the user who gets the points: 1 2 3 4 5 UserActivityPointHandler :: getInstance () -> fireEvent ( 'com.example.foo.activityPointEvent.bar' , $bar -> barID , $bar -> userID ); To remove activity points once objects are deleted, you have to use UserActivityPointHandler::removeEvents() which also expects the name of the activity point event object type and additionally an array mapping the id of the user whose activity points will be reduced to the number of objects that are removed for the relevant user: 1 2 3 4 5 6 7 UserActivityPointHandler :: getInstance () -> removeEvents ( 'com.example.foo.activityPointEvent.bar' , [ 1 => 1 , // remove points for one object for user with id `1` 4 => 2 // remove points for two objects for user with id `4` ] );","title":"User Activity Points"},{"location":"php/api/user_notifications/","text":"User Notifications # WoltLab Suite includes a powerful user notification system that supports notifications directly shown on the website and emails sent immediately or on a daily basis. objectType.xml # For any type of object related to events, you have to define an object type for the object type definition com.woltlab.wcf.notification.objectType : objectType.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectType.xsd\" > <import> <type> <name> com.woltlab.example.foo </name> <definitionname> com.woltlab.wcf.notification.objectType </definitionname> <classname> example\\system\\user\\notification\\object\\type\\FooUserNotificationObjectType </classname> <category> com.woltlab.example </category> </type> </import> </data> The referenced class FooUserNotificationObjectType has to implement the IUserNotificationObjectType interface, which should be done by extending AbstractUserNotificationObjectType . files/lib/system/user/notification/object/type/FooUserNotificationObjectType.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <? php namespace example\\system\\user\\notification\\object\\type ; use example\\data\\foo\\Foo ; use example\\data\\foo\\FooList ; use example\\system\\user\\notification\\object\\FooUserNotificationObject ; use wcf\\system\\user\\notification\\object\\type\\AbstractUserNotificationObjectType ; /** * Represents a foo as a notification object type. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Object\\Type */ class FooUserNotificationObjectType extends AbstractUserNotificationObjectType { /** * @inheritDoc */ protected static $decoratorClassName = FooUserNotificationObject :: class ; /** * @inheritDoc */ protected static $objectClassName = Foo :: class ; /** * @inheritDoc */ protected static $objectListClassName = FooList :: class ; } You have to set the class names of the database object ( $objectClassName ) and the related list ( $objectListClassName ). Additionally, you have to create a class that implements the IUserNotificationObject whose name you have to set as the value of the $decoratorClassName property. files/lib/system/user/notification/object/FooUserNotificationObject.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <? php namespace example\\system\\user\\notification\\object ; use example\\data\\foo\\Foo ; use wcf\\data\\DatabaseObjectDecorator ; use wcf\\system\\user\\notification\\object\\IUserNotificationObject ; /** * Represents a foo as a notification object. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Object * * @method Foo getDecoratedObject() * @mixin Foo */ class FooUserNotificationObject extends DatabaseObjectDecorator implements IUserNotificationObject { /** * @inheritDoc */ protected static $baseClass = Foo :: class ; /** * @inheritDoc */ public function getTitle () { return $this -> getDecoratedObject () -> getTitle (); } /** * @inheritDoc */ public function getURL () { return $this -> getDecoratedObject () -> getLink (); } /** * @inheritDoc */ public function getAuthorID () { return $this -> getDecoratedObject () -> userID ; } } The getTitle() method returns the title of the object. In this case, we assume that the Foo class has implemented the ITitledObject interface so that the decorated Foo can handle this method call itself. The getURL() method returns the link to the object. As for the getTitle() , we assume that the Foo class has implemented the ILinkableObject interface so that the decorated Foo can also handle this method call itself. The getAuthorID() method returns the id of the user who created the decorated Foo object. We assume that Foo objects have a userID property that contains this id. userNotificationEvent.xml # Each event that you fire in your package needs to be registered using the user notification event package installation plugin . An example file might look like this: userNotificationEvent.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userNotificationEvent.xsd\" > <import> <event> <name> bar </name> <objecttype> com.woltlab.example.foo </objecttype> <classname> example\\system\\user\\notification\\event\\FooUserNotificationEvent </classname> <preset> 1 </preset> </event> </import> </data> Here, you reference the user notification object type created via objectType.xml . The referenced class in the <classname> element has to implement the IUserNotificationEvent interface by extending the AbstractUserNotificationEvent class or the AbstractSharedUserNotificationEvent class if you want to pre-load additional data before processing notifications. In AbstractSharedUserNotificationEvent::prepare() , you can, for example, tell runtime caches to prepare to load certain objects which then are loaded all at once when the objects are needed. files/lib/system/user/notification/event/FooUserNotificationEvent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 <? php namespace example\\system\\user\\notification\\event ; use example\\system\\cache\\runtime\\BazRuntimeCache ; use example\\system\\user\\notification\\object\\FooUserNotificationObject ; use wcf\\system\\email\\Email ; use wcf\\system\\request\\LinkHandler ; use wcf\\system\\user\\notification\\event\\AbstractSharedUserNotificationEvent ; /** * Notification event for foos. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Event * * @method FooUserNotificationObject getUserNotificationObject() */ class FooUserNotificationEvent extends AbstractSharedUserNotificationEvent { /** * @inheritDoc */ protected $stackable = true ; /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function checkAccess () { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); if ( ! $this -> getUserNotificationObject () -> isAccessible ()) { // do some cleanup, if necessary return false ; } return true ; } /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function getEmailMessage ( $notificationType = 'instant' ) { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); $messageID = '<com.woltlab.example.baz/' . $this -> getUserNotificationObject () -> bazID . '@' . Email :: getHost () . '>' ; return [ 'application' => 'example' , 'in-reply-to' => [ $messageID ], 'message-id' => 'com.woltlab.example.foo/' . $this -> getUserNotificationObject () -> fooID , 'references' => [ $messageID ], 'template' => 'email_notification_foo' ]; } /** * @inheritDoc * @since 5.0 */ public function getEmailTitle () { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.mail.title' , [ 'userNotificationObject' => $this -> getUserNotificationObject () ]); } /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function getEventHash () { return sha1 ( $this -> eventID . '-' . $this -> getUserNotificationObject () -> bazID ); } /** * @inheritDoc */ public function getLink () { return LinkHandler :: getInstance () -> getLink ( 'Foo' , [ 'application' => 'example' , 'object' => $this -> getUserNotificationObject () -> getDecoratedObject () ]); } /** * @inheritDoc */ public function getMessage () { $authors = $this -> getAuthors (); $count = count ( $authors ); if ( $count > 1 ) { if ( isset ( $authors [ 0 ])) { unset ( $authors [ 0 ]); } $count = count ( $authors ); return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.message.stacked' , [ 'author' => $this -> author , 'authors' => array_values ( $authors ), 'count' => $count , 'guestTimesTriggered' => $this -> notification -> guestTimesTriggered , 'message' => $this -> getUserNotificationObject (), 'others' => $count - 1 ]); } return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.message' , [ 'author' => $this -> author , 'userNotificationObject' => $this -> getUserNotificationObject () ]); } /** * @inheritDoc */ public function getTitle () { $count = count ( $this -> getAuthors ()); if ( $count > 1 ) { return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.title.stacked' , [ 'count' => $count , 'timesTriggered' => $this -> notification -> timesTriggered ]); } return $this -> getLanguage () -> get ( 'example.foo.notification.title' ); } /** * @inheritDoc */ protected function prepare () { BazRuntimeCache :: getInstance () -> cacheObjectID ( $this -> getUserNotificationObject () -> bazID ); } } The $stackable property is false by default and has to be explicitly set to true if stacking of notifications should be enabled. Stacking of notification does not create new notifications for the same event for a certain object if the related action as been triggered by different users. For example, if something is liked by one user and then liked again by another user before the recipient of the notification has confirmed it, the existing notification will be amended to include both users who liked the content. Stacking can thus be used to avoid cluttering the notification list of users. The checkAccess() method makes sure that the active user still has access to the object related to the notification. If that is not the case, the user notification system will automatically deleted the user notification based on the return value of the method. If you have any cached values related to notifications, you should also reset these values here. The getEmailMessage() method return data to create the instant email or the daily summary email. For instant emails ( $notificationType = 'instant' ), you have to return an array like the one shown in the code above with the following components: application : abbreviation of application in-reply-to (optional): message id of the notification for the parent item and used to improve the ordering in threaded email clients message-id (optional): message id of the notification mail and has to be used in in-reply-to and references for follow up mails references (optional): all of the message ids of parent items (i.e. recursive in-reply-to) template : name of the template used to render the email body, should start with email_ variables (optional): template variables passed to the email template where they can be accessed via $notificationContent[variables] For daily emails ( $notificationType = 'daily' ), only application , template , and variables are supported. - The getEmailTitle() returns the title of the instant email sent to the user. By default, getEmailTitle() simply calls getTitle() . - The getEventHash() method returns a hash by which user notifications are grouped. Here, we want to group them not by the actual Foo object but by its parent Baz object and thus overwrite the default implementation provided by AbstractUserNotificationEvent . - The getLink() returns the link to the Foo object the notification belongs to. - The getMessage() method and the getTitle() return the message and the title of the user notification respectively. By checking the value of count($this->getAuthors()) , we check if the notification is stacked, thus if the event has been triggered for multiple users so that different languages items are used. If your notification event does not support stacking, this distinction is not necessary. - The prepare() method is called for each user notification before all user notifications are rendered. This allows to tell runtime caches to prepare to load objects later on (see Runtime Caches ). Firing Events # When the action related to a user notification is executed, you can use UserNotificationHandler::fireEvent() to create the notifications: 1 2 3 4 5 6 7 $recipientIDs = []; // fill with user ids of the recipients of the notification UserNotificationHandler :: getInstance () -> fireEvent ( 'bar' , // event name 'com.woltlab.example.foo' , // event object type name new FooUserNotificationObject ( new Foo ( $fooID )), // object related to the event $recipientIDs ); Marking Notifications as Confirmed # In some instances, you might want to manually mark user notifications as confirmed without the user manually confirming them, for example when they visit the page that is related to the user notification. In this case, you can use UserNotificationHandler::markAsConfirmed() : 1 2 3 4 5 6 7 8 $recipientIDs = []; // fill with user ids of the recipients of the notification $fooIDs = []; // fill with ids of related foo objects UserNotificationHandler :: getInstance () -> markAsConfirmed ( 'bar' , // event name 'com.woltlab.example.foo' , // event object type name $recipientIDs , $fooIDs );","title":"User Notifications"},{"location":"php/api/user_notifications/#user-notifications","text":"WoltLab Suite includes a powerful user notification system that supports notifications directly shown on the website and emails sent immediately or on a daily basis.","title":"User Notifications"},{"location":"php/api/user_notifications/#objecttypexml","text":"For any type of object related to events, you have to define an object type for the object type definition com.woltlab.wcf.notification.objectType : objectType.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectType.xsd\" > <import> <type> <name> com.woltlab.example.foo </name> <definitionname> com.woltlab.wcf.notification.objectType </definitionname> <classname> example\\system\\user\\notification\\object\\type\\FooUserNotificationObjectType </classname> <category> com.woltlab.example </category> </type> </import> </data> The referenced class FooUserNotificationObjectType has to implement the IUserNotificationObjectType interface, which should be done by extending AbstractUserNotificationObjectType . files/lib/system/user/notification/object/type/FooUserNotificationObjectType.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <? php namespace example\\system\\user\\notification\\object\\type ; use example\\data\\foo\\Foo ; use example\\data\\foo\\FooList ; use example\\system\\user\\notification\\object\\FooUserNotificationObject ; use wcf\\system\\user\\notification\\object\\type\\AbstractUserNotificationObjectType ; /** * Represents a foo as a notification object type. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Object\\Type */ class FooUserNotificationObjectType extends AbstractUserNotificationObjectType { /** * @inheritDoc */ protected static $decoratorClassName = FooUserNotificationObject :: class ; /** * @inheritDoc */ protected static $objectClassName = Foo :: class ; /** * @inheritDoc */ protected static $objectListClassName = FooList :: class ; } You have to set the class names of the database object ( $objectClassName ) and the related list ( $objectListClassName ). Additionally, you have to create a class that implements the IUserNotificationObject whose name you have to set as the value of the $decoratorClassName property. files/lib/system/user/notification/object/FooUserNotificationObject.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <? php namespace example\\system\\user\\notification\\object ; use example\\data\\foo\\Foo ; use wcf\\data\\DatabaseObjectDecorator ; use wcf\\system\\user\\notification\\object\\IUserNotificationObject ; /** * Represents a foo as a notification object. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Object * * @method Foo getDecoratedObject() * @mixin Foo */ class FooUserNotificationObject extends DatabaseObjectDecorator implements IUserNotificationObject { /** * @inheritDoc */ protected static $baseClass = Foo :: class ; /** * @inheritDoc */ public function getTitle () { return $this -> getDecoratedObject () -> getTitle (); } /** * @inheritDoc */ public function getURL () { return $this -> getDecoratedObject () -> getLink (); } /** * @inheritDoc */ public function getAuthorID () { return $this -> getDecoratedObject () -> userID ; } } The getTitle() method returns the title of the object. In this case, we assume that the Foo class has implemented the ITitledObject interface so that the decorated Foo can handle this method call itself. The getURL() method returns the link to the object. As for the getTitle() , we assume that the Foo class has implemented the ILinkableObject interface so that the decorated Foo can also handle this method call itself. The getAuthorID() method returns the id of the user who created the decorated Foo object. We assume that Foo objects have a userID property that contains this id.","title":"objectType.xml"},{"location":"php/api/user_notifications/#usernotificationeventxml","text":"Each event that you fire in your package needs to be registered using the user notification event package installation plugin . An example file might look like this: userNotificationEvent.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userNotificationEvent.xsd\" > <import> <event> <name> bar </name> <objecttype> com.woltlab.example.foo </objecttype> <classname> example\\system\\user\\notification\\event\\FooUserNotificationEvent </classname> <preset> 1 </preset> </event> </import> </data> Here, you reference the user notification object type created via objectType.xml . The referenced class in the <classname> element has to implement the IUserNotificationEvent interface by extending the AbstractUserNotificationEvent class or the AbstractSharedUserNotificationEvent class if you want to pre-load additional data before processing notifications. In AbstractSharedUserNotificationEvent::prepare() , you can, for example, tell runtime caches to prepare to load certain objects which then are loaded all at once when the objects are needed. files/lib/system/user/notification/event/FooUserNotificationEvent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 <? php namespace example\\system\\user\\notification\\event ; use example\\system\\cache\\runtime\\BazRuntimeCache ; use example\\system\\user\\notification\\object\\FooUserNotificationObject ; use wcf\\system\\email\\Email ; use wcf\\system\\request\\LinkHandler ; use wcf\\system\\user\\notification\\event\\AbstractSharedUserNotificationEvent ; /** * Notification event for foos. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Event * * @method FooUserNotificationObject getUserNotificationObject() */ class FooUserNotificationEvent extends AbstractSharedUserNotificationEvent { /** * @inheritDoc */ protected $stackable = true ; /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function checkAccess () { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); if ( ! $this -> getUserNotificationObject () -> isAccessible ()) { // do some cleanup, if necessary return false ; } return true ; } /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function getEmailMessage ( $notificationType = 'instant' ) { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); $messageID = '<com.woltlab.example.baz/' . $this -> getUserNotificationObject () -> bazID . '@' . Email :: getHost () . '>' ; return [ 'application' => 'example' , 'in-reply-to' => [ $messageID ], 'message-id' => 'com.woltlab.example.foo/' . $this -> getUserNotificationObject () -> fooID , 'references' => [ $messageID ], 'template' => 'email_notification_foo' ]; } /** * @inheritDoc * @since 5.0 */ public function getEmailTitle () { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.mail.title' , [ 'userNotificationObject' => $this -> getUserNotificationObject () ]); } /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function getEventHash () { return sha1 ( $this -> eventID . '-' . $this -> getUserNotificationObject () -> bazID ); } /** * @inheritDoc */ public function getLink () { return LinkHandler :: getInstance () -> getLink ( 'Foo' , [ 'application' => 'example' , 'object' => $this -> getUserNotificationObject () -> getDecoratedObject () ]); } /** * @inheritDoc */ public function getMessage () { $authors = $this -> getAuthors (); $count = count ( $authors ); if ( $count > 1 ) { if ( isset ( $authors [ 0 ])) { unset ( $authors [ 0 ]); } $count = count ( $authors ); return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.message.stacked' , [ 'author' => $this -> author , 'authors' => array_values ( $authors ), 'count' => $count , 'guestTimesTriggered' => $this -> notification -> guestTimesTriggered , 'message' => $this -> getUserNotificationObject (), 'others' => $count - 1 ]); } return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.message' , [ 'author' => $this -> author , 'userNotificationObject' => $this -> getUserNotificationObject () ]); } /** * @inheritDoc */ public function getTitle () { $count = count ( $this -> getAuthors ()); if ( $count > 1 ) { return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.title.stacked' , [ 'count' => $count , 'timesTriggered' => $this -> notification -> timesTriggered ]); } return $this -> getLanguage () -> get ( 'example.foo.notification.title' ); } /** * @inheritDoc */ protected function prepare () { BazRuntimeCache :: getInstance () -> cacheObjectID ( $this -> getUserNotificationObject () -> bazID ); } } The $stackable property is false by default and has to be explicitly set to true if stacking of notifications should be enabled. Stacking of notification does not create new notifications for the same event for a certain object if the related action as been triggered by different users. For example, if something is liked by one user and then liked again by another user before the recipient of the notification has confirmed it, the existing notification will be amended to include both users who liked the content. Stacking can thus be used to avoid cluttering the notification list of users. The checkAccess() method makes sure that the active user still has access to the object related to the notification. If that is not the case, the user notification system will automatically deleted the user notification based on the return value of the method. If you have any cached values related to notifications, you should also reset these values here. The getEmailMessage() method return data to create the instant email or the daily summary email. For instant emails ( $notificationType = 'instant' ), you have to return an array like the one shown in the code above with the following components: application : abbreviation of application in-reply-to (optional): message id of the notification for the parent item and used to improve the ordering in threaded email clients message-id (optional): message id of the notification mail and has to be used in in-reply-to and references for follow up mails references (optional): all of the message ids of parent items (i.e. recursive in-reply-to) template : name of the template used to render the email body, should start with email_ variables (optional): template variables passed to the email template where they can be accessed via $notificationContent[variables] For daily emails ( $notificationType = 'daily' ), only application , template , and variables are supported. - The getEmailTitle() returns the title of the instant email sent to the user. By default, getEmailTitle() simply calls getTitle() . - The getEventHash() method returns a hash by which user notifications are grouped. Here, we want to group them not by the actual Foo object but by its parent Baz object and thus overwrite the default implementation provided by AbstractUserNotificationEvent . - The getLink() returns the link to the Foo object the notification belongs to. - The getMessage() method and the getTitle() return the message and the title of the user notification respectively. By checking the value of count($this->getAuthors()) , we check if the notification is stacked, thus if the event has been triggered for multiple users so that different languages items are used. If your notification event does not support stacking, this distinction is not necessary. - The prepare() method is called for each user notification before all user notifications are rendered. This allows to tell runtime caches to prepare to load objects later on (see Runtime Caches ).","title":"userNotificationEvent.xml"},{"location":"php/api/user_notifications/#firing-events","text":"When the action related to a user notification is executed, you can use UserNotificationHandler::fireEvent() to create the notifications: 1 2 3 4 5 6 7 $recipientIDs = []; // fill with user ids of the recipients of the notification UserNotificationHandler :: getInstance () -> fireEvent ( 'bar' , // event name 'com.woltlab.example.foo' , // event object type name new FooUserNotificationObject ( new Foo ( $fooID )), // object related to the event $recipientIDs );","title":"Firing Events"},{"location":"php/api/user_notifications/#marking-notifications-as-confirmed","text":"In some instances, you might want to manually mark user notifications as confirmed without the user manually confirming them, for example when they visit the page that is related to the user notification. In this case, you can use UserNotificationHandler::markAsConfirmed() : 1 2 3 4 5 6 7 8 $recipientIDs = []; // fill with user ids of the recipients of the notification $fooIDs = []; // fill with ids of related foo objects UserNotificationHandler :: getInstance () -> markAsConfirmed ( 'bar' , // event name 'com.woltlab.example.foo' , // event object type name $recipientIDs , $fooIDs );","title":"Marking Notifications as Confirmed"},{"location":"php/api/form_builder/dependencies/","text":"Form Node Dependencies # Form node dependencies allow to make parts of a form dynamically available or unavailable depending on the values of form fields. Dependencies are always added to the object whose visibility is determined by certain form fields. They are not added to the form field\u2019s whose values determine the visibility! An example is a text form field that should only be available if a certain option from a single selection form field is selected. Form builder\u2019s dependency system supports such scenarios and also automatically making form containers unavailable once all of its children are unavailable. If a form node has multiple dependencies and one of them is not met, the form node is unavailable. A form node not being available due to dependencies has to the following consequences: The form field value is not validated. It is, however, read from the request data as all request data needs to be read first so that the dependencies can determine whether they are met or not. No data is collected for the form field and returned by IFormDocument::getData() . In the actual form, the form field will be hidden via JavaScript. IFormFieldDependency # The basis of the dependencies is the IFormFieldDependency interface that has to be implemented by every dependency class. The interface requires the following methods: checkDependency() checks if the dependency is met, thus if the dependant form field should be considered available. dependentNode(IFormNode $node) and getDependentNode() can be used to set and get the node whose availability depends on the referenced form field. TFormNode::addDependency() automatically calls dependentNode(IFormNode $node) with itself as the dependent node, thus the dependent node is automatically set by the API. field(IFormField $field) and getField() can be used to set and get the form field that influences the availability of the dependent node. fieldId($fieldId) and getFieldId() can be used to set and get the id of the form field that influences the availability of the dependent node. getHtml() returns JavaScript code required to ensure the dependency in the form output. getId() returns the id of the dependency used to identify multiple dependencies of the same form node. static create($id) is the factory method that has to be used to create new dependencies with the given id. AbstractFormFieldDependency provides default implementations for all methods except for checkDependency() . Using fieldId($fieldId) instead of field(IFormField $field) makes sense when adding the dependency directly when setting up the form: 1 2 3 4 5 6 7 8 9 $container -> appendChildren ([ FooField :: create ( 'a' ), BarField :: create ( 'b' ) -> addDependency ( BazDependency :: create ( 'a' ) -> fieldId ( 'a' ) ) ]); Here, without an additional assignment, the first field with id a cannot be accessed thus fieldId($fieldId) should be used as the id of the relevant field is known. When the form is built, all dependencies that only know the id of the relevant field and do not have a reference for the actual object are populated with the actual form field objects. Default Dependencies # WoltLab Suite Core delivers the following default dependency classes by default: NonEmptyFormFieldDependency # NonEmptyFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is not empty (being empty is determined using PHP\u2019s empty() language construct). EmptyFormFieldDependency # This is the inverse of NonEmptyFormFieldDependency , checking for !empty() . ValueFormFieldDependency # ValueFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is from a specified list of of values (see methods values($values) and getValues() ). Additionally, via negate($negate = true) and isNegated() , the logic can also be inverted by requiring the value of the referenced form field not to be from a specified list of values. ValueIntervalFormFieldDependency # Only available since version 5.5. ValueIntervalFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is in a specific interval whose boundaries are set via minimum(?float $minimum = null) and maximum(?float $maximum = null) . IsNotClickedFormFieldDependency # IsNotClickedFormFieldDependency is a special dependency for ButtonFormField s . Refer to the documentation of ButtomFormField for details. JavaScript Implementation # To ensure that dependent node are correctly shown and hidden when changing the value of referenced form fields, every PHP dependency class has a corresponding JavaScript module that checks the dependency in the browser. Every JavaScript dependency has to extend WoltLabSuite/Core/Form/Builder/Field/Dependency/Abstract and implement the checkDependency() function, the JavaScript version of IFormFieldDependency::checkDependency() . All of the JavaScript dependency objects automatically register themselves during initialization with the WoltLabSuite/Core/Form/Builder/Field/Dependency/Manager which takes care of checking the dependencies at the correct points in time. Additionally, the dependency manager also ensures that form containers in which all children are hidden due to dependencies are also hidden and, once any child becomes available again, makes the container also available again. Every form container has to create a matching form container dependency object from a module based on WoltLabSuite/Core/Form/Builder/Field/Dependency/Abstract . Examples # If $booleanFormField is an instance of BooleanFormField and the text form field $textFormField should only be available if \u201cYes\u201d has been selected, the following condition has to be set up: 1 2 3 4 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'booleanFormField' ) -> field ( $booleanFormField ) ); If $singleSelectionFormField is an instance of SingleSelectionFormField that offers the options 1 , 2 , and 3 and $textFormField should only be available if 1 or 3 is selected, the following condition has to be set up: 1 2 3 4 5 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'singleSelectionFormField' ) -> field ( $singleSelectionFormField ) -> values ([ 1 , 3 ]) ); If, in contrast, $singleSelectionFormField has many available options and 7 is the only option for which $textFormField should not be available, negate() should be used: 1 2 3 4 5 6 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'singleSelectionFormField' ) -> field ( $singleSelectionFormField ) -> values ([ 7 ]) -> negate () );","title":"Dependencies"},{"location":"php/api/form_builder/dependencies/#form-node-dependencies","text":"Form node dependencies allow to make parts of a form dynamically available or unavailable depending on the values of form fields. Dependencies are always added to the object whose visibility is determined by certain form fields. They are not added to the form field\u2019s whose values determine the visibility! An example is a text form field that should only be available if a certain option from a single selection form field is selected. Form builder\u2019s dependency system supports such scenarios and also automatically making form containers unavailable once all of its children are unavailable. If a form node has multiple dependencies and one of them is not met, the form node is unavailable. A form node not being available due to dependencies has to the following consequences: The form field value is not validated. It is, however, read from the request data as all request data needs to be read first so that the dependencies can determine whether they are met or not. No data is collected for the form field and returned by IFormDocument::getData() . In the actual form, the form field will be hidden via JavaScript.","title":"Form Node Dependencies"},{"location":"php/api/form_builder/dependencies/#iformfielddependency","text":"The basis of the dependencies is the IFormFieldDependency interface that has to be implemented by every dependency class. The interface requires the following methods: checkDependency() checks if the dependency is met, thus if the dependant form field should be considered available. dependentNode(IFormNode $node) and getDependentNode() can be used to set and get the node whose availability depends on the referenced form field. TFormNode::addDependency() automatically calls dependentNode(IFormNode $node) with itself as the dependent node, thus the dependent node is automatically set by the API. field(IFormField $field) and getField() can be used to set and get the form field that influences the availability of the dependent node. fieldId($fieldId) and getFieldId() can be used to set and get the id of the form field that influences the availability of the dependent node. getHtml() returns JavaScript code required to ensure the dependency in the form output. getId() returns the id of the dependency used to identify multiple dependencies of the same form node. static create($id) is the factory method that has to be used to create new dependencies with the given id. AbstractFormFieldDependency provides default implementations for all methods except for checkDependency() . Using fieldId($fieldId) instead of field(IFormField $field) makes sense when adding the dependency directly when setting up the form: 1 2 3 4 5 6 7 8 9 $container -> appendChildren ([ FooField :: create ( 'a' ), BarField :: create ( 'b' ) -> addDependency ( BazDependency :: create ( 'a' ) -> fieldId ( 'a' ) ) ]); Here, without an additional assignment, the first field with id a cannot be accessed thus fieldId($fieldId) should be used as the id of the relevant field is known. When the form is built, all dependencies that only know the id of the relevant field and do not have a reference for the actual object are populated with the actual form field objects.","title":"IFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#default-dependencies","text":"WoltLab Suite Core delivers the following default dependency classes by default:","title":"Default Dependencies"},{"location":"php/api/form_builder/dependencies/#nonemptyformfielddependency","text":"NonEmptyFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is not empty (being empty is determined using PHP\u2019s empty() language construct).","title":"NonEmptyFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#emptyformfielddependency","text":"This is the inverse of NonEmptyFormFieldDependency , checking for !empty() .","title":"EmptyFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#valueformfielddependency","text":"ValueFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is from a specified list of of values (see methods values($values) and getValues() ). Additionally, via negate($negate = true) and isNegated() , the logic can also be inverted by requiring the value of the referenced form field not to be from a specified list of values.","title":"ValueFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#valueintervalformfielddependency","text":"Only available since version 5.5. ValueIntervalFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is in a specific interval whose boundaries are set via minimum(?float $minimum = null) and maximum(?float $maximum = null) .","title":"ValueIntervalFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#isnotclickedformfielddependency","text":"IsNotClickedFormFieldDependency is a special dependency for ButtonFormField s . Refer to the documentation of ButtomFormField for details.","title":"IsNotClickedFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#javascript-implementation","text":"To ensure that dependent node are correctly shown and hidden when changing the value of referenced form fields, every PHP dependency class has a corresponding JavaScript module that checks the dependency in the browser. Every JavaScript dependency has to extend WoltLabSuite/Core/Form/Builder/Field/Dependency/Abstract and implement the checkDependency() function, the JavaScript version of IFormFieldDependency::checkDependency() . All of the JavaScript dependency objects automatically register themselves during initialization with the WoltLabSuite/Core/Form/Builder/Field/Dependency/Manager which takes care of checking the dependencies at the correct points in time. Additionally, the dependency manager also ensures that form containers in which all children are hidden due to dependencies are also hidden and, once any child becomes available again, makes the container also available again. Every form container has to create a matching form container dependency object from a module based on WoltLabSuite/Core/Form/Builder/Field/Dependency/Abstract .","title":"JavaScript Implementation"},{"location":"php/api/form_builder/dependencies/#examples","text":"If $booleanFormField is an instance of BooleanFormField and the text form field $textFormField should only be available if \u201cYes\u201d has been selected, the following condition has to be set up: 1 2 3 4 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'booleanFormField' ) -> field ( $booleanFormField ) ); If $singleSelectionFormField is an instance of SingleSelectionFormField that offers the options 1 , 2 , and 3 and $textFormField should only be available if 1 or 3 is selected, the following condition has to be set up: 1 2 3 4 5 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'singleSelectionFormField' ) -> field ( $singleSelectionFormField ) -> values ([ 1 , 3 ]) ); If, in contrast, $singleSelectionFormField has many available options and 7 is the only option for which $textFormField should not be available, negate() should be used: 1 2 3 4 5 6 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'singleSelectionFormField' ) -> field ( $singleSelectionFormField ) -> values ([ 7 ]) -> negate () );","title":"Examples"},{"location":"php/api/form_builder/form_fields/","text":"Form Builder Fields # Abstract Form Fields # The following form field classes cannot be instantiated directly because they are abstract, but they can/must be used when creating own form field classes. AbstractFormField # AbstractFormField is the abstract default implementation of the IFormField interface and it is expected that every implementation of IFormField implements the interface by extending this class. AbstractNumericFormField # AbstractNumericFormField is the abstract implementation of a form field handling a single numeric value. The class implements IAttributeFormField , IAutoCompleteFormField , ICssClassFormField , IImmutableFormField , IInputModeFormField , IMaximumFormField , IMinimumFormField , INullableFormField , IPlaceholderFormField and ISuffixedFormField . If the property $integerValues is true , the form field works with integer values, otherwise it works with floating point numbers. The methods step($step = null) and getStep() can be used to set and get the step attribute of the input element. The default step for form fields with integer values is 1 . Otherwise, the default step is any . AbstractFormFieldDecorator # Only available since version 5.4.5. AbstractFormFieldDecorator is a default implementation of a decorator for form fields that forwards calls to all methods defined in IFormField to the respective method of the decorated object. The class implements IFormfield . If the implementation of a more specific interface is required then the remaining methods must be implemented in the concrete decorator derived from AbstractFormFieldDecorator and the type of the $field property must be narrowed appropriately. General Form Fields # The following form fields are general reusable fields without any underlying context. BooleanFormField # BooleanFormField is used for boolean ( 0 or 1 , yes or no ) values. Objects of this class require a label. The return value of getSaveValue() is the integer representation of the boolean value, i.e. 0 or 1 . The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , and IImmutableFormField . CheckboxFormField # Only available since version 5.3.2. CheckboxFormField extends BooleanFormField and offers a simple HTML checkbox. ClassNameFormField # ClassNameFormField is a text form field that supports additional settings, specific to entering a PHP class name: classExists($classExists = true) and getClassExists() can be used to ensure that the entered class currently exists in the installation. By default, the existance of the entered class is required. implementedInterface($interface) and getImplementedInterface() can be used to ensure that the entered class implements the specified interface. By default, no interface is required. parentClass($parentClass) and getParentClass() can be used to ensure that the entered class extends the specified class. By default, no parent class is required. instantiable($instantiable = true) and isInstantiable() can be used to ensure that the entered class is instantiable. By default, entered classes have to instantiable. Additionally, the default id of a ClassNameFormField object is className , the default label is wcf.form.field.className , and if either an interface or a parent class is required, a default description is set if no description has already been set ( wcf.form.field.className.description.interface and wcf.form.field.className.description.parentClass , respectively). DateFormField # DateFormField is a form field to enter a date (and optionally a time). The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , IImmutableFormField , and INullableFormField . The following methods are specific to this form field class: earliestDate($earliestDate) and getEarliestDate() can be used to get and set the earliest selectable/valid date and latestDate($latestDate) and getLatestDate() can be used to get and set the latest selectable/valid date. The date passed to the setters must have the same format as set via saveValueFormat() . If a custom format is used, that format has to be set via saveValueFormat() before calling any of the setters. saveValueFormat($saveValueFormat) and getSaveValueFormat() can be used to specify the date format of the value returned by getSaveValue() . By default, U is used as format. The PHP manual provides an overview of supported formats. supportTime($supportsTime = true) and supportsTime() can be used to toggle whether, in addition to a date, a time can also be specified. By default, specifying a time is disabled. DescriptionFormField # DescriptionFormField is a multi-line text form field with description as the default id and wcf.global.description as the default label. EmailFormField # EmailFormField is a form field to enter an email address which is internally validated using UserUtil::isValidEmail() . The class implements IAttributeFormField , IAutoCompleteFormField , IAutoFocusFormField , ICssClassFormField , II18nFormField , IImmutableFormField , IInputModeFormField , IPatternFormField , and IPlaceholderFormField . FloatFormField # FloatFormField is an implementation of AbstractNumericFormField for floating point numbers. IconFormField # IconFormField is a form field to select a FontAwesome icon. IntegerFormField # IntegerFormField is an implementation of AbstractNumericFormField for integers. IsDisabledFormField # IsDisabledFormField is a boolean form field with isDisabled as the default id. ItemListFormField # ItemListFormField is a form field in which multiple values can be entered and returned in different formats as save value. The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , IImmutableFormField , and IMultipleFormField . The saveValueType($saveValueType) and getSaveValueType() methods are specific to this form field class and determine the format of the save value. The following save value types are supported: ItemListFormField::SAVE_VALUE_TYPE_ARRAY adds a custom data processor that writes the form field data directly in the parameters array and not in the data sub-array of the parameters array. ItemListFormField::SAVE_VALUE_TYPE_CSV lets the value be returned as a string in which the values are concatenated by commas. ItemListFormField::SAVE_VALUE_TYPE_NSV lets the value be returned as a string in which the values are concatenated by \\n . ItemListFormField::SAVE_VALUE_TYPE_SSV lets the value be returned as a string in which the values are concatenated by spaces. By default, ItemListFormField::SAVE_VALUE_TYPE_CSV is used. If ItemListFormField::SAVE_VALUE_TYPE_ARRAY is used as save value type, ItemListFormField objects register a custom form field data processor to add the relevant array into the $parameters array directly using the object property as the array key. MultilineTextFormField # MultilineTextFormField is a text form field that supports multiple rows of text. The methods rows($rows) and getRows() can be used to set and get the number of rows of the textarea elements. The default number of rows is 10 . These methods do not , however, restrict the number of text rows that can be entered. MultipleSelectionFormField # MultipleSelectionFormField is a form fields that allows the selection of multiple options out of a predefined list of available options. The class implements IAttributeFormField , ICssClassFormField , IFilterableSelectionFormField , IImmutableFormField , and INullableFormField . If the field is nullable and no option is selected, null is returned as the save value. RadioButtonFormField # RadioButtonFormField is a form fields that allows the selection of a single option out of a predefined list of available options using radiobuttons. The class implements IAttributeFormField , ICssClassFormField , IImmutableFormField , and ISelectionFormField . RatingFormField # RatingFormField is a form field to set a rating for an object. The class implements IImmutableFormField , IMaximumFormField , IMinimumFormField , and INullableFormField . Form fields of this class have rating as their default id, wcf.form.field.rating as their default label, 1 as their default minimum, and 5 as their default maximum. For this field, the minimum and maximum refer to the minimum and maximum rating an object can get. When the field is shown, there will be maximum() - minimum() + 1 icons be shown with additional CSS classes that can be set and gotten via defaultCssClasses(array $cssClasses) and getDefaultCssClasses() . If a rating values is set, the first getValue() icons will instead use the classes that can be set and gotten via activeCssClasses(array $cssClasses) and getActiveCssClasses() . By default, the only default class is fa-star-o and the active classes are fa-star and orange . ShowOrderFormField # ShowOrderFormField is a single selection form field for which the selected value determines the position at which an object is shown. The show order field provides a list of all siblings and the object will be positioned after the selected sibling. To insert objects at the very beginning, the options() automatically method prepends an additional option for that case so that only the existing siblings need to be passed. The default id of instances of this class is showOrder and their default label is wcf.form.field.showOrder . It is important that the relevant object property is always kept updated. Whenever a new object is added or an existing object is edited or delete, the values of the other objects have to be adjusted to ensure consecutive numbering. SingleSelectionFormField # SingleSelectionFormField is a form fields that allows the selection of a single option out of a predefined list of available options. The class implements ICssClassFormField , IFilterableSelectionFormField , IImmutableFormField , and INullableFormField . If the field is nullable and the current form field value is considered empty by PHP, null is returned as the save value. SortOrderFormField # SingleSelectionFormField is a single selection form field with default id sortOrder , default label wcf.global.showOrder and default options ASC: wcf.global.sortOrder.ascending and DESC: wcf.global.sortOrder.descending . TextFormField # TextFormField is a form field that allows entering a single line of text. The class implements IAttributeFormField , IAutoCompleteFormField , ICssClassFormField , IImmutableFormField , II18nFormField , IInputModeFormField , IMaximumLengthFormField , IMinimumLengthFormField , IPatternFormField , and IPlaceholderFormField . TitleFormField # TitleFormField is a text form field with title as the default id and wcf.global.title as the default label. UrlFormField # UrlFormField is a text form field whose values are checked via Url::is() . Specific Fields # The following form fields are reusable fields that generally are bound to a certain API or DatabaseObject implementation. AclFormField # AclFormField is used for setting up acl values for specific objects. The class implements IObjectTypeFormField and requires an object type of the object type definition com.woltlab.wcf.acl . Additionally, the class provides the methods categoryName($categoryName) and getCategoryName() that allow setting a specific name or filter for the acl option categories whose acl options are shown. A category name of null signals that no category filter is used. Since version 5.5, the category name also supports filtering using a wildcard like user.* , see WoltLab/WCF#4355 . AclFormField objects register a custom form field data processor to add the relevant ACL object type id into the $parameters array directly using {$objectProperty}_aclObjectTypeID as the array key. The relevant database object action method is expected, based on the given ACL object type id, to save the ACL option values appropriately. ButtonFormField # Only available since version 5.4. ButtonFormField shows a submit button as part of the form. The class implements IAttributeFormField and ICssClassFormField . Specifically for this form field, there is the IsNotClickedFormFieldDependency dependency with which certain parts of the form will only be processed if the relevent button has not clicked. CaptchaFormField # CaptchaFormField is used to add captcha protection to the form. You must specify a captcha object type ( com.woltlab.wcf.captcha ) using the objectType() method. ColorFormField # Only available since version 5.5. ColorFormField is used to specify RGBA colors using the rgba(r, g, b, a) format. The class implements IImmutableFormField . ContentLanguageFormField # ContentLanguageFormField is used to select the content language of an object. Fields of this class are only available if multilingualism is enabled and if there are content languages. The class implements IImmutableFormField . LabelFormField # LabelFormField is used to select a label from a specific label group. The class implements IObjectTypeFormNode . The labelGroup(ViewableLabelGroup $labelGroup) and getLabelGroup() methods are specific to this form field class and can be used to set and get the label group whose labels can be selected. Additionally, there is the static method createFields($objectType, array $labelGroups, $objectProperty = 'labelIDs) that can be used to create all relevant label form fields for a given list of label groups. In most cases, LabelFormField::createFields() should be used. OptionFormField # OptionFormField is an item list form field to set a list of options. The class implements IPackagesFormField and only options of the set packages are considered available. The default label of instances of this class is wcf.form.field.option and their default id is options . SimpleAclFormField # SimpleAclFormField is used for setting up simple acl values (one yes / no option per user and user group) for specific objects. SimpleAclFormField objects register a custom form field data processor to add the relevant simple ACL data array into the $parameters array directly using the object property as the array key. Since version 5.5, the field also supports inverted permissions, see WoltLab/WCF#4570 . The SimpleAclFormField supports inverted permissions, allowing the administrator to grant access to all non-selected users and groups. If this behavior is desired, it needs to be enabled by calling supportInvertedPermissions . An invertPermissions key containing a boolean value with the users selection will be provided together with the ACL values when saving the field. SingleMediaSelectionFormField # SingleMediaSelectionFormField is used to select a specific media file. The class implements IImmutableFormField . The following methods are specific to this form field class: imageOnly($imageOnly = true) and isImageOnly() can be used to set and check if only images may be selected. getMedia() returns the media file based on the current field value if a field is set. TagFormField # TagFormField is a form field to enter tags. The class implements IAttributeFormField and IObjectTypeFormNode . Arrays passed to TagFormField::values() can contain tag names as strings and Tag objects. The default label of instances of this class is wcf.tagging.tags and their default description is wcf.tagging.tags.description . TagFormField objects register a custom form field data processor to add the array with entered tag names into the $parameters array directly using the object property as the array key. UploadFormField # UploadFormField is a form field that allows uploading files by the user. UploadFormField objects register a custom form field data processor to add the array of wcf\\system\\file\\upload\\UploadFile\\UploadFile into the $parameters array directly using the object property as the array key. Also it registers the removed files as an array of wcf\\system\\file\\upload\\UploadFile\\UploadFile into the $parameters array directly using the object property with the suffix _removedFiles as the array key. The field supports additional settings: - imageOnly($imageOnly = true) and isImageOnly() can be used to ensure that the uploaded files are only images. - allowSvgImage($allowSvgImages = true) and svgImageAllowed() can be used to allow SVG images, if the image only mode is enabled (otherwise, the method will throw an exception). By default, SVG images are not allowed. Provide value from database object # To provide values from a database object, you should implement the method get{$objectProperty}UploadFileLocations() to your database object class. This method must return an array of strings with the locations of the files. Process files # To process files in the database object action class, you must rename the file to the final destination. You get the temporary location, by calling the method getLocation() on the given UploadFile objects. After that, you call setProcessed($location) with $location contains the new file location. This method sets the isProcessed flag to true and saves the new location. For updating files, it is relevant, whether a given file is already processed or not. For this case, the UploadFile object has an method isProcessed() which indicates, whether a file is already processed or new uploaded. UserFormField # UserFormField is a form field to enter existing users. The class implements IAutoCompleteFormField , IAutoFocusFormField , IImmutableFormField , IMultipleFormField , and INullableFormField . While the user is presented the names of the specified users in the user interface, the field returns the ids of the users as data. The relevant UserProfile objects can be accessed via the getUsers() method. UserPasswordField # Only available since version 5.4. UserPasswordField is a form field for users' to enter their current password. The class implements IAttributeFormField , IAttributeFormField , IAutoCompleteFormField , IAutoFocusFormField , and IPlaceholderFormField UserGroupOptionFormField # UserGroupOptionFormField is an item list form field to set a list of user group options/permissions. The class implements IPackagesFormField and only user group options of the set packages are considered available. The default label of instances of this class is wcf.form.field.userGroupOption and their default id is permissions . UsernameFormField # UsernameFormField is used for entering one non-existing username. The class implements IAttributeFormField , IImmutableFormField , IMaximumLengthFormField , IMinimumLengthFormField , INullableFormField , and IPlaceholderFormField . As usernames have a system-wide restriction of a minimum length of 3 and a maximum length of 100 characters, these values are also used as the default value for the field\u2019s minimum and maximum length. Wysiwyg form container # To integrate a wysiwyg editor into a form, you have to create a WysiwygFormContainer object. This container takes care of creating all necessary form nodes listed below for a wysiwyg editor. When creating the container object, its id has to be the id of the form field that will manage the actual text. The following methods are specific to this form container class: addSettingsNode(IFormChildNode $settingsNode) and addSettingsNodes(array $settingsNodes) can be used to add nodes to the settings tab container. attachmentData($objectType, $parentObjectID) can be used to set the data relevant for attachment support. By default, not attachment data is set, thus attachments are not supported. getAttachmentField() , getPollContainer() , getSettingsContainer() , getSmiliesContainer() , and getWysiwygField() can be used to get the different components of the wysiwyg form container once the form has been built. enablePreviewButton($enablePreviewButton) can be used to set whether the preview button for the message is shown or not. By default, the preview button is shown. This method is only relevant before the form is built. Afterwards, the preview button availability can not be changed. Only available since WoltLab Suite Core 5.3. getObjectId() returns the id of the edited object or 0 if no object is edited. getPreselect() , preselect($preselect) can be used to set the value of the wysiwyg tab menu's data-preselect attribute used to determine which tab is preselected. By default, the preselect is 'true' which is used to pre-select the first tab. messageObjectType($messageObjectType) can be used to set the message object type. pollObjectType($pollObjectType) can be used to set the poll object type. By default, no poll object type is set, thus the poll form field container is not available. supportMentions($supportMentions) can be used to set if mentions are supported. By default, mentions are not supported. This method is only relevant before the form is built. Afterwards, mention support can only be changed via the wysiwyg form field. supportSmilies($supportSmilies) can be used to set if smilies are supported. By default, smilies are supported. This method is only relevant before the form is built. Afterwards, smiley availability can only be changed via changing the availability of the smilies form container. WysiwygAttachmentFormField # WysiwygAttachmentFormField provides attachment support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . The methods attachmentHandler(AttachmentHandler $attachmentHandler) and getAttachmentHandler() can be used to set and get the AttachmentHandler object that is used for uploaded attachments. WysiwygPollFormContainer # WysiwygPollFormContainer provides poll support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . WysiwygPollFormContainer contains all form fields that are required to create polls and requires edited objects to implement IPollContainer . The following methods are specific to this form container class: getEndTimeField() returns the form field to set the end time of the poll once the form has been built. getIsChangeableField() returns the form field to set if poll votes can be changed once the form has been built. getIsPublicField() returns the form field to set if poll results are public once the form has been built. getMaxVotesField() returns the form field to set the maximum number of votes once the form has been built. getOptionsField() returns the form field to set the poll options once the form has been built. getQuestionField() returns the form field to set the poll question once the form has been built. getResultsRequireVoteField() returns the form field to set if viewing the poll results requires voting once the form has been built. getSortByVotesField() returns the form field to set if the results are sorted by votes once the form has been built. WysiwygSmileyFormContainer # WysiwygSmileyFormContainer provides smiley support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . WysiwygSmileyFormContainer creates a sub-tab for each smiley category. WysiwygSmileyFormNode # WysiwygSmileyFormNode is contains the smilies of a specific category. This class should not be used directly but only via WysiwygSmileyFormContainer . Example # The following code creates a WYSIWYG editor component for a message object property. As smilies are supported by default and an attachment object type is given, the tab menu below the editor has two tabs: \u201cSmilies\u201d and \u201cAttachments\u201d. Additionally, mentions and quotes are supported. 1 2 3 4 5 6 WysiwygFormContainer :: create ( 'message' ) -> label ( 'foo.bar.message' ) -> messageObjectType ( 'com.example.foo.bar' ) -> attachmentData ( 'com.example.foo.bar' ) -> supportMentions () -> supportQuotes () WysiwygFormField # WysiwygFormField is used for wysiwyg editor form fields. This class should, in general, not be used directly but only via WysiwygFormContainer . The class implements IAttributeFormField , IMaximumLengthFormField , IMinimumLengthFormField , and IObjectTypeFormNode and requires an object type of the object type definition com.woltlab.wcf.message . The following methods are specific to this form field class: autosaveId($autosaveId) and getAutosaveId() can be used enable automatically saving the current editor contents in the browser using the given id. An empty string signals that autosaving is disabled. lastEditTime($lastEditTime) and getLastEditTime() can be used to set the last time the contents have been edited and saved so that the JavaScript can determine if the contents stored in the browser are older or newer. 0 signals that no last edit time has been set. supportAttachments($supportAttachments) and supportsAttachments() can be used to set and check if the form field supports attachments. It is not sufficient to simply signal attachment support via these methods for attachments to work. These methods are relevant internally to signal the Javascript code that the editor supports attachments. Actual attachment support is provided by WysiwygAttachmentFormField . supportMentions($supportMentions) and supportsMentions() can be used to set and check if the form field supports mentions of other users. WysiwygFormField objects register a custom form field data processor to add the relevant simple ACL data array into the $parameters array directly using the object property as the array key. TWysiwygFormNode # All form nodes that need to know the id of the WysiwygFormField field should use TWysiwygFormNode . This trait provides getWysiwygId() and wysiwygId($wysiwygId) to get and set the relevant wysiwyg editor id. Application-Specific Form Fields # WoltLab Suite Forum # MultipleBoardSelectionFormField # Only available since version 5.5. MultipleBoardSelectionFormField is used to select multiple forums. The class implements IAttributeFormField , ICssClassFormField , and IImmutableFormField . The field supports additional settings: boardNodeList(BoardNodeList $boardNodeList): self and getBoardNodeList(): BoardNodeList are used to set and get the list of board nodes used to render the board selection. boardNodeList(BoardNodeList $boardNodeList): self will automatically call readNodeTree() on the given board node list. categoriesSelectable(bool $categoriesSelectable = true): self and areCategoriesSelectable(): bool are used to set and check if the categories in the board node list are selectable. By default, categories are selectable. This option is useful if only actual boards, in which threads can be posted, should be selectable but the categories must still be shown so that the overall forum structure is still properly shown. supportExternalLinks(bool $supportExternalLinks): self and supportsExternalLinks(): bool are used to set and check if external links will be shown in the selection list. By default, external links are shown. Like in the example given before, in cases where only actual boards, in which threads can be posted, are relevant, this option allows to exclude external links. Single-Use Form Fields # The following form fields are specific for certain forms and hardly reusable in other contexts. BBCodeAttributesFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the attributes of a BBCode. DevtoolsProjectExcludedPackagesFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the excluded packages of a devtools project. DevtoolsProjectInstructionsFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the installation and update instructions of a devtools project. DevtoolsProjectOptionalPackagesFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the optional packages of a devtools project. DevtoolsProjectRequiredPackagesFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the required packages of a devtools project.","title":"Fields"},{"location":"php/api/form_builder/form_fields/#form-builder-fields","text":"","title":"Form Builder Fields"},{"location":"php/api/form_builder/form_fields/#abstract-form-fields","text":"The following form field classes cannot be instantiated directly because they are abstract, but they can/must be used when creating own form field classes.","title":"Abstract Form Fields"},{"location":"php/api/form_builder/form_fields/#abstractformfield","text":"AbstractFormField is the abstract default implementation of the IFormField interface and it is expected that every implementation of IFormField implements the interface by extending this class.","title":"AbstractFormField"},{"location":"php/api/form_builder/form_fields/#abstractnumericformfield","text":"AbstractNumericFormField is the abstract implementation of a form field handling a single numeric value. The class implements IAttributeFormField , IAutoCompleteFormField , ICssClassFormField , IImmutableFormField , IInputModeFormField , IMaximumFormField , IMinimumFormField , INullableFormField , IPlaceholderFormField and ISuffixedFormField . If the property $integerValues is true , the form field works with integer values, otherwise it works with floating point numbers. The methods step($step = null) and getStep() can be used to set and get the step attribute of the input element. The default step for form fields with integer values is 1 . Otherwise, the default step is any .","title":"AbstractNumericFormField"},{"location":"php/api/form_builder/form_fields/#abstractformfielddecorator","text":"Only available since version 5.4.5. AbstractFormFieldDecorator is a default implementation of a decorator for form fields that forwards calls to all methods defined in IFormField to the respective method of the decorated object. The class implements IFormfield . If the implementation of a more specific interface is required then the remaining methods must be implemented in the concrete decorator derived from AbstractFormFieldDecorator and the type of the $field property must be narrowed appropriately.","title":"AbstractFormFieldDecorator"},{"location":"php/api/form_builder/form_fields/#general-form-fields","text":"The following form fields are general reusable fields without any underlying context.","title":"General Form Fields"},{"location":"php/api/form_builder/form_fields/#booleanformfield","text":"BooleanFormField is used for boolean ( 0 or 1 , yes or no ) values. Objects of this class require a label. The return value of getSaveValue() is the integer representation of the boolean value, i.e. 0 or 1 . The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , and IImmutableFormField .","title":"BooleanFormField"},{"location":"php/api/form_builder/form_fields/#checkboxformfield","text":"Only available since version 5.3.2. CheckboxFormField extends BooleanFormField and offers a simple HTML checkbox.","title":"CheckboxFormField"},{"location":"php/api/form_builder/form_fields/#classnameformfield","text":"ClassNameFormField is a text form field that supports additional settings, specific to entering a PHP class name: classExists($classExists = true) and getClassExists() can be used to ensure that the entered class currently exists in the installation. By default, the existance of the entered class is required. implementedInterface($interface) and getImplementedInterface() can be used to ensure that the entered class implements the specified interface. By default, no interface is required. parentClass($parentClass) and getParentClass() can be used to ensure that the entered class extends the specified class. By default, no parent class is required. instantiable($instantiable = true) and isInstantiable() can be used to ensure that the entered class is instantiable. By default, entered classes have to instantiable. Additionally, the default id of a ClassNameFormField object is className , the default label is wcf.form.field.className , and if either an interface or a parent class is required, a default description is set if no description has already been set ( wcf.form.field.className.description.interface and wcf.form.field.className.description.parentClass , respectively).","title":"ClassNameFormField"},{"location":"php/api/form_builder/form_fields/#dateformfield","text":"DateFormField is a form field to enter a date (and optionally a time). The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , IImmutableFormField , and INullableFormField . The following methods are specific to this form field class: earliestDate($earliestDate) and getEarliestDate() can be used to get and set the earliest selectable/valid date and latestDate($latestDate) and getLatestDate() can be used to get and set the latest selectable/valid date. The date passed to the setters must have the same format as set via saveValueFormat() . If a custom format is used, that format has to be set via saveValueFormat() before calling any of the setters. saveValueFormat($saveValueFormat) and getSaveValueFormat() can be used to specify the date format of the value returned by getSaveValue() . By default, U is used as format. The PHP manual provides an overview of supported formats. supportTime($supportsTime = true) and supportsTime() can be used to toggle whether, in addition to a date, a time can also be specified. By default, specifying a time is disabled.","title":"DateFormField"},{"location":"php/api/form_builder/form_fields/#descriptionformfield","text":"DescriptionFormField is a multi-line text form field with description as the default id and wcf.global.description as the default label.","title":"DescriptionFormField"},{"location":"php/api/form_builder/form_fields/#emailformfield","text":"EmailFormField is a form field to enter an email address which is internally validated using UserUtil::isValidEmail() . The class implements IAttributeFormField , IAutoCompleteFormField , IAutoFocusFormField , ICssClassFormField , II18nFormField , IImmutableFormField , IInputModeFormField , IPatternFormField , and IPlaceholderFormField .","title":"EmailFormField"},{"location":"php/api/form_builder/form_fields/#floatformfield","text":"FloatFormField is an implementation of AbstractNumericFormField for floating point numbers.","title":"FloatFormField"},{"location":"php/api/form_builder/form_fields/#iconformfield","text":"IconFormField is a form field to select a FontAwesome icon.","title":"IconFormField"},{"location":"php/api/form_builder/form_fields/#integerformfield","text":"IntegerFormField is an implementation of AbstractNumericFormField for integers.","title":"IntegerFormField"},{"location":"php/api/form_builder/form_fields/#isdisabledformfield","text":"IsDisabledFormField is a boolean form field with isDisabled as the default id.","title":"IsDisabledFormField"},{"location":"php/api/form_builder/form_fields/#itemlistformfield","text":"ItemListFormField is a form field in which multiple values can be entered and returned in different formats as save value. The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , IImmutableFormField , and IMultipleFormField . The saveValueType($saveValueType) and getSaveValueType() methods are specific to this form field class and determine the format of the save value. The following save value types are supported: ItemListFormField::SAVE_VALUE_TYPE_ARRAY adds a custom data processor that writes the form field data directly in the parameters array and not in the data sub-array of the parameters array. ItemListFormField::SAVE_VALUE_TYPE_CSV lets the value be returned as a string in which the values are concatenated by commas. ItemListFormField::SAVE_VALUE_TYPE_NSV lets the value be returned as a string in which the values are concatenated by \\n . ItemListFormField::SAVE_VALUE_TYPE_SSV lets the value be returned as a string in which the values are concatenated by spaces. By default, ItemListFormField::SAVE_VALUE_TYPE_CSV is used. If ItemListFormField::SAVE_VALUE_TYPE_ARRAY is used as save value type, ItemListFormField objects register a custom form field data processor to add the relevant array into the $parameters array directly using the object property as the array key.","title":"ItemListFormField"},{"location":"php/api/form_builder/form_fields/#multilinetextformfield","text":"MultilineTextFormField is a text form field that supports multiple rows of text. The methods rows($rows) and getRows() can be used to set and get the number of rows of the textarea elements. The default number of rows is 10 . These methods do not , however, restrict the number of text rows that can be entered.","title":"MultilineTextFormField"},{"location":"php/api/form_builder/form_fields/#multipleselectionformfield","text":"MultipleSelectionFormField is a form fields that allows the selection of multiple options out of a predefined list of available options. The class implements IAttributeFormField , ICssClassFormField , IFilterableSelectionFormField , IImmutableFormField , and INullableFormField . If the field is nullable and no option is selected, null is returned as the save value.","title":"MultipleSelectionFormField"},{"location":"php/api/form_builder/form_fields/#radiobuttonformfield","text":"RadioButtonFormField is a form fields that allows the selection of a single option out of a predefined list of available options using radiobuttons. The class implements IAttributeFormField , ICssClassFormField , IImmutableFormField , and ISelectionFormField .","title":"RadioButtonFormField"},{"location":"php/api/form_builder/form_fields/#ratingformfield","text":"RatingFormField is a form field to set a rating for an object. The class implements IImmutableFormField , IMaximumFormField , IMinimumFormField , and INullableFormField . Form fields of this class have rating as their default id, wcf.form.field.rating as their default label, 1 as their default minimum, and 5 as their default maximum. For this field, the minimum and maximum refer to the minimum and maximum rating an object can get. When the field is shown, there will be maximum() - minimum() + 1 icons be shown with additional CSS classes that can be set and gotten via defaultCssClasses(array $cssClasses) and getDefaultCssClasses() . If a rating values is set, the first getValue() icons will instead use the classes that can be set and gotten via activeCssClasses(array $cssClasses) and getActiveCssClasses() . By default, the only default class is fa-star-o and the active classes are fa-star and orange .","title":"RatingFormField"},{"location":"php/api/form_builder/form_fields/#showorderformfield","text":"ShowOrderFormField is a single selection form field for which the selected value determines the position at which an object is shown. The show order field provides a list of all siblings and the object will be positioned after the selected sibling. To insert objects at the very beginning, the options() automatically method prepends an additional option for that case so that only the existing siblings need to be passed. The default id of instances of this class is showOrder and their default label is wcf.form.field.showOrder . It is important that the relevant object property is always kept updated. Whenever a new object is added or an existing object is edited or delete, the values of the other objects have to be adjusted to ensure consecutive numbering.","title":"ShowOrderFormField"},{"location":"php/api/form_builder/form_fields/#singleselectionformfield","text":"SingleSelectionFormField is a form fields that allows the selection of a single option out of a predefined list of available options. The class implements ICssClassFormField , IFilterableSelectionFormField , IImmutableFormField , and INullableFormField . If the field is nullable and the current form field value is considered empty by PHP, null is returned as the save value.","title":"SingleSelectionFormField"},{"location":"php/api/form_builder/form_fields/#sortorderformfield","text":"SingleSelectionFormField is a single selection form field with default id sortOrder , default label wcf.global.showOrder and default options ASC: wcf.global.sortOrder.ascending and DESC: wcf.global.sortOrder.descending .","title":"SortOrderFormField"},{"location":"php/api/form_builder/form_fields/#textformfield","text":"TextFormField is a form field that allows entering a single line of text. The class implements IAttributeFormField , IAutoCompleteFormField , ICssClassFormField , IImmutableFormField , II18nFormField , IInputModeFormField , IMaximumLengthFormField , IMinimumLengthFormField , IPatternFormField , and IPlaceholderFormField .","title":"TextFormField"},{"location":"php/api/form_builder/form_fields/#titleformfield","text":"TitleFormField is a text form field with title as the default id and wcf.global.title as the default label.","title":"TitleFormField"},{"location":"php/api/form_builder/form_fields/#urlformfield","text":"UrlFormField is a text form field whose values are checked via Url::is() .","title":"UrlFormField"},{"location":"php/api/form_builder/form_fields/#specific-fields","text":"The following form fields are reusable fields that generally are bound to a certain API or DatabaseObject implementation.","title":"Specific Fields"},{"location":"php/api/form_builder/form_fields/#aclformfield","text":"AclFormField is used for setting up acl values for specific objects. The class implements IObjectTypeFormField and requires an object type of the object type definition com.woltlab.wcf.acl . Additionally, the class provides the methods categoryName($categoryName) and getCategoryName() that allow setting a specific name or filter for the acl option categories whose acl options are shown. A category name of null signals that no category filter is used. Since version 5.5, the category name also supports filtering using a wildcard like user.* , see WoltLab/WCF#4355 . AclFormField objects register a custom form field data processor to add the relevant ACL object type id into the $parameters array directly using {$objectProperty}_aclObjectTypeID as the array key. The relevant database object action method is expected, based on the given ACL object type id, to save the ACL option values appropriately.","title":"AclFormField"},{"location":"php/api/form_builder/form_fields/#buttonformfield","text":"Only available since version 5.4. ButtonFormField shows a submit button as part of the form. The class implements IAttributeFormField and ICssClassFormField . Specifically for this form field, there is the IsNotClickedFormFieldDependency dependency with which certain parts of the form will only be processed if the relevent button has not clicked.","title":"ButtonFormField"},{"location":"php/api/form_builder/form_fields/#captchaformfield","text":"CaptchaFormField is used to add captcha protection to the form. You must specify a captcha object type ( com.woltlab.wcf.captcha ) using the objectType() method.","title":"CaptchaFormField"},{"location":"php/api/form_builder/form_fields/#colorformfield","text":"Only available since version 5.5. ColorFormField is used to specify RGBA colors using the rgba(r, g, b, a) format. The class implements IImmutableFormField .","title":"ColorFormField"},{"location":"php/api/form_builder/form_fields/#contentlanguageformfield","text":"ContentLanguageFormField is used to select the content language of an object. Fields of this class are only available if multilingualism is enabled and if there are content languages. The class implements IImmutableFormField .","title":"ContentLanguageFormField"},{"location":"php/api/form_builder/form_fields/#labelformfield","text":"LabelFormField is used to select a label from a specific label group. The class implements IObjectTypeFormNode . The labelGroup(ViewableLabelGroup $labelGroup) and getLabelGroup() methods are specific to this form field class and can be used to set and get the label group whose labels can be selected. Additionally, there is the static method createFields($objectType, array $labelGroups, $objectProperty = 'labelIDs) that can be used to create all relevant label form fields for a given list of label groups. In most cases, LabelFormField::createFields() should be used.","title":"LabelFormField"},{"location":"php/api/form_builder/form_fields/#optionformfield","text":"OptionFormField is an item list form field to set a list of options. The class implements IPackagesFormField and only options of the set packages are considered available. The default label of instances of this class is wcf.form.field.option and their default id is options .","title":"OptionFormField"},{"location":"php/api/form_builder/form_fields/#simpleaclformfield","text":"SimpleAclFormField is used for setting up simple acl values (one yes / no option per user and user group) for specific objects. SimpleAclFormField objects register a custom form field data processor to add the relevant simple ACL data array into the $parameters array directly using the object property as the array key. Since version 5.5, the field also supports inverted permissions, see WoltLab/WCF#4570 . The SimpleAclFormField supports inverted permissions, allowing the administrator to grant access to all non-selected users and groups. If this behavior is desired, it needs to be enabled by calling supportInvertedPermissions . An invertPermissions key containing a boolean value with the users selection will be provided together with the ACL values when saving the field.","title":"SimpleAclFormField"},{"location":"php/api/form_builder/form_fields/#singlemediaselectionformfield","text":"SingleMediaSelectionFormField is used to select a specific media file. The class implements IImmutableFormField . The following methods are specific to this form field class: imageOnly($imageOnly = true) and isImageOnly() can be used to set and check if only images may be selected. getMedia() returns the media file based on the current field value if a field is set.","title":"SingleMediaSelectionFormField"},{"location":"php/api/form_builder/form_fields/#tagformfield","text":"TagFormField is a form field to enter tags. The class implements IAttributeFormField and IObjectTypeFormNode . Arrays passed to TagFormField::values() can contain tag names as strings and Tag objects. The default label of instances of this class is wcf.tagging.tags and their default description is wcf.tagging.tags.description . TagFormField objects register a custom form field data processor to add the array with entered tag names into the $parameters array directly using the object property as the array key.","title":"TagFormField"},{"location":"php/api/form_builder/form_fields/#uploadformfield","text":"UploadFormField is a form field that allows uploading files by the user. UploadFormField objects register a custom form field data processor to add the array of wcf\\system\\file\\upload\\UploadFile\\UploadFile into the $parameters array directly using the object property as the array key. Also it registers the removed files as an array of wcf\\system\\file\\upload\\UploadFile\\UploadFile into the $parameters array directly using the object property with the suffix _removedFiles as the array key. The field supports additional settings: - imageOnly($imageOnly = true) and isImageOnly() can be used to ensure that the uploaded files are only images. - allowSvgImage($allowSvgImages = true) and svgImageAllowed() can be used to allow SVG images, if the image only mode is enabled (otherwise, the method will throw an exception). By default, SVG images are not allowed.","title":"UploadFormField"},{"location":"php/api/form_builder/form_fields/#provide-value-from-database-object","text":"To provide values from a database object, you should implement the method get{$objectProperty}UploadFileLocations() to your database object class. This method must return an array of strings with the locations of the files.","title":"Provide value from database object"},{"location":"php/api/form_builder/form_fields/#process-files","text":"To process files in the database object action class, you must rename the file to the final destination. You get the temporary location, by calling the method getLocation() on the given UploadFile objects. After that, you call setProcessed($location) with $location contains the new file location. This method sets the isProcessed flag to true and saves the new location. For updating files, it is relevant, whether a given file is already processed or not. For this case, the UploadFile object has an method isProcessed() which indicates, whether a file is already processed or new uploaded.","title":"Process files"},{"location":"php/api/form_builder/form_fields/#userformfield","text":"UserFormField is a form field to enter existing users. The class implements IAutoCompleteFormField , IAutoFocusFormField , IImmutableFormField , IMultipleFormField , and INullableFormField . While the user is presented the names of the specified users in the user interface, the field returns the ids of the users as data. The relevant UserProfile objects can be accessed via the getUsers() method.","title":"UserFormField"},{"location":"php/api/form_builder/form_fields/#userpasswordfield","text":"Only available since version 5.4. UserPasswordField is a form field for users' to enter their current password. The class implements IAttributeFormField , IAttributeFormField , IAutoCompleteFormField , IAutoFocusFormField , and IPlaceholderFormField","title":"UserPasswordField"},{"location":"php/api/form_builder/form_fields/#usergroupoptionformfield","text":"UserGroupOptionFormField is an item list form field to set a list of user group options/permissions. The class implements IPackagesFormField and only user group options of the set packages are considered available. The default label of instances of this class is wcf.form.field.userGroupOption and their default id is permissions .","title":"UserGroupOptionFormField"},{"location":"php/api/form_builder/form_fields/#usernameformfield","text":"UsernameFormField is used for entering one non-existing username. The class implements IAttributeFormField , IImmutableFormField , IMaximumLengthFormField , IMinimumLengthFormField , INullableFormField , and IPlaceholderFormField . As usernames have a system-wide restriction of a minimum length of 3 and a maximum length of 100 characters, these values are also used as the default value for the field\u2019s minimum and maximum length.","title":"UsernameFormField"},{"location":"php/api/form_builder/form_fields/#wysiwyg-form-container","text":"To integrate a wysiwyg editor into a form, you have to create a WysiwygFormContainer object. This container takes care of creating all necessary form nodes listed below for a wysiwyg editor. When creating the container object, its id has to be the id of the form field that will manage the actual text. The following methods are specific to this form container class: addSettingsNode(IFormChildNode $settingsNode) and addSettingsNodes(array $settingsNodes) can be used to add nodes to the settings tab container. attachmentData($objectType, $parentObjectID) can be used to set the data relevant for attachment support. By default, not attachment data is set, thus attachments are not supported. getAttachmentField() , getPollContainer() , getSettingsContainer() , getSmiliesContainer() , and getWysiwygField() can be used to get the different components of the wysiwyg form container once the form has been built. enablePreviewButton($enablePreviewButton) can be used to set whether the preview button for the message is shown or not. By default, the preview button is shown. This method is only relevant before the form is built. Afterwards, the preview button availability can not be changed. Only available since WoltLab Suite Core 5.3. getObjectId() returns the id of the edited object or 0 if no object is edited. getPreselect() , preselect($preselect) can be used to set the value of the wysiwyg tab menu's data-preselect attribute used to determine which tab is preselected. By default, the preselect is 'true' which is used to pre-select the first tab. messageObjectType($messageObjectType) can be used to set the message object type. pollObjectType($pollObjectType) can be used to set the poll object type. By default, no poll object type is set, thus the poll form field container is not available. supportMentions($supportMentions) can be used to set if mentions are supported. By default, mentions are not supported. This method is only relevant before the form is built. Afterwards, mention support can only be changed via the wysiwyg form field. supportSmilies($supportSmilies) can be used to set if smilies are supported. By default, smilies are supported. This method is only relevant before the form is built. Afterwards, smiley availability can only be changed via changing the availability of the smilies form container.","title":"Wysiwyg form container"},{"location":"php/api/form_builder/form_fields/#wysiwygattachmentformfield","text":"WysiwygAttachmentFormField provides attachment support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . The methods attachmentHandler(AttachmentHandler $attachmentHandler) and getAttachmentHandler() can be used to set and get the AttachmentHandler object that is used for uploaded attachments.","title":"WysiwygAttachmentFormField"},{"location":"php/api/form_builder/form_fields/#wysiwygpollformcontainer","text":"WysiwygPollFormContainer provides poll support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . WysiwygPollFormContainer contains all form fields that are required to create polls and requires edited objects to implement IPollContainer . The following methods are specific to this form container class: getEndTimeField() returns the form field to set the end time of the poll once the form has been built. getIsChangeableField() returns the form field to set if poll votes can be changed once the form has been built. getIsPublicField() returns the form field to set if poll results are public once the form has been built. getMaxVotesField() returns the form field to set the maximum number of votes once the form has been built. getOptionsField() returns the form field to set the poll options once the form has been built. getQuestionField() returns the form field to set the poll question once the form has been built. getResultsRequireVoteField() returns the form field to set if viewing the poll results requires voting once the form has been built. getSortByVotesField() returns the form field to set if the results are sorted by votes once the form has been built.","title":"WysiwygPollFormContainer"},{"location":"php/api/form_builder/form_fields/#wysiwygsmileyformcontainer","text":"WysiwygSmileyFormContainer provides smiley support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . WysiwygSmileyFormContainer creates a sub-tab for each smiley category.","title":"WysiwygSmileyFormContainer"},{"location":"php/api/form_builder/form_fields/#wysiwygsmileyformnode","text":"WysiwygSmileyFormNode is contains the smilies of a specific category. This class should not be used directly but only via WysiwygSmileyFormContainer .","title":"WysiwygSmileyFormNode"},{"location":"php/api/form_builder/form_fields/#example","text":"The following code creates a WYSIWYG editor component for a message object property. As smilies are supported by default and an attachment object type is given, the tab menu below the editor has two tabs: \u201cSmilies\u201d and \u201cAttachments\u201d. Additionally, mentions and quotes are supported. 1 2 3 4 5 6 WysiwygFormContainer :: create ( 'message' ) -> label ( 'foo.bar.message' ) -> messageObjectType ( 'com.example.foo.bar' ) -> attachmentData ( 'com.example.foo.bar' ) -> supportMentions () -> supportQuotes ()","title":"Example"},{"location":"php/api/form_builder/form_fields/#wysiwygformfield","text":"WysiwygFormField is used for wysiwyg editor form fields. This class should, in general, not be used directly but only via WysiwygFormContainer . The class implements IAttributeFormField , IMaximumLengthFormField , IMinimumLengthFormField , and IObjectTypeFormNode and requires an object type of the object type definition com.woltlab.wcf.message . The following methods are specific to this form field class: autosaveId($autosaveId) and getAutosaveId() can be used enable automatically saving the current editor contents in the browser using the given id. An empty string signals that autosaving is disabled. lastEditTime($lastEditTime) and getLastEditTime() can be used to set the last time the contents have been edited and saved so that the JavaScript can determine if the contents stored in the browser are older or newer. 0 signals that no last edit time has been set. supportAttachments($supportAttachments) and supportsAttachments() can be used to set and check if the form field supports attachments. It is not sufficient to simply signal attachment support via these methods for attachments to work. These methods are relevant internally to signal the Javascript code that the editor supports attachments. Actual attachment support is provided by WysiwygAttachmentFormField . supportMentions($supportMentions) and supportsMentions() can be used to set and check if the form field supports mentions of other users. WysiwygFormField objects register a custom form field data processor to add the relevant simple ACL data array into the $parameters array directly using the object property as the array key.","title":"WysiwygFormField"},{"location":"php/api/form_builder/form_fields/#twysiwygformnode","text":"All form nodes that need to know the id of the WysiwygFormField field should use TWysiwygFormNode . This trait provides getWysiwygId() and wysiwygId($wysiwygId) to get and set the relevant wysiwyg editor id.","title":"TWysiwygFormNode"},{"location":"php/api/form_builder/form_fields/#application-specific-form-fields","text":"","title":"Application-Specific Form Fields"},{"location":"php/api/form_builder/form_fields/#woltlab-suite-forum","text":"","title":"WoltLab Suite Forum"},{"location":"php/api/form_builder/form_fields/#multipleboardselectionformfield","text":"Only available since version 5.5. MultipleBoardSelectionFormField is used to select multiple forums. The class implements IAttributeFormField , ICssClassFormField , and IImmutableFormField . The field supports additional settings: boardNodeList(BoardNodeList $boardNodeList): self and getBoardNodeList(): BoardNodeList are used to set and get the list of board nodes used to render the board selection. boardNodeList(BoardNodeList $boardNodeList): self will automatically call readNodeTree() on the given board node list. categoriesSelectable(bool $categoriesSelectable = true): self and areCategoriesSelectable(): bool are used to set and check if the categories in the board node list are selectable. By default, categories are selectable. This option is useful if only actual boards, in which threads can be posted, should be selectable but the categories must still be shown so that the overall forum structure is still properly shown. supportExternalLinks(bool $supportExternalLinks): self and supportsExternalLinks(): bool are used to set and check if external links will be shown in the selection list. By default, external links are shown. Like in the example given before, in cases where only actual boards, in which threads can be posted, are relevant, this option allows to exclude external links.","title":"MultipleBoardSelectionFormField"},{"location":"php/api/form_builder/form_fields/#single-use-form-fields","text":"The following form fields are specific for certain forms and hardly reusable in other contexts.","title":"Single-Use Form Fields"},{"location":"php/api/form_builder/form_fields/#bbcodeattributesformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the attributes of a BBCode.","title":"BBCodeAttributesFormField"},{"location":"php/api/form_builder/form_fields/#devtoolsprojectexcludedpackagesformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the excluded packages of a devtools project.","title":"DevtoolsProjectExcludedPackagesFormField"},{"location":"php/api/form_builder/form_fields/#devtoolsprojectinstructionsformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the installation and update instructions of a devtools project.","title":"DevtoolsProjectInstructionsFormField"},{"location":"php/api/form_builder/form_fields/#devtoolsprojectoptionalpackagesformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the optional packages of a devtools project.","title":"DevtoolsProjectOptionalPackagesFormField"},{"location":"php/api/form_builder/form_fields/#devtoolsprojectrequiredpackagesformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the required packages of a devtools project.","title":"DevtoolsProjectRequiredPackagesFormField"},{"location":"php/api/form_builder/overview/","text":"Form Builder # WoltLab Suite includes a powerful way of creating forms: Form Builder. Form builder allows you to easily define all the fields and their constraints and interdependencies within PHP with full IDE support. It will then automatically generate the necessary HTML with full interactivity to render all the fields and also validate the fields\u2019 contents upon submission. The migration guide for WoltLab Suite Core 5.2 provides some examples of how to migrate existing forms to form builder that can also help in understanding form builder if the old way of creating forms is familiar. Form Builder Components # Form builder consists of several components that are presented on the following pages: Structure of form builder Form validation and form data Form node dependencies In general, form builder provides default implementation of interfaces by providing either abstract classes or traits. It is expected that the interfaces are always implemented using these abstract classes and traits! This way, if new methods are added to the interfaces, default implementations can be provided by the abstract classes and traits without causing backwards compatibility problems. AbstractFormBuilderForm # To make using form builder easier, AbstractFormBuilderForm extends AbstractForm and provides most of the code needed to set up a form (of course without specific fields, those have to be added by the concrete form class), like reading and validating form values and using a database object action to use the form data to create or update a database object. In addition to the existing methods inherited by AbstractForm , AbstractFormBuilderForm provides the following methods: buildForm() builds the form in the following steps: Call AbtractFormBuilderForm::createForm() to create the IFormDocument object and add the form fields. Call IFormDocument::build() to build the form. Call AbtractFormBuilderForm::finalizeForm() to finalize the form like adding dependencies. Additionally, between steps 1 and 2 and after step 3, the method provides two events, createForm and buildForm to allow plugins to register event listeners to execute additional code at the right point in time. - createForm() creates the FormDocument object and sets the form mode. Classes extending AbstractFormBuilderForm have to override this method (and call parent::createForm() as the first line in the overridden method) to add concrete form containers and form fields to the bare form document. - finalizeForm() is called after the form has been built and the complete form hierarchy has been established. This method should be overridden to add dependencies, for example. - setFormAction() is called at the end of readData() and sets the form document\u2019s action based on the controller class name and whether an object is currently edited. - If an object is edited, at the beginning of readData() , setFormObjectData() is called which calls IFormDocument::loadValuesFromObject() . If values need to be loaded from additional sources, this method should be used for that. AbstractFormBuilderForm also provides the following (public) properties: $form contains the IFormDocument object created in createForm() . $formAction is either create (default) or edit and handles which method of the database object is called by default ( create is called for $formAction = 'create' and update is called for $formAction = 'edit' ) and is used to set the value of the action template variable. $formObject contains the IStorableObject if the form is used to edit an existing object. For forms used to create objects, $formObject is always null . Edit forms have to manually identify the edited object based on the request data and set the value of $formObject . $objectActionName can be used to set an alternative action to be executed by the database object action that deviates from the default action determined by the value of $formAction . $objectActionClass is the name of the database object action class that is used to create or update the database object. DialogFormDocument # Form builder forms can also be used in dialogs. For such forms, DialogFormDocument should be used which provides the additional methods cancelable($cancelable = true) and isCancelable() to set and check if the dialog can be canceled. If a dialog form can be canceled, a cancel button is added. If the dialog form is fetched via an AJAX request, IFormDocument::ajax() has to be called. AJAX forms are registered with WoltLabSuite/Core/Form/Builder/Manager which also supports getting all of the data of a form via the getData(formId) function. The getData() function relies on all form fields creating and registering a WoltLabSuite/Core/Form/Builder/Field/Field object that provides the data of a specific field. To make it as easy as possible to work with AJAX forms in dialogs, WoltLabSuite/Core/Form/Builder/Dialog (abbreviated as FormBuilderDialog from now on) should generally be used instead of WoltLabSuite/Core/Form/Builder/Manager directly. The constructor of FormBuilderDialog expects the following parameters: dialogId : id of the dialog element className : PHP class used to get the form dialog (and save the data if options.submitActionName is set) actionName : name of the action/method of className that returns the dialog; the method is expected to return an array with formId containg the id of the returned form and dialog containing the rendered form dialog options : additional options: actionParameters (default: empty): additional parameters sent during AJAX requests destroyOnClose (default: false ): if true , whenever the dialog is closed, the form is destroyed so that a new form is fetched if the dialog is opened again dialog : additional dialog options used as options during dialog setup onSubmit : callback when the form is submitted (takes precedence over submitActionName ) submitActionName (default: not set): name of the action/method of className called when the form is submitted The three public functions of FormBuilderDialog are: destroy() destroys the dialog, the form, and all of the form fields. getData() returns a Promise that returns the form data. open() opens the dialog. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 require ([ 'WoltLabSuite/Core/Form/Builder/Dialog' ], function ( FormBuilderDialog ) { var dialog = new FormBuilderDialog ( 'testDialog' , 'wcf\\\\data\\\\test\\\\TestAction' , 'getDialog' , { destroyOnClose : true , dialog : { title : 'Test Dialog' }, submitActionName : 'saveDialog' } ); elById ( 'testDialogButton' ). addEventListener ( 'click' , function () { dialog . open (); }); });","title":"Overview"},{"location":"php/api/form_builder/overview/#form-builder","text":"WoltLab Suite includes a powerful way of creating forms: Form Builder. Form builder allows you to easily define all the fields and their constraints and interdependencies within PHP with full IDE support. It will then automatically generate the necessary HTML with full interactivity to render all the fields and also validate the fields\u2019 contents upon submission. The migration guide for WoltLab Suite Core 5.2 provides some examples of how to migrate existing forms to form builder that can also help in understanding form builder if the old way of creating forms is familiar.","title":"Form Builder"},{"location":"php/api/form_builder/overview/#form-builder-components","text":"Form builder consists of several components that are presented on the following pages: Structure of form builder Form validation and form data Form node dependencies In general, form builder provides default implementation of interfaces by providing either abstract classes or traits. It is expected that the interfaces are always implemented using these abstract classes and traits! This way, if new methods are added to the interfaces, default implementations can be provided by the abstract classes and traits without causing backwards compatibility problems.","title":"Form Builder Components"},{"location":"php/api/form_builder/overview/#abstractformbuilderform","text":"To make using form builder easier, AbstractFormBuilderForm extends AbstractForm and provides most of the code needed to set up a form (of course without specific fields, those have to be added by the concrete form class), like reading and validating form values and using a database object action to use the form data to create or update a database object. In addition to the existing methods inherited by AbstractForm , AbstractFormBuilderForm provides the following methods: buildForm() builds the form in the following steps: Call AbtractFormBuilderForm::createForm() to create the IFormDocument object and add the form fields. Call IFormDocument::build() to build the form. Call AbtractFormBuilderForm::finalizeForm() to finalize the form like adding dependencies. Additionally, between steps 1 and 2 and after step 3, the method provides two events, createForm and buildForm to allow plugins to register event listeners to execute additional code at the right point in time. - createForm() creates the FormDocument object and sets the form mode. Classes extending AbstractFormBuilderForm have to override this method (and call parent::createForm() as the first line in the overridden method) to add concrete form containers and form fields to the bare form document. - finalizeForm() is called after the form has been built and the complete form hierarchy has been established. This method should be overridden to add dependencies, for example. - setFormAction() is called at the end of readData() and sets the form document\u2019s action based on the controller class name and whether an object is currently edited. - If an object is edited, at the beginning of readData() , setFormObjectData() is called which calls IFormDocument::loadValuesFromObject() . If values need to be loaded from additional sources, this method should be used for that. AbstractFormBuilderForm also provides the following (public) properties: $form contains the IFormDocument object created in createForm() . $formAction is either create (default) or edit and handles which method of the database object is called by default ( create is called for $formAction = 'create' and update is called for $formAction = 'edit' ) and is used to set the value of the action template variable. $formObject contains the IStorableObject if the form is used to edit an existing object. For forms used to create objects, $formObject is always null . Edit forms have to manually identify the edited object based on the request data and set the value of $formObject . $objectActionName can be used to set an alternative action to be executed by the database object action that deviates from the default action determined by the value of $formAction . $objectActionClass is the name of the database object action class that is used to create or update the database object.","title":"AbstractFormBuilderForm"},{"location":"php/api/form_builder/overview/#dialogformdocument","text":"Form builder forms can also be used in dialogs. For such forms, DialogFormDocument should be used which provides the additional methods cancelable($cancelable = true) and isCancelable() to set and check if the dialog can be canceled. If a dialog form can be canceled, a cancel button is added. If the dialog form is fetched via an AJAX request, IFormDocument::ajax() has to be called. AJAX forms are registered with WoltLabSuite/Core/Form/Builder/Manager which also supports getting all of the data of a form via the getData(formId) function. The getData() function relies on all form fields creating and registering a WoltLabSuite/Core/Form/Builder/Field/Field object that provides the data of a specific field. To make it as easy as possible to work with AJAX forms in dialogs, WoltLabSuite/Core/Form/Builder/Dialog (abbreviated as FormBuilderDialog from now on) should generally be used instead of WoltLabSuite/Core/Form/Builder/Manager directly. The constructor of FormBuilderDialog expects the following parameters: dialogId : id of the dialog element className : PHP class used to get the form dialog (and save the data if options.submitActionName is set) actionName : name of the action/method of className that returns the dialog; the method is expected to return an array with formId containg the id of the returned form and dialog containing the rendered form dialog options : additional options: actionParameters (default: empty): additional parameters sent during AJAX requests destroyOnClose (default: false ): if true , whenever the dialog is closed, the form is destroyed so that a new form is fetched if the dialog is opened again dialog : additional dialog options used as options during dialog setup onSubmit : callback when the form is submitted (takes precedence over submitActionName ) submitActionName (default: not set): name of the action/method of className called when the form is submitted The three public functions of FormBuilderDialog are: destroy() destroys the dialog, the form, and all of the form fields. getData() returns a Promise that returns the form data. open() opens the dialog. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 require ([ 'WoltLabSuite/Core/Form/Builder/Dialog' ], function ( FormBuilderDialog ) { var dialog = new FormBuilderDialog ( 'testDialog' , 'wcf\\\\data\\\\test\\\\TestAction' , 'getDialog' , { destroyOnClose : true , dialog : { title : 'Test Dialog' }, submitActionName : 'saveDialog' } ); elById ( 'testDialogButton' ). addEventListener ( 'click' , function () { dialog . open (); }); });","title":"DialogFormDocument"},{"location":"php/api/form_builder/structure/","text":"Structure of Form Builder # Forms built with form builder consist of three major structural elements listed from top to bottom: form document, form container, form field. The basis for all three elements are form nodes. The form builder API uses fluent interfaces heavily, meaning that unless a method is a getter, it generally returns the objects itself to support method chaining. Form Nodes # IFormNode is the base interface that any node of a form has to implement. IFormChildNode extends IFormNode for such elements of a form that can be a child node to a parent node. IFormParentNode extends IFormNode for such elements of a form that can be a parent to child nodes. IFormElement extends IFormNode for such elements of a form that can have a description and a label. IFormNode # IFormNode is the base interface that any node of a form has to implement and it requires the following methods: addClass($class) , addClasses(array $classes) , removeClass($class) , getClasses() , and hasClass($class) add, remove, get, and check for CSS classes of the HTML element representing the form node. If the form node consists of multiple (nested) HTML elements, the classes are generally added to the top element. static validateClass($class) is used to check if a given CSS class is valid. By default, a form node has no CSS classes. addDependency(IFormFieldDependency $dependency) , removeDependency($dependencyId) , getDependencies() , and hasDependency($dependencyId) add, remove, get, and check for dependencies of this form node on other form fields. checkDependencies() checks if all of the node\u2019s dependencies are met and returns a boolean value reflecting the check\u2019s result. The form builder dependency documentation provides more detailed information about dependencies and how they work. By default, a form node has no dependencies. attribute($name, $value = null) , removeAttribute($name) , getAttribute($name) , getAttributes() , hasAttribute($name) add, remove, get, and check for attributes of the HTML element represting the form node. The attributes are added to the same element that the CSS classes are added to. static validateAttribute($name) is used to check if a given attribute is valid. By default, a form node has no attributes. available($available = true) and isAvailable() can be used to set and check if the node is available. The availability functionality can be used to easily toggle form nodes based, for example, on options without having to create a condition to append the relevant. This way of checking availability makes it easier to set up forms. By default, every form node is available. The following aspects are important when working with availability: Unavailable fields produce no output, their value is not read, they are not validated and they are not checked for save values. Form fields are also able to mark themselves as unavailable, for example, a selection field without any options. Form containers are automatically unavailable if they contain no available children. Availability sets the static availability for form nodes that does not change during the lifetime of a form. In contrast, dependencies represent a dynamic availability for form nodes that depends on the current value of certain form fields. - cleanup() is called after the whole form is not used anymore to reset other APIs if the form fields depends on them and they expect such a reset. This method is not intended to clean up the form field\u2019s value as a new form document object is created to show a clean form. - getDocument() returns the IFormDocument object the node belongs to. (As IFormDocument extends IFormNode , form document objects simply return themselves.) - getHtml() returns the HTML representation of the node. getHtmlVariables() return template variables (in addition to the form node itself) to render the node\u2019s HTML representation. - id($id) and getId() set and get the id of the form node. Every id has to be unique within a form. getPrefixedId() returns the prefixed version of the node\u2019s id (see IFormDocument::getPrefix() and IFormDocument::prefix() ). static validateId($id) is used to check if a given id is valid. - populate() is called by IFormDocument::build() after all form nodes have been added. This method should finilize the initialization of the form node after all parent-child relations of the form document have been established. This method is needed because during the construction of a form node, it neither knows the form document it will belong to nor does it know its parent. - validate() checks, after the form is submitted, if the form node is valid. A form node with children is valid if all of its child nodes are valid. A form field is valid if its value is valid. - static create($id) is the factory method that has to be used to create new form nodes with the given id. TFormNode provides a default implementation of most of these methods. IFormChildNode # IFormChildNode extends IFormNode for such elements of a form that can be a child node to a parent node and it requires the parent(IFormParentNode $parentNode) and getParent() methods used to set and get the node\u2019s parent node. TFormChildNode provides a default implementation of these two methods and also of IFormNode::getDocument() . IFormParentNode # IFormParentNode extends IFormNode for such elements of a form that can be a parent to child nodes. Additionally, the interface also extends \\Countable and \\RecursiveIterator . The interface requires the following methods: appendChild(IFormChildNode $child) , appendChildren(array $children) , insertAfter(IFormChildNode $child, $referenceNodeId) , and insertBefore(IFormChildNode $child, $referenceNodeId) are used to insert new children either at the end or at specific positions. validateChild(IFormChildNode $child) is used to check if a given child node can be added. A child node cannot be added if it would cause an id to be used twice. children() returns the direct children of a form node. getIterator() return a recursive iterator for a form node. getNodeById($nodeId) returns the node with the given id by searching for it in the node\u2019s children and recursively in all of their children. contains($nodeId) can be used to simply check if a node with the given id exists. hasValidationErrors() checks if a form node or any of its children has a validation error (see IFormField::getValidationErrors() ). readValues() recursively calls IFormParentNode::readValues() and IFormField::readValue() on its children. IFormElement # IFormElement extends IFormNode for such elements of a form that can have a description and a label and it requires the following methods: label($languageItem = null, array $variables = []) and getLabel() can be used to set and get the label of the form element. requiresLabel() can be checked if the form element requires a label. A label-less form element that requires a label will prevent the form from being rendered by throwing an exception. description($languageItem = null, array $variables = []) and getDescription() can be used to set and get the description of the form element. IObjectTypeFormNode # IObjectTypeFormField has to be implemented by form nodes that rely on a object type of a specific object type definition in order to function. The implementing class has to implement the methods objectType($objectType) , getObjectType() , and getObjectTypeDefinition() . TObjectTypeFormNode provides a default implementation of these three methods. CustomFormNode # CustomFormNode is a form node whose contents can be set directly via content($content) . This class should generally not be relied on. Instead, TemplateFormNode should be used. TemplateFormNode # TemplateFormNode is a form node whose contents are read from a template. TemplateFormNode has the following additional methods: application($application) and getApplicaton() can be used to set and get the abbreviation of the application the shown template belongs to. If no template has been set explicitly, getApplicaton() returns wcf . templateName($templateName) and getTemplateName() can be used to set and get the name of the template containing the node contents. If no template has been set and the node is rendered, an exception will be thrown. variables(array $variables) and getVariables() can be used to set and get additional variables passed to the template. Form Document # A form document object represents the form as a whole and has to implement the IFormDocument interface. WoltLab Suite provides a default implementation with the FormDocument class. IFormDocument should not be implemented directly but instead FormDocument should be extended to avoid issues if the IFormDocument interface changes in the future. IFormDocument extends IFormParentNode and requires the following additional methods: action($action) and getAction() can be used set and get the action attribute of the <form> HTML element. addButton(IFormButton $button) and getButtons() can be used add and get form buttons that are shown at the bottom of the form. addDefaultButton($addDefaultButton) and hasDefaultButton() can be used to set and check if the form has the default button which is added by default unless specified otherwise. Each implementing class may define its own default button. FormDocument has a button with id submitButton , label wcf.global.button.submit , access key s , and CSS class buttonPrimary as its default button. ajax($ajax) and isAjax() can be used to set and check if the form document is requested via an AJAX request or processes data via an AJAX request. These methods are helpful for form fields that behave differently when providing data via AJAX. build() has to be called once after all nodes have been added to this document to trigger IFormNode::populate() . formMode($formMode) and getFormMode() sets the form mode. Possible form modes are: IFormDocument::FORM_MODE_CREATE has to be used when the form is used to create a new object. IFormDocument::FORM_MODE_UPDATE has to be used when the form is used to edit an existing object. getData() returns the array containing the form data and which is passed as the $parameters argument of the constructor of a database object action object. getDataHandler() returns the data handler for this document that is used to process the field data into a parameters array for the constructor of a database object action object. getEnctype() returns the encoding type of the form. If the form contains a IFileFormField , multipart/form-data is returned, otherwise null is returned. loadValues(array $data, IStorableObject $object) is used when editing an existing object to set the form field values by calling IFormField::loadValue() for all form fields. Additionally, the form mode is set to IFormDocument::FORM_MODE_UPDATE . 5.4+ markRequiredFields(bool $markRequiredFields = true): self and marksRequiredFields(): bool can be used to set and check whether fields that are required are marked (with an asterisk in the label) in the output. method($method) and getMethod() can be used to set and get the method attribute of the <form> HTML element. By default, the method is post . prefix($prefix) and getPrefix() can be used to set and get a global form prefix that is prepended to form elements\u2019 names and ids to avoid conflicts with other forms. By default, the prefix is an empty string. If a prefix of foo is set, getPrefix() returns foo_ (additional trailing underscore). requestData(array $requestData) , getRequestData($index = null) , and hasRequestData($index = null) can be used to set, get and check for specific request data. In most cases, the relevant request data is the $_POST array. In default AJAX requests handled by database object actions, however, the request data generally is in AbstractDatabaseObjectAction::$parameters . By default, $_POST is the request data. The last aspect is relevant for DialogFormDocument objects. DialogFormDocument is a specialized class for forms in dialogs that, in contrast to FormDocument do not require an action to be set. Additionally, DialogFormDocument provides the cancelable($cancelable = true) and isCancelable() methods used to determine if the dialog from can be canceled. By default, dialog forms are cancelable. Form Button # A form button object represents a button shown at the end of the form that, for example, submits the form. Every form button has to implement the IFormButton interface that extends IFormChildNode and IFormElement . IFormButton requires four methods to be implemented: accessKey($accessKey) and getAccessKey() can be used to set and get the access key with which the form button can be activated. By default, form buttons have no access key set. submit($submitButton) and isSubmit() can be used to set and check if the form button is a submit button. A submit button is an input[type=submit] element. Otherwise, the button is a button element. Form Container # A form container object represents a container for other form containers or form field directly. Every form container has to implement the IFormContainer interface which requires the following method: loadValues(array $data, IStorableObject $object) is called by IFormDocument::loadValuesFromObject() to inform the container that object data is loaded. This method is not intended to generally call IFormField::loadValues() on its form field children as these methods are already called by IFormDocument::loadValuesFromObject() . This method is intended for specialized form containers with more complex logic. There are multiple default container implementations: FormContainer is the default implementation of IFormContainer . TabMenuFormContainer represents the container of tab menu, while TabFormContainer represents a tab of a tab menu and TabTabMenuFormContainer represents a tab of a tab menu that itself contains a tab menu. The children of RowFormContainer are shown in a row and should use col-* classes. The children of RowFormFieldContainer are also shown in a row but does not show the labels and descriptions of the individual form fields. Instead of the individual labels and descriptions, the container's label and description is shown and both span all of fields. SuffixFormFieldContainer can be used for one form field with a second selection form field used as a suffix. The methods of the interfaces that FormContainer is implementing are well documented, but here is a short overview of the most important methods when setting up a form or extending a form with an event listener: appendChild(IFormChildNode $child) , appendChildren(array $children) , and insertBefore(IFormChildNode $child, $referenceNodeId) are used to insert new children into the form container. description($languageItem = null, array $variables = []) and label($languageItem = null, array $variables = []) are used to set the description and the label or title of the form container. Form Field # A form field object represents a concrete form field that allows entering data. Every form field has to implement the IFormField interface which extends IFormChildNode and IFormElement . IFormField requires the following additional methods: addValidationError(IFormFieldValidationError $error) and getValidationErrors() can be used to get and set validation errors of the form field (see form validation ). addValidator(IFormFieldValidator $validator) , getValidators() , removeValidator($validatorId) , and hasValidator($validatorId) can be used to get, set, remove, and check for validators for the form field (see form validation ). getFieldHtml() returns the field's HTML output without the surrounding dl structure. objectProperty($objectProperty) and getObjectProperty() can be used to get and set the object property that the field represents. When setting the object property is set to an empty string, the previously set object property is unset. If no object property has been set, the field\u2019s (non-prefixed) id is returned. The object property allows having different fields (requiring different ids) that represent the same object property which is handy when available options of the field\u2019s value depend on another field. Having object property allows to define different fields for each value of the other field and to use form field dependencies to only show the appropriate field. - readValue() reads the form field value from the request data after the form is submitted. - required($required = true) and isRequired() can be used to determine if the form field has to be filled out. By default, form fields do not have to be filled out. - value($value) and getSaveValue() can be used to get and set the value of the form field to be used outside of the context of forms. getValue() , in contrast, returns the internal representation of the form field\u2019s value. In general, the internal representation is only relevant when validating the value in additional validators. loadValue(array $data, IStorableObject $object) extracts the form field value from the given data array (and additional, non-editable data from the object if the field needs them). AbstractFormField provides default implementations of many of the listed methods above and should be extended instead of implementing IFormField directly. An overview of the form fields provided by default can be found here . Form Field Interfaces and Traits # WoltLab Suite Core provides a variety of interfaces and matching traits with default implementations for several common features of form fields: IAttributeFormField # Only available since version 5.4. IAttributeFormField has to be implemented by form fields for which attributes can be added to the actual form element (in addition to adding attributes to the surrounding element via the attribute-related methods of IFormNode ). The implementing class has to implement the methods fieldAttribute(string $name, string $value = null): self and getFieldAttribute(string $name): self / getFieldAttributes(): array , which are used to add and get the attributes, respectively. Additionally, hasFieldAttribute(string $name): bool has to implemented to check if a certain attribute is present, removeFieldAttribute(string $name): self to remove an attribute, and static validateFieldAttribute(string $name) to check if the attribute is valid for this specific class. TAttributeFormField provides a default implementation of these methods and TInputAttributeFormField specializes the trait for input -based form fields. These two traits also ensure that if a specific interface that handles a specific attribute is implemented, like IAutoCompleteFormField handling autocomplete , this attribute cannot be set with this API. Instead, the dedicated API provided by the relevant interface has to be used. IAutoCompleteFormField # Only available since version 5.4. IAutoCompleteFormField has to be implemented by form fields that support the autocomplete attribute . The implementing class has to implement the methods autoComplete(?string $autoComplete): self and getAutoComplete(): ?string , which are used to set and get the autocomplete value, respectively. TAutoCompleteFormField provides a default implementation of these two methods and TTextAutoCompleteFormField specializes the trait for text form fields. When using TAutoCompleteFormField , you have to implement the getValidAutoCompleteTokens(): array method which returns all valid autocomplete tokens. IAutoFocusFormField # IAutoFocusFormField has to be implemented by form fields that can be auto-focused. The implementing class has to implement the methods autoFocus($autoFocus = true) and isAutoFocused() . By default, form fields are not auto-focused. TAutoFocusFormField provides a default implementation of these two methods. ICssClassFormField # Only available since version 5.4. ICssClassFormField has to be implemented by form fields for which CSS classes can be added to the actual form element (in addition to adding CSS classes to the surrounding element via the class-related methods of IFormNode ). The implementing class has to implement the methods addFieldClass(string $class): self / addFieldClasses(array $classes): self and getFieldClasses(): array , which are used to add and get the CSS classes, respectively. Additionally, hasFieldClass(string $class): bool has to implemented to check if a certain CSS class is present and removeFieldClass(string $class): self to remove a CSS class. TCssClassFormField provides a default implementation of these methods. IFileFormField # IFileFormField has to be implemented by every form field that uploads files so that the enctype attribute of the form document is multipart/form-data (see IFormDocument::getEnctype() ). IFilterableSelectionFormField # IFilterableSelectionFormField extends ISelectionFormField by the possibilty for users when selecting the value(s) to filter the list of available options. The implementing class has to implement the methods filterable($filterable = true) and isFilterable() . TFilterableSelectionFormField provides a default implementation of these two methods. II18nFormField # II18nFormField has to be implemented by form fields if the form field value can be entered separately for all available languages. The implementing class has to implement the following methods: i18n($i18n = true) and isI18n() can be used to set whether a specific instance of the class actually supports multilingual input. i18nRequired($i18nRequired = true) and isI18nRequired() can be used to set whether a specific instance of the class requires separate values for all languages. languageItemPattern($pattern) and getLanguageItemPattern() can be used to set the pattern/regular expression for the language item used to save the multilingual values. hasI18nValues() and hasPlainValue() check if the current value is a multilingual or monolingual value. TI18nFormField provides a default implementation of these eight methods and additional default implementations of some of the IFormField methods. If multilingual input is enabled for a specific form field, classes using TI18nFormField register a custom form field data processor to add the array with multilingual input into the $parameters array directly using {$objectProperty}_i18n as the array key. If multilingual input is enabled but only a monolingual value is entered, the custom form field data processor does nothing and the form field\u2019s value is added by the DefaultFormDataProcessor into the data sub-array of the $parameters array. TI18nFormField already provides a default implementation of IFormField::validate() . IImmutableFormField # IImmutableFormField has to be implemented by form fields that support being displayed but whose value cannot be changed. The implementing class has to implement the methods immutable($immutable = true) and isImmutable() that can be used to determine if the value of the form field is mutable or immutable. By default, form field are mutable. IInputModeFormField # Only available since version 5.4. IInputModeFormField has to be implemented by form fields that support the inputmode attribute . The implementing class has to implement the methods inputMode(?string $inputMode): self and getInputMode(): ?string , which are used to set and get the input mode, respectively. TInputModeFormField provides a default implementation of these two methods. IMaximumFormField # IMaximumFormField has to be implemented by form fields if the entered value must have a maximum value. The implementing class has to implement the methods maximum($maximum = null) and getMaximum() . A maximum of null signals that no maximum value has been set. TMaximumFormField provides a default implementation of these two methods. The implementing class has to validate the entered value against the maximum value manually. IMaximumLengthFormField # IMaximumLengthFormField has to be implemented by form fields if the entered value must have a maximum length. The implementing class has to implement the methods maximumLength($maximumLength = null) , getMaximumLength() , and validateMaximumLength($text, Language $language = null) . A maximum length of null signals that no maximum length has been set. TMaximumLengthFormField provides a default implementation of these two methods. The implementing class has to validate the entered value against the maximum value manually by calling validateMaximumLength() . IMinimumFormField # IMinimumFormField has to be implemented by form fields if the entered value must have a minimum value. The implementing class has to implement the methods minimum($minimum = null) and getMinimum() . A minimum of null signals that no minimum value has been set. TMinimumFormField provides a default implementation of these three methods. The implementing class has to validate the entered value against the minimum value manually. IMinimumLengthFormField # IMinimumLengthFormField has to be implemented by form fields if the entered value must have a minimum length. The implementing class has to implement the methods minimumLength($minimumLength = null) , getMinimumLength() , and validateMinimumLength($text, Language $language = null) . A minimum length of null signals that no minimum length has been set. TMinimumLengthFormField provides a default implementation of these three methods. The implementing class has to validate the entered value against the minimum value manually by calling validateMinimumLength() . IMultipleFormField # IMinimumLengthFormField has to be implemented by form fields that support selecting or setting multiple values. The implementing class has to implement the following methods: multiple($multiple = true) and allowsMultiple() can be used to set whether a specific instance of the class actually should support multiple values. By default, multiple values are not supported. minimumMultiples($minimum) and getMinimumMultiples() can be used to set the minimum number of values that have to be selected/entered. By default, there is no required minimum number of values. maximumMultiples($minimum) and getMaximumMultiples() can be used to set the maximum number of values that have to be selected/entered. By default, there is no maximum number of values. IMultipleFormField::NO_MAXIMUM_MULTIPLES is returned if no maximum number of values has been set and it can also be used to unset a previously set maximum number of values. TMultipleFormField provides a default implementation of these six methods and classes using TMultipleFormField register a custom form field data processor to add the HtmlInputProcessor object with the text into the $parameters array directly using {$objectProperty}_htmlInputProcessor as the array key. The implementing class has to validate the values against the minimum and maximum number of values manually. INullableFormField # INullableFormField has to be implemented by form fields that support null as their (empty) value. The implementing class has to implement the methods nullable($nullable = true) and isNullable() . TNullableFormField provides a default implementation of these two methods. null should be returned by IFormField::getSaveValue() is the field is considered empty and the form field has been set as nullable. IPackagesFormField # IPackagesFormField has to be implemented by form fields that, in some way, considers packages whose ids may be passed to the field object. The implementing class has to implement the methods packageIDs(array $packageIDs) and getPackageIDs() . TPackagesFormField provides a default implementation of these two methods. IPatternFormField # Only available since version 5.4. IPatternFormField has to be implemented by form fields that support the pattern attribute . The implementing class has to implement the methods pattern(?string $pattern): self and getPattern(): ?string , which are used to set and get the pattern, respectively. TPatternFormField provides a default implementation of these two methods. IPlaceholderFormField # IPlaceholderFormField has to be implemented by form fields that support a placeholder value for empty fields. The implementing class has to implement the methods placeholder($languageItem = null, array $variables = []) and getPlaceholder() . TPlaceholderFormField provides a default implementation of these two methods. ISelectionFormField # ISelectionFormField has to be implemented by form fields with a predefined set of possible values. The implementing class has to implement the getter and setter methods options($options, $nestedOptions = false, $labelLanguageItems = true) and getOptions() and additionally two methods related to nesting, i.e. whether the selectable options have a hierarchy: supportsNestedOptions() and getNestedOptions() . TSelectionFormField provides a default implementation of these four methods. ISuffixedFormField # ISuffixedFormField has to be implemented by form fields that support supports displaying a suffix behind the actual input field. The implementing class has to implement the methods suffix($languageItem = null, array $variables = []) and getSuffix() . TSuffixedFormField provides a default implementation of these two methods. TDefaultIdFormField # Form fields that have a default id have to use TDefaultIdFormField and have to implement the method getDefaultId() . Displaying Forms # The only thing to do in a template to display the whole form including all of the necessary JavaScript is to put 1 { @ $form -> getHtml () } into the template file at the relevant position.","title":"Structure"},{"location":"php/api/form_builder/structure/#structure-of-form-builder","text":"Forms built with form builder consist of three major structural elements listed from top to bottom: form document, form container, form field. The basis for all three elements are form nodes. The form builder API uses fluent interfaces heavily, meaning that unless a method is a getter, it generally returns the objects itself to support method chaining.","title":"Structure of Form Builder"},{"location":"php/api/form_builder/structure/#form-nodes","text":"IFormNode is the base interface that any node of a form has to implement. IFormChildNode extends IFormNode for such elements of a form that can be a child node to a parent node. IFormParentNode extends IFormNode for such elements of a form that can be a parent to child nodes. IFormElement extends IFormNode for such elements of a form that can have a description and a label.","title":"Form Nodes"},{"location":"php/api/form_builder/structure/#iformnode","text":"IFormNode is the base interface that any node of a form has to implement and it requires the following methods: addClass($class) , addClasses(array $classes) , removeClass($class) , getClasses() , and hasClass($class) add, remove, get, and check for CSS classes of the HTML element representing the form node. If the form node consists of multiple (nested) HTML elements, the classes are generally added to the top element. static validateClass($class) is used to check if a given CSS class is valid. By default, a form node has no CSS classes. addDependency(IFormFieldDependency $dependency) , removeDependency($dependencyId) , getDependencies() , and hasDependency($dependencyId) add, remove, get, and check for dependencies of this form node on other form fields. checkDependencies() checks if all of the node\u2019s dependencies are met and returns a boolean value reflecting the check\u2019s result. The form builder dependency documentation provides more detailed information about dependencies and how they work. By default, a form node has no dependencies. attribute($name, $value = null) , removeAttribute($name) , getAttribute($name) , getAttributes() , hasAttribute($name) add, remove, get, and check for attributes of the HTML element represting the form node. The attributes are added to the same element that the CSS classes are added to. static validateAttribute($name) is used to check if a given attribute is valid. By default, a form node has no attributes. available($available = true) and isAvailable() can be used to set and check if the node is available. The availability functionality can be used to easily toggle form nodes based, for example, on options without having to create a condition to append the relevant. This way of checking availability makes it easier to set up forms. By default, every form node is available. The following aspects are important when working with availability: Unavailable fields produce no output, their value is not read, they are not validated and they are not checked for save values. Form fields are also able to mark themselves as unavailable, for example, a selection field without any options. Form containers are automatically unavailable if they contain no available children. Availability sets the static availability for form nodes that does not change during the lifetime of a form. In contrast, dependencies represent a dynamic availability for form nodes that depends on the current value of certain form fields. - cleanup() is called after the whole form is not used anymore to reset other APIs if the form fields depends on them and they expect such a reset. This method is not intended to clean up the form field\u2019s value as a new form document object is created to show a clean form. - getDocument() returns the IFormDocument object the node belongs to. (As IFormDocument extends IFormNode , form document objects simply return themselves.) - getHtml() returns the HTML representation of the node. getHtmlVariables() return template variables (in addition to the form node itself) to render the node\u2019s HTML representation. - id($id) and getId() set and get the id of the form node. Every id has to be unique within a form. getPrefixedId() returns the prefixed version of the node\u2019s id (see IFormDocument::getPrefix() and IFormDocument::prefix() ). static validateId($id) is used to check if a given id is valid. - populate() is called by IFormDocument::build() after all form nodes have been added. This method should finilize the initialization of the form node after all parent-child relations of the form document have been established. This method is needed because during the construction of a form node, it neither knows the form document it will belong to nor does it know its parent. - validate() checks, after the form is submitted, if the form node is valid. A form node with children is valid if all of its child nodes are valid. A form field is valid if its value is valid. - static create($id) is the factory method that has to be used to create new form nodes with the given id. TFormNode provides a default implementation of most of these methods.","title":"IFormNode"},{"location":"php/api/form_builder/structure/#iformchildnode","text":"IFormChildNode extends IFormNode for such elements of a form that can be a child node to a parent node and it requires the parent(IFormParentNode $parentNode) and getParent() methods used to set and get the node\u2019s parent node. TFormChildNode provides a default implementation of these two methods and also of IFormNode::getDocument() .","title":"IFormChildNode"},{"location":"php/api/form_builder/structure/#iformparentnode","text":"IFormParentNode extends IFormNode for such elements of a form that can be a parent to child nodes. Additionally, the interface also extends \\Countable and \\RecursiveIterator . The interface requires the following methods: appendChild(IFormChildNode $child) , appendChildren(array $children) , insertAfter(IFormChildNode $child, $referenceNodeId) , and insertBefore(IFormChildNode $child, $referenceNodeId) are used to insert new children either at the end or at specific positions. validateChild(IFormChildNode $child) is used to check if a given child node can be added. A child node cannot be added if it would cause an id to be used twice. children() returns the direct children of a form node. getIterator() return a recursive iterator for a form node. getNodeById($nodeId) returns the node with the given id by searching for it in the node\u2019s children and recursively in all of their children. contains($nodeId) can be used to simply check if a node with the given id exists. hasValidationErrors() checks if a form node or any of its children has a validation error (see IFormField::getValidationErrors() ). readValues() recursively calls IFormParentNode::readValues() and IFormField::readValue() on its children.","title":"IFormParentNode"},{"location":"php/api/form_builder/structure/#iformelement","text":"IFormElement extends IFormNode for such elements of a form that can have a description and a label and it requires the following methods: label($languageItem = null, array $variables = []) and getLabel() can be used to set and get the label of the form element. requiresLabel() can be checked if the form element requires a label. A label-less form element that requires a label will prevent the form from being rendered by throwing an exception. description($languageItem = null, array $variables = []) and getDescription() can be used to set and get the description of the form element.","title":"IFormElement"},{"location":"php/api/form_builder/structure/#iobjecttypeformnode","text":"IObjectTypeFormField has to be implemented by form nodes that rely on a object type of a specific object type definition in order to function. The implementing class has to implement the methods objectType($objectType) , getObjectType() , and getObjectTypeDefinition() . TObjectTypeFormNode provides a default implementation of these three methods.","title":"IObjectTypeFormNode"},{"location":"php/api/form_builder/structure/#customformnode","text":"CustomFormNode is a form node whose contents can be set directly via content($content) . This class should generally not be relied on. Instead, TemplateFormNode should be used.","title":"CustomFormNode"},{"location":"php/api/form_builder/structure/#templateformnode","text":"TemplateFormNode is a form node whose contents are read from a template. TemplateFormNode has the following additional methods: application($application) and getApplicaton() can be used to set and get the abbreviation of the application the shown template belongs to. If no template has been set explicitly, getApplicaton() returns wcf . templateName($templateName) and getTemplateName() can be used to set and get the name of the template containing the node contents. If no template has been set and the node is rendered, an exception will be thrown. variables(array $variables) and getVariables() can be used to set and get additional variables passed to the template.","title":"TemplateFormNode"},{"location":"php/api/form_builder/structure/#form-document","text":"A form document object represents the form as a whole and has to implement the IFormDocument interface. WoltLab Suite provides a default implementation with the FormDocument class. IFormDocument should not be implemented directly but instead FormDocument should be extended to avoid issues if the IFormDocument interface changes in the future. IFormDocument extends IFormParentNode and requires the following additional methods: action($action) and getAction() can be used set and get the action attribute of the <form> HTML element. addButton(IFormButton $button) and getButtons() can be used add and get form buttons that are shown at the bottom of the form. addDefaultButton($addDefaultButton) and hasDefaultButton() can be used to set and check if the form has the default button which is added by default unless specified otherwise. Each implementing class may define its own default button. FormDocument has a button with id submitButton , label wcf.global.button.submit , access key s , and CSS class buttonPrimary as its default button. ajax($ajax) and isAjax() can be used to set and check if the form document is requested via an AJAX request or processes data via an AJAX request. These methods are helpful for form fields that behave differently when providing data via AJAX. build() has to be called once after all nodes have been added to this document to trigger IFormNode::populate() . formMode($formMode) and getFormMode() sets the form mode. Possible form modes are: IFormDocument::FORM_MODE_CREATE has to be used when the form is used to create a new object. IFormDocument::FORM_MODE_UPDATE has to be used when the form is used to edit an existing object. getData() returns the array containing the form data and which is passed as the $parameters argument of the constructor of a database object action object. getDataHandler() returns the data handler for this document that is used to process the field data into a parameters array for the constructor of a database object action object. getEnctype() returns the encoding type of the form. If the form contains a IFileFormField , multipart/form-data is returned, otherwise null is returned. loadValues(array $data, IStorableObject $object) is used when editing an existing object to set the form field values by calling IFormField::loadValue() for all form fields. Additionally, the form mode is set to IFormDocument::FORM_MODE_UPDATE . 5.4+ markRequiredFields(bool $markRequiredFields = true): self and marksRequiredFields(): bool can be used to set and check whether fields that are required are marked (with an asterisk in the label) in the output. method($method) and getMethod() can be used to set and get the method attribute of the <form> HTML element. By default, the method is post . prefix($prefix) and getPrefix() can be used to set and get a global form prefix that is prepended to form elements\u2019 names and ids to avoid conflicts with other forms. By default, the prefix is an empty string. If a prefix of foo is set, getPrefix() returns foo_ (additional trailing underscore). requestData(array $requestData) , getRequestData($index = null) , and hasRequestData($index = null) can be used to set, get and check for specific request data. In most cases, the relevant request data is the $_POST array. In default AJAX requests handled by database object actions, however, the request data generally is in AbstractDatabaseObjectAction::$parameters . By default, $_POST is the request data. The last aspect is relevant for DialogFormDocument objects. DialogFormDocument is a specialized class for forms in dialogs that, in contrast to FormDocument do not require an action to be set. Additionally, DialogFormDocument provides the cancelable($cancelable = true) and isCancelable() methods used to determine if the dialog from can be canceled. By default, dialog forms are cancelable.","title":"Form Document"},{"location":"php/api/form_builder/structure/#form-button","text":"A form button object represents a button shown at the end of the form that, for example, submits the form. Every form button has to implement the IFormButton interface that extends IFormChildNode and IFormElement . IFormButton requires four methods to be implemented: accessKey($accessKey) and getAccessKey() can be used to set and get the access key with which the form button can be activated. By default, form buttons have no access key set. submit($submitButton) and isSubmit() can be used to set and check if the form button is a submit button. A submit button is an input[type=submit] element. Otherwise, the button is a button element.","title":"Form Button"},{"location":"php/api/form_builder/structure/#form-container","text":"A form container object represents a container for other form containers or form field directly. Every form container has to implement the IFormContainer interface which requires the following method: loadValues(array $data, IStorableObject $object) is called by IFormDocument::loadValuesFromObject() to inform the container that object data is loaded. This method is not intended to generally call IFormField::loadValues() on its form field children as these methods are already called by IFormDocument::loadValuesFromObject() . This method is intended for specialized form containers with more complex logic. There are multiple default container implementations: FormContainer is the default implementation of IFormContainer . TabMenuFormContainer represents the container of tab menu, while TabFormContainer represents a tab of a tab menu and TabTabMenuFormContainer represents a tab of a tab menu that itself contains a tab menu. The children of RowFormContainer are shown in a row and should use col-* classes. The children of RowFormFieldContainer are also shown in a row but does not show the labels and descriptions of the individual form fields. Instead of the individual labels and descriptions, the container's label and description is shown and both span all of fields. SuffixFormFieldContainer can be used for one form field with a second selection form field used as a suffix. The methods of the interfaces that FormContainer is implementing are well documented, but here is a short overview of the most important methods when setting up a form or extending a form with an event listener: appendChild(IFormChildNode $child) , appendChildren(array $children) , and insertBefore(IFormChildNode $child, $referenceNodeId) are used to insert new children into the form container. description($languageItem = null, array $variables = []) and label($languageItem = null, array $variables = []) are used to set the description and the label or title of the form container.","title":"Form Container"},{"location":"php/api/form_builder/structure/#form-field","text":"A form field object represents a concrete form field that allows entering data. Every form field has to implement the IFormField interface which extends IFormChildNode and IFormElement . IFormField requires the following additional methods: addValidationError(IFormFieldValidationError $error) and getValidationErrors() can be used to get and set validation errors of the form field (see form validation ). addValidator(IFormFieldValidator $validator) , getValidators() , removeValidator($validatorId) , and hasValidator($validatorId) can be used to get, set, remove, and check for validators for the form field (see form validation ). getFieldHtml() returns the field's HTML output without the surrounding dl structure. objectProperty($objectProperty) and getObjectProperty() can be used to get and set the object property that the field represents. When setting the object property is set to an empty string, the previously set object property is unset. If no object property has been set, the field\u2019s (non-prefixed) id is returned. The object property allows having different fields (requiring different ids) that represent the same object property which is handy when available options of the field\u2019s value depend on another field. Having object property allows to define different fields for each value of the other field and to use form field dependencies to only show the appropriate field. - readValue() reads the form field value from the request data after the form is submitted. - required($required = true) and isRequired() can be used to determine if the form field has to be filled out. By default, form fields do not have to be filled out. - value($value) and getSaveValue() can be used to get and set the value of the form field to be used outside of the context of forms. getValue() , in contrast, returns the internal representation of the form field\u2019s value. In general, the internal representation is only relevant when validating the value in additional validators. loadValue(array $data, IStorableObject $object) extracts the form field value from the given data array (and additional, non-editable data from the object if the field needs them). AbstractFormField provides default implementations of many of the listed methods above and should be extended instead of implementing IFormField directly. An overview of the form fields provided by default can be found here .","title":"Form Field"},{"location":"php/api/form_builder/structure/#form-field-interfaces-and-traits","text":"WoltLab Suite Core provides a variety of interfaces and matching traits with default implementations for several common features of form fields:","title":"Form Field Interfaces and Traits"},{"location":"php/api/form_builder/structure/#iattributeformfield","text":"Only available since version 5.4. IAttributeFormField has to be implemented by form fields for which attributes can be added to the actual form element (in addition to adding attributes to the surrounding element via the attribute-related methods of IFormNode ). The implementing class has to implement the methods fieldAttribute(string $name, string $value = null): self and getFieldAttribute(string $name): self / getFieldAttributes(): array , which are used to add and get the attributes, respectively. Additionally, hasFieldAttribute(string $name): bool has to implemented to check if a certain attribute is present, removeFieldAttribute(string $name): self to remove an attribute, and static validateFieldAttribute(string $name) to check if the attribute is valid for this specific class. TAttributeFormField provides a default implementation of these methods and TInputAttributeFormField specializes the trait for input -based form fields. These two traits also ensure that if a specific interface that handles a specific attribute is implemented, like IAutoCompleteFormField handling autocomplete , this attribute cannot be set with this API. Instead, the dedicated API provided by the relevant interface has to be used.","title":"IAttributeFormField"},{"location":"php/api/form_builder/structure/#iautocompleteformfield","text":"Only available since version 5.4. IAutoCompleteFormField has to be implemented by form fields that support the autocomplete attribute . The implementing class has to implement the methods autoComplete(?string $autoComplete): self and getAutoComplete(): ?string , which are used to set and get the autocomplete value, respectively. TAutoCompleteFormField provides a default implementation of these two methods and TTextAutoCompleteFormField specializes the trait for text form fields. When using TAutoCompleteFormField , you have to implement the getValidAutoCompleteTokens(): array method which returns all valid autocomplete tokens.","title":"IAutoCompleteFormField"},{"location":"php/api/form_builder/structure/#iautofocusformfield","text":"IAutoFocusFormField has to be implemented by form fields that can be auto-focused. The implementing class has to implement the methods autoFocus($autoFocus = true) and isAutoFocused() . By default, form fields are not auto-focused. TAutoFocusFormField provides a default implementation of these two methods.","title":"IAutoFocusFormField"},{"location":"php/api/form_builder/structure/#icssclassformfield","text":"Only available since version 5.4. ICssClassFormField has to be implemented by form fields for which CSS classes can be added to the actual form element (in addition to adding CSS classes to the surrounding element via the class-related methods of IFormNode ). The implementing class has to implement the methods addFieldClass(string $class): self / addFieldClasses(array $classes): self and getFieldClasses(): array , which are used to add and get the CSS classes, respectively. Additionally, hasFieldClass(string $class): bool has to implemented to check if a certain CSS class is present and removeFieldClass(string $class): self to remove a CSS class. TCssClassFormField provides a default implementation of these methods.","title":"ICssClassFormField"},{"location":"php/api/form_builder/structure/#ifileformfield","text":"IFileFormField has to be implemented by every form field that uploads files so that the enctype attribute of the form document is multipart/form-data (see IFormDocument::getEnctype() ).","title":"IFileFormField"},{"location":"php/api/form_builder/structure/#ifilterableselectionformfield","text":"IFilterableSelectionFormField extends ISelectionFormField by the possibilty for users when selecting the value(s) to filter the list of available options. The implementing class has to implement the methods filterable($filterable = true) and isFilterable() . TFilterableSelectionFormField provides a default implementation of these two methods.","title":"IFilterableSelectionFormField"},{"location":"php/api/form_builder/structure/#ii18nformfield","text":"II18nFormField has to be implemented by form fields if the form field value can be entered separately for all available languages. The implementing class has to implement the following methods: i18n($i18n = true) and isI18n() can be used to set whether a specific instance of the class actually supports multilingual input. i18nRequired($i18nRequired = true) and isI18nRequired() can be used to set whether a specific instance of the class requires separate values for all languages. languageItemPattern($pattern) and getLanguageItemPattern() can be used to set the pattern/regular expression for the language item used to save the multilingual values. hasI18nValues() and hasPlainValue() check if the current value is a multilingual or monolingual value. TI18nFormField provides a default implementation of these eight methods and additional default implementations of some of the IFormField methods. If multilingual input is enabled for a specific form field, classes using TI18nFormField register a custom form field data processor to add the array with multilingual input into the $parameters array directly using {$objectProperty}_i18n as the array key. If multilingual input is enabled but only a monolingual value is entered, the custom form field data processor does nothing and the form field\u2019s value is added by the DefaultFormDataProcessor into the data sub-array of the $parameters array. TI18nFormField already provides a default implementation of IFormField::validate() .","title":"II18nFormField"},{"location":"php/api/form_builder/structure/#iimmutableformfield","text":"IImmutableFormField has to be implemented by form fields that support being displayed but whose value cannot be changed. The implementing class has to implement the methods immutable($immutable = true) and isImmutable() that can be used to determine if the value of the form field is mutable or immutable. By default, form field are mutable.","title":"IImmutableFormField"},{"location":"php/api/form_builder/structure/#iinputmodeformfield","text":"Only available since version 5.4. IInputModeFormField has to be implemented by form fields that support the inputmode attribute . The implementing class has to implement the methods inputMode(?string $inputMode): self and getInputMode(): ?string , which are used to set and get the input mode, respectively. TInputModeFormField provides a default implementation of these two methods.","title":"IInputModeFormField"},{"location":"php/api/form_builder/structure/#imaximumformfield","text":"IMaximumFormField has to be implemented by form fields if the entered value must have a maximum value. The implementing class has to implement the methods maximum($maximum = null) and getMaximum() . A maximum of null signals that no maximum value has been set. TMaximumFormField provides a default implementation of these two methods. The implementing class has to validate the entered value against the maximum value manually.","title":"IMaximumFormField"},{"location":"php/api/form_builder/structure/#imaximumlengthformfield","text":"IMaximumLengthFormField has to be implemented by form fields if the entered value must have a maximum length. The implementing class has to implement the methods maximumLength($maximumLength = null) , getMaximumLength() , and validateMaximumLength($text, Language $language = null) . A maximum length of null signals that no maximum length has been set. TMaximumLengthFormField provides a default implementation of these two methods. The implementing class has to validate the entered value against the maximum value manually by calling validateMaximumLength() .","title":"IMaximumLengthFormField"},{"location":"php/api/form_builder/structure/#iminimumformfield","text":"IMinimumFormField has to be implemented by form fields if the entered value must have a minimum value. The implementing class has to implement the methods minimum($minimum = null) and getMinimum() . A minimum of null signals that no minimum value has been set. TMinimumFormField provides a default implementation of these three methods. The implementing class has to validate the entered value against the minimum value manually.","title":"IMinimumFormField"},{"location":"php/api/form_builder/structure/#iminimumlengthformfield","text":"IMinimumLengthFormField has to be implemented by form fields if the entered value must have a minimum length. The implementing class has to implement the methods minimumLength($minimumLength = null) , getMinimumLength() , and validateMinimumLength($text, Language $language = null) . A minimum length of null signals that no minimum length has been set. TMinimumLengthFormField provides a default implementation of these three methods. The implementing class has to validate the entered value against the minimum value manually by calling validateMinimumLength() .","title":"IMinimumLengthFormField"},{"location":"php/api/form_builder/structure/#imultipleformfield","text":"IMinimumLengthFormField has to be implemented by form fields that support selecting or setting multiple values. The implementing class has to implement the following methods: multiple($multiple = true) and allowsMultiple() can be used to set whether a specific instance of the class actually should support multiple values. By default, multiple values are not supported. minimumMultiples($minimum) and getMinimumMultiples() can be used to set the minimum number of values that have to be selected/entered. By default, there is no required minimum number of values. maximumMultiples($minimum) and getMaximumMultiples() can be used to set the maximum number of values that have to be selected/entered. By default, there is no maximum number of values. IMultipleFormField::NO_MAXIMUM_MULTIPLES is returned if no maximum number of values has been set and it can also be used to unset a previously set maximum number of values. TMultipleFormField provides a default implementation of these six methods and classes using TMultipleFormField register a custom form field data processor to add the HtmlInputProcessor object with the text into the $parameters array directly using {$objectProperty}_htmlInputProcessor as the array key. The implementing class has to validate the values against the minimum and maximum number of values manually.","title":"IMultipleFormField"},{"location":"php/api/form_builder/structure/#inullableformfield","text":"INullableFormField has to be implemented by form fields that support null as their (empty) value. The implementing class has to implement the methods nullable($nullable = true) and isNullable() . TNullableFormField provides a default implementation of these two methods. null should be returned by IFormField::getSaveValue() is the field is considered empty and the form field has been set as nullable.","title":"INullableFormField"},{"location":"php/api/form_builder/structure/#ipackagesformfield","text":"IPackagesFormField has to be implemented by form fields that, in some way, considers packages whose ids may be passed to the field object. The implementing class has to implement the methods packageIDs(array $packageIDs) and getPackageIDs() . TPackagesFormField provides a default implementation of these two methods.","title":"IPackagesFormField"},{"location":"php/api/form_builder/structure/#ipatternformfield","text":"Only available since version 5.4. IPatternFormField has to be implemented by form fields that support the pattern attribute . The implementing class has to implement the methods pattern(?string $pattern): self and getPattern(): ?string , which are used to set and get the pattern, respectively. TPatternFormField provides a default implementation of these two methods.","title":"IPatternFormField"},{"location":"php/api/form_builder/structure/#iplaceholderformfield","text":"IPlaceholderFormField has to be implemented by form fields that support a placeholder value for empty fields. The implementing class has to implement the methods placeholder($languageItem = null, array $variables = []) and getPlaceholder() . TPlaceholderFormField provides a default implementation of these two methods.","title":"IPlaceholderFormField"},{"location":"php/api/form_builder/structure/#iselectionformfield","text":"ISelectionFormField has to be implemented by form fields with a predefined set of possible values. The implementing class has to implement the getter and setter methods options($options, $nestedOptions = false, $labelLanguageItems = true) and getOptions() and additionally two methods related to nesting, i.e. whether the selectable options have a hierarchy: supportsNestedOptions() and getNestedOptions() . TSelectionFormField provides a default implementation of these four methods.","title":"ISelectionFormField"},{"location":"php/api/form_builder/structure/#isuffixedformfield","text":"ISuffixedFormField has to be implemented by form fields that support supports displaying a suffix behind the actual input field. The implementing class has to implement the methods suffix($languageItem = null, array $variables = []) and getSuffix() . TSuffixedFormField provides a default implementation of these two methods.","title":"ISuffixedFormField"},{"location":"php/api/form_builder/structure/#tdefaultidformfield","text":"Form fields that have a default id have to use TDefaultIdFormField and have to implement the method getDefaultId() .","title":"TDefaultIdFormField"},{"location":"php/api/form_builder/structure/#displaying-forms","text":"The only thing to do in a template to display the whole form including all of the necessary JavaScript is to put 1 { @ $form -> getHtml () } into the template file at the relevant position.","title":"Displaying Forms"},{"location":"php/api/form_builder/validation_data/","text":"Form Validation and Form Data # Form Validation # Every form field class has to implement IFormField::validate() according to their internal logic of what constitutes a valid value. If a certain constraint for the value is not met, a form field validation error object is added to the form field. Form field validation error classes have to implement the interface IFormFieldValidationError . In addition to intrinsic validations like checking the length of the value of a text form field, in many cases, there are additional constraints specific to the form like ensuring that the text is not already used by a different object of the same database object class. Such additional validations can be added to (and removed from) the form field via implementations of the IFormFieldValidator interface. IFormFieldValidationError / FormFieldValidationError # IFormFieldValidationError requires the following methods: __construct($type, $languageItem = null, array $information = []) creates a new validation error object for an error with the given type and message stored in the given language items. The information array is used when generating the error message. getHtml() returns the HTML element representing the error that is shown to the user. getMessage() returns the error message based on the language item and information array given in the constructor. getInformation() and getType() are getters for the first and third parameter of the constructor. FormFieldValidationError is a default implementation of the interface that shows the error in an small.innerError HTML element below the form field. Form field validation errors are added to form fields via the IFormField::addValidationError(IFormFieldValidationError $error) method. IFormFieldValidator / FormFieldValidator # IFormFieldValidator requires the following methods: __construct($id, callable $validator) creates a new validator with the given id that passes the validated form field to the given callable that does the actual validation. static validateId($id) is used to check if the given id is valid. __invoke(IFormField $field) is used when the form field is validated to execute the validator. getId() returns the id of the validator. FormFieldValidator is a default implementation of the interface. Form field validators are added to form fields via the addValidator(IFormFieldValidator $validator) method. Form Data # After a form is successfully validated, the data of the form fields (returned by IFormDocument::getData() ) have to be extracted which is the job of the IFormDataHandler object returned by IFormDocument::getDataHandler() . Form data handlers themselves, however, are only iterating through all IFormDataProcessor instances that have been registered with the data handler. IFormDataHandler / FormDataHandler # IFormDataHandler requires the following methods: addProcessor(IFormDataProcessor $processor) adds a new data processor to the data handler. getFormData(IFormDocument $document) returns the data of the given form by applying all registered data handlers on the form. getObjectData(IFormDocument $document, IStorableObject $object) returns the data of the given object which will be used to populate the form field values of the given form. FormDataHandler is the default implementation of this interface and should also be extended instead of implementing the interface directly. IFormDataProcessor / DefaultFormDataProcessor # IFormDataProcessor requires the following methods: processFormData(IFormDocument $document, array $parameters) is called by IFormDataHandler::getFormData() . The method processes the given parameters array and returns the processed version. processObjectData(IFormDocument $document, array $data, IStorableObject $object) is called by IFormDataHandler::getObjectData() . The method processes the given object data array and returns the processed version. When FormDocument creates its FormDataHandler instance, it automatically registers an DefaultFormDataProcessor object as the first data processor. DefaultFormDataProcessor puts the save value of all form fields that are available and have a save value into $parameters['data'] using the form field\u2019s object property as the array key. IFormDataProcessor should not be implemented directly. Instead, AbstractFormDataProcessor should be extended. All form data is put into the data sub-array so that the whole $parameters array can be passed to a database object action object that requires the actual database object data to be in the data sub-array. When adding a data processor to a form, make sure to add the data processor after the form has been built. Additional Data Processors # CustomFormDataProcessor # As mentioned above, the data in the data sub-array is intended to directly create or update the database object with. As these values are used in the database query directly, these values cannot contain arrays. Several form fields, however, store and return their data in form of arrays. Thus, this data cannot be returned by IFormField::getSaveValue() so that IFormField::hasSaveValue() returns false and the form field\u2019s data is not collected by the standard DefaultFormDataProcessor object. Instead, such form fields register a CustomFormDataProcessor in their IFormField::populate() method that inserts the form field value into the $parameters array directly. This way, the relevant database object action method has access to the data to save it appropriately. The constructor of CustomFormDataProcessor requires an id (that is primarily used in error messages during the validation of the second parameter) and callables for IFormDataProcessor::processFormData() and IFormDataProcessor::processObjectData() which are passed the same parameters as the IFormDataProcessor methods. Only one of the callables has to be given, the other one then defaults to simply returning the relevant array unchanged. VoidFormDataProcessor # Some form fields might only exist to toggle the visibility of other form fields (via dependencies) but the data of form field itself is irrelevant. As DefaultFormDataProcessor collects the data of all form fields, an additional data processor in the form of a VoidFormDataProcessor can be added whose constructor __construct($property, $isDataProperty = true) requires the name of the relevant object property/form id and whether the form field value is stored in the data sub-array or directory in the $parameters array. When the data processor is invoked, it checks whether the relevant entry in the $parameters array exists and voids it by removing it from the array.","title":"Validation and Data"},{"location":"php/api/form_builder/validation_data/#form-validation-and-form-data","text":"","title":"Form Validation and Form Data"},{"location":"php/api/form_builder/validation_data/#form-validation","text":"Every form field class has to implement IFormField::validate() according to their internal logic of what constitutes a valid value. If a certain constraint for the value is not met, a form field validation error object is added to the form field. Form field validation error classes have to implement the interface IFormFieldValidationError . In addition to intrinsic validations like checking the length of the value of a text form field, in many cases, there are additional constraints specific to the form like ensuring that the text is not already used by a different object of the same database object class. Such additional validations can be added to (and removed from) the form field via implementations of the IFormFieldValidator interface.","title":"Form Validation"},{"location":"php/api/form_builder/validation_data/#iformfieldvalidationerror-formfieldvalidationerror","text":"IFormFieldValidationError requires the following methods: __construct($type, $languageItem = null, array $information = []) creates a new validation error object for an error with the given type and message stored in the given language items. The information array is used when generating the error message. getHtml() returns the HTML element representing the error that is shown to the user. getMessage() returns the error message based on the language item and information array given in the constructor. getInformation() and getType() are getters for the first and third parameter of the constructor. FormFieldValidationError is a default implementation of the interface that shows the error in an small.innerError HTML element below the form field. Form field validation errors are added to form fields via the IFormField::addValidationError(IFormFieldValidationError $error) method.","title":"IFormFieldValidationError / FormFieldValidationError"},{"location":"php/api/form_builder/validation_data/#iformfieldvalidator-formfieldvalidator","text":"IFormFieldValidator requires the following methods: __construct($id, callable $validator) creates a new validator with the given id that passes the validated form field to the given callable that does the actual validation. static validateId($id) is used to check if the given id is valid. __invoke(IFormField $field) is used when the form field is validated to execute the validator. getId() returns the id of the validator. FormFieldValidator is a default implementation of the interface. Form field validators are added to form fields via the addValidator(IFormFieldValidator $validator) method.","title":"IFormFieldValidator / FormFieldValidator"},{"location":"php/api/form_builder/validation_data/#form-data","text":"After a form is successfully validated, the data of the form fields (returned by IFormDocument::getData() ) have to be extracted which is the job of the IFormDataHandler object returned by IFormDocument::getDataHandler() . Form data handlers themselves, however, are only iterating through all IFormDataProcessor instances that have been registered with the data handler.","title":"Form Data"},{"location":"php/api/form_builder/validation_data/#iformdatahandler-formdatahandler","text":"IFormDataHandler requires the following methods: addProcessor(IFormDataProcessor $processor) adds a new data processor to the data handler. getFormData(IFormDocument $document) returns the data of the given form by applying all registered data handlers on the form. getObjectData(IFormDocument $document, IStorableObject $object) returns the data of the given object which will be used to populate the form field values of the given form. FormDataHandler is the default implementation of this interface and should also be extended instead of implementing the interface directly.","title":"IFormDataHandler / FormDataHandler"},{"location":"php/api/form_builder/validation_data/#iformdataprocessor-defaultformdataprocessor","text":"IFormDataProcessor requires the following methods: processFormData(IFormDocument $document, array $parameters) is called by IFormDataHandler::getFormData() . The method processes the given parameters array and returns the processed version. processObjectData(IFormDocument $document, array $data, IStorableObject $object) is called by IFormDataHandler::getObjectData() . The method processes the given object data array and returns the processed version. When FormDocument creates its FormDataHandler instance, it automatically registers an DefaultFormDataProcessor object as the first data processor. DefaultFormDataProcessor puts the save value of all form fields that are available and have a save value into $parameters['data'] using the form field\u2019s object property as the array key. IFormDataProcessor should not be implemented directly. Instead, AbstractFormDataProcessor should be extended. All form data is put into the data sub-array so that the whole $parameters array can be passed to a database object action object that requires the actual database object data to be in the data sub-array. When adding a data processor to a form, make sure to add the data processor after the form has been built.","title":"IFormDataProcessor / DefaultFormDataProcessor"},{"location":"php/api/form_builder/validation_data/#additional-data-processors","text":"","title":"Additional Data Processors"},{"location":"php/api/form_builder/validation_data/#customformdataprocessor","text":"As mentioned above, the data in the data sub-array is intended to directly create or update the database object with. As these values are used in the database query directly, these values cannot contain arrays. Several form fields, however, store and return their data in form of arrays. Thus, this data cannot be returned by IFormField::getSaveValue() so that IFormField::hasSaveValue() returns false and the form field\u2019s data is not collected by the standard DefaultFormDataProcessor object. Instead, such form fields register a CustomFormDataProcessor in their IFormField::populate() method that inserts the form field value into the $parameters array directly. This way, the relevant database object action method has access to the data to save it appropriately. The constructor of CustomFormDataProcessor requires an id (that is primarily used in error messages during the validation of the second parameter) and callables for IFormDataProcessor::processFormData() and IFormDataProcessor::processObjectData() which are passed the same parameters as the IFormDataProcessor methods. Only one of the callables has to be given, the other one then defaults to simply returning the relevant array unchanged.","title":"CustomFormDataProcessor"},{"location":"php/api/form_builder/validation_data/#voidformdataprocessor","text":"Some form fields might only exist to toggle the visibility of other form fields (via dependencies) but the data of form field itself is irrelevant. As DefaultFormDataProcessor collects the data of all form fields, an additional data processor in the form of a VoidFormDataProcessor can be added whose constructor __construct($property, $isDataProperty = true) requires the name of the relevant object property/form id and whether the form field value is stored in the data sub-array or directory in the $parameters array. When the data processor is invoked, it checks whether the relevant entry in the $parameters array exists and voids it by removing it from the array.","title":"VoidFormDataProcessor"},{"location":"tutorial/series/overview/","text":"Tutorial Series # In this tutorial series, we will code a package that allows administrators to create a registry of people. In this context, \"people\" does not refer to users registered on the website but anybody living, dead or fictional. We will start this tutorial series by creating a base structure for the package and then continue by adding further features step by step using different APIs. Note that in the context of this example, not every added feature might make perfect sense but the goal of this tutorial is not to create a useful package but to introduce you to WoltLab Suite. Part 1: Base Structure Part 2: Event and Template Listeners Part 3: Person Page and Comments Part 4: Box and Box Conditions Part 5: Person Information Part 6: Activity Points and Activity Events","title":"Overview"},{"location":"tutorial/series/overview/#tutorial-series","text":"In this tutorial series, we will code a package that allows administrators to create a registry of people. In this context, \"people\" does not refer to users registered on the website but anybody living, dead or fictional. We will start this tutorial series by creating a base structure for the package and then continue by adding further features step by step using different APIs. Note that in the context of this example, not every added feature might make perfect sense but the goal of this tutorial is not to create a useful package but to introduce you to WoltLab Suite. Part 1: Base Structure Part 2: Event and Template Listeners Part 3: Person Page and Comments Part 4: Box and Box Conditions Part 5: Person Information Part 6: Activity Points and Activity Events","title":"Tutorial Series"},{"location":"tutorial/series/part_1/","text":"Tutorial Series Part 1: Base Structure # In the first part of this tutorial series, we will lay out what the basic version of package should be able to do and how to implement these functions. Package Functionality # The package should provide the following possibilities/functions: Sortable list of all people in the ACP Ability to add, edit and delete people in the ACP Restrict the ability to add, edit and delete people (in short: manage people) in the ACP Sortable list of all people in the front end Used Components # We will use the following package installation plugins: acpTemplate package installation plugin , acpMenu package installation plugin , database package installation plugin , file package installation plugin , language package installation plugin , menuItem package installation plugin , page package installation plugin , template package installation plugin , userGroupOption package installation plugin , use database objects , create pages and use templates . Package Structure # The package will have the following file structure: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 \u251c\u2500\u2500 acpMenu.xml \u251c\u2500\u2500 acptemplates \u2502 \u251c\u2500\u2500 personAdd.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u251c\u2500\u2500 form \u2502 \u2502 \u2502 \u251c\u2500\u2500 PersonAddForm.class.php \u2502 \u2502 \u2502 \u2514\u2500\u2500 PersonEditForm.class.php \u2502 \u2502 \u2514\u2500\u2500 page \u2502 \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonList.class.php \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 menuItem.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u251c\u2500\u2500 templates \u2502 \u2514\u2500\u2500 personList.tpl \u2514\u2500\u2500 userGroupOption.xml Person Modeling # Database Table # As the first step, we have to model the people we want to manage with this package. As this is only an introductory tutorial, we will keep things simple and only consider the first and last name of a person. Thus, the database table we will store the people in only contains three columns: personID is the unique numeric identifier of each person created, firstName contains the first name of the person, lastName contains the last name of the person. The first file for our package is the install_com.woltlab.wcf.people.php file used to create such a database table during package installation: files/acp/database/install_com.woltlab.wcf.people.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php use wcf\\system\\database\\table\\column\\NotNullVarchar255DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\ObjectIdDatabaseTableColumn ; use wcf\\system\\database\\table\\DatabaseTable ; use wcf\\system\\database\\table\\index\\DatabaseTablePrimaryIndex ; return [ DatabaseTable :: create ( 'wcf1_person' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'personID' ), NotNullVarchar255DatabaseTableColumn :: create ( 'firstName' ), NotNullVarchar255DatabaseTableColumn :: create ( 'lastName' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'personID' ]), ]), ]; Database Object # Person # In our PHP code, each person will be represented by an object of the following class: files/lib/data/person/Person.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObject ; use wcf\\system\\request\\IRouteController ; /** * Represents a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @property-read int $personID unique id of the person * @property-read string $firstName first name of the person * @property-read string $lastName last name of the person */ class Person extends DatabaseObject implements IRouteController { /** * Returns the first and last name of the person if a person object is treated as a string. * * @return string */ public function __toString () { return $this -> getTitle (); } /** * @inheritDoc */ public function getTitle () { return $this -> firstName . ' ' . $this -> lastName ; } } The important thing here is that Person extends DatabaseObject . Additionally, we implement the IRouteController interface, which allows us to use Person objects to create links, and we implement PHP's magic __toString() method for convenience. For every database object, you need to implement three additional classes: an action class, an editor class and a list class. PersonAction # files/lib/data/person/PersonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <? php namespace wcf\\data\\person ; use wcf\\data\\AbstractDatabaseObjectAction ; /** * Executes person-related actions. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method Person create() * @method PersonEditor[] getObjects() * @method PersonEditor getSingleObject() */ class PersonAction extends AbstractDatabaseObjectAction { /** * @inheritDoc */ protected $permissionsDelete = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ protected $requireACP = [ 'delete' ]; } This implementation of AbstractDatabaseObjectAction is very basic and only sets the $permissionsDelete and $requireACP properties. This is done so that later on, when implementing the people list for the ACP, we can delete people simply via AJAX. $permissionsDelete has to be set to the permission needed in order to delete a person. We will later use the userGroupOption package installation plugin to create the admin.content.canManagePeople permission. $requireACP restricts deletion of people to the ACP. PersonEditor # files/lib/data/person/PersonEditor.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObjectEditor ; /** * Provides functions to edit people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method static Person create(array $parameters = []) * @method Person getDecoratedObject() * @mixin Person */ class PersonEditor extends DatabaseObjectEditor { /** * @inheritDoc */ protected static $baseClass = Person :: class ; } This implementation of DatabaseObjectEditor fulfills the minimum requirement for a database object editor: setting the static $baseClass property to the database object class name. PersonList # files/lib/data/person/PersonList.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObjectList ; /** * Represents a list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method Person current() * @method Person[] getObjects() * @method Person|null search($objectID) * @property Person[] $objects */ class PersonList extends DatabaseObjectList { } Due to the default implementation of DatabaseObjectList , our PersonList class just needs to extend it and everything else is either automatically set by the code of DatabaseObjectList or, in the case of properties and methods, provided by that class. ACP # Next, we will take care of the controllers and views for the ACP. In total, we need three each: page to list people, form to add people, and form to edit people. Before we create the controllers and views, let us first create the menu items for the pages in the ACP menu. ACP Menu # We need to create three menu items: a \u201cparent\u201d menu item on the second level of the ACP menu item tree, a third level menu item for the people list page, and a fourth level menu item for the form to add new people. acpMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/acpMenu.xsd\" > <import> <acpmenuitem name= \"wcf.acp.menu.link.person\" > <parent> wcf.acp.menu.link.content </parent> </acpmenuitem> <acpmenuitem name= \"wcf.acp.menu.link.person.list\" > <controller> wcf\\acp\\page\\PersonListPage </controller> <parent> wcf.acp.menu.link.person </parent> <permissions> admin.content.canManagePeople </permissions> </acpmenuitem> <acpmenuitem name= \"wcf.acp.menu.link.person.add\" > <controller> wcf\\acp\\form\\PersonAddForm </controller> <parent> wcf.acp.menu.link.person.list </parent> <permissions> admin.content.canManagePeople </permissions> <icon> fa-plus </icon> </acpmenuitem> </import> </data> We choose wcf.acp.menu.link.content as the parent menu item for the first menu item wcf.acp.menu.link.person because the people we are managing is just one form of content. The fourth level menu item wcf.acp.menu.link.person.add will only be shown as an icon and thus needs an additional element icon which takes a FontAwesome icon class as value. People List # To list the people in the ACP, we need a PersonListPage class and a personList template. PersonListPage # files/lib/acp/page/PersonListPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\acp\\page ; use wcf\\data\\person\\PersonList ; use wcf\\page\\SortablePage ; /** * Shows the list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Page */ class PersonListPage extends SortablePage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.list' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectListClassName = PersonList :: class ; /** * @inheritDoc */ public $validSortFields = [ 'personID' , 'firstName' , 'lastName' ]; } As WoltLab Suite Core already provides a powerful default implementation of a sortable page, our work here is minimal: We need to set the active ACP menu item via the $activeMenuItem . $neededPermissions contains a list of permissions of which the user needs to have at least one in order to see the person list. We use the same permission for both the menu item and the page. The database object list class whose name is provided via $objectListClassName and that handles fetching the people from database is the PersonList class, which we have already created. To validate the sort field passed with the request, we set $validSortFields to the available database table columns. personList.tpl # acptemplates/personList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 { include file = 'header' pageTitle = 'wcf.acp.person.list' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person.list { /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonAdd' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.acp.menu.link.person.add { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { hascontent } <div class=\"paginationTop\"> { content }{ pages print = true assign = pagesLinks controller = \"PersonList\" link = \"pageNo=%d&sortField=$sortField&sortOrder=$sortOrder\" }{ /content } </div> { /hascontent } { if $objects | count } <div class=\"section tabularBox\"> <table class=\"table jsObjectActionContainer\" data-object-action-class-name=\"wcf\\data\\person\\PersonAction\"> <thead> <tr> <th class=\"columnID columnPersonID { if $sortField == 'personID' } active { @ $sortOrder }{ /if } \" colspan=\"2\"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=personID&sortOrder= { if $sortField == 'personID' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.global.objectID { /lang } </a></th> <th class=\"columnTitle columnFirstName { if $sortField == 'firstName' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=firstName&sortOrder= { if $sortField == 'firstName' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.firstName { /lang } </a></th> <th class=\"columnTitle columnLastName { if $sortField == 'lastName' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=lastName&sortOrder= { if $sortField == 'lastName' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.lastName { /lang } </a></th> { event name = 'columnHeads' } </tr> </thead> <tbody class=\"jsReloadPageWhenEmpty\"> { foreach from = $objects item = person } <tr class=\"jsObjectActionObject\" data-object-id=\" { @ $person -> getObjectID () } \"> <td class=\"columnIcon\"> <a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \" title=\" { lang } wcf.global.button.edit { /lang } \" class=\"jsTooltip\"><span class=\"icon icon16 fa-pencil\"></span></a> { objectAction action = \"delete\" objectTitle = $person -> getTitle () } { event name = 'rowButtons' } </td> <td class=\"columnID\"> { # $person -> personID } </td> <td class=\"columnTitle columnFirstName\"><a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \"> { $person -> firstName } </a></td> <td class=\"columnTitle columnLastName\"><a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \"> { $person -> lastName } </a></td> { event name = 'columns' } </tr> { /foreach } </tbody> </table> </div> <footer class=\"contentFooter\"> { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } <nav class=\"contentFooterNavigation\"> <ul> <li><a href=\" { link controller = 'PersonAdd' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.acp.menu.link.person.add { /lang } </span></a></li> { event name = 'contentFooterNavigation' } </ul> </nav> </footer> { else } <p class=\"info\"> { lang } wcf.global.noItems { /lang } </p> { /if } { include file = 'footer' } We will go piece by piece through the template code: We include the header template and set the page title wcf.acp.person.list . You have to include this template for every page! We set the content header and additional provide a button to create a new person in the content header navigation. As not all people are listed on the same page if many people have been created, we need a pagination for which we use the pages template plugin. The {hascontent}{content}{/content}{/hascontent} construct ensures the .paginationTop element is only shown if the pages template plugin has a return value, thus if a pagination is necessary. Now comes the main part of the page, the list of the people, which will only be displayed if any people exist. Otherwise, an info box is displayed using the generic wcf.global.noItems language item. The $objects template variable is automatically assigned by wcf\\page\\MultipleLinkPage and contains the PersonList object used to read the people from database. The table itself consists of a thead and a tbody element and is extendable with more columns using the template events columnHeads and columns . In general, every table should provide these events. The default structure of a table is used here so that the first column of the content rows contains icons to edit and to delete the row (and provides another standard event rowButtons ) and that the second column contains the ID of the person. The table can be sorted by clicking on the head of each column. The used variables $sortField and $sortOrder are automatically assigned to the template by SortablePage . The .contentFooter element is only shown if people exist as it basically repeats the .contentHeaderNavigation and .paginationTop element. The delete button for each person shown in the .columnIcon element relies on the global WoltLabSuite/Core/Ui/Object/Action module which only requires the jsObjectActionContainer CSS class in combination with the data-object-action-class-name attribute for the table element, the jsObjectActionObject CSS class for each person's tr element in combination with the data-object-id attribute, and lastly the delete button itself, which is created with the objectAction template plugin . The .jsReloadPageWhenEmpty CSS class on the tbody element ensures that once all persons on the page have been deleted, the page is reloaded. Lastly, the footer template is included that terminates the page. You also have to include this template for every page! Now, we have finished the page to manage the people so that we can move on to the forms with which we actually create and edit the people. Person Add Form # Like the person list, the form to add new people requires a controller class and a template. PersonAddForm # files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\TextFormField ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractFormBuilderForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * @inheritDoc */ public $formAction = 'create' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectActionClass = PersonAction :: class ; /** * @inheritDoc */ public $objectEditLinkController = PersonEditForm :: class ; /** * @inheritDoc */ protected function createForm () { parent :: createForm (); $this -> form -> appendChild ( FormContainer :: create ( 'data' ) -> label ( 'wcf.global.form.data' ) -> appendChildren ([ TextFormField :: create ( 'firstName' ) -> label ( 'wcf.person.firstName' ) -> required () -> autoFocus () -> maximumLength ( 255 ), TextFormField :: create ( 'lastName' ) -> label ( 'wcf.person.lastName' ) -> required () -> maximumLength ( 255 ), ]) ); } } The properties here consist of three types: the \u201chousekeeping\u201d properties $activeMenuItem and $neededPermissions , which fulfill the same roles as for PersonListPage , and the $objectEditLinkController property , which is used to generate a link to edit the newly created person after submitting the form, and finally $formAction and $objectActionClass required by the PHP form builder API used to generate the form. Because of using form builder, we only have to set up the two form fields for entering the first and last name, respectively: Each field is a simple single-line text field, thus we use TextFormField . The parameter of the create() method expects the id of the field/name of the database object property, which is firstName and lastName , respectively, here. The language item of the label shown in the ouput above the input field is set via the label() method. As both fields have to be filled out, required() is called, and the maximum length is set via maximumLength() . Lastly, to make it easier to fill out the form more quickly, the first field is auto-focused by calling autoFocus() . personAdd.tpl # acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { @ $form -> getHtml () } { include file = 'footer' } We will now only concentrate on the new parts compared to personList.tpl : We use the $action variable to distinguish between the languages items used for adding a person and for creating a person. Because of form builder, we only have to call {@$form->getHtml()} to generate all relevant output for the form. Person Edit Form # As mentioned before, for the form to edit existing people, we only need a new controller as the template has already been implemented in a way that it handles both, adding and editing. PersonEditForm # files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\system\\exception\\IllegalLinkException ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * @inheritDoc */ public $formAction = 'update' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> formObject = new Person ( $_REQUEST [ 'id' ]); if ( ! $this -> formObject -> getObjectID ()) { throw new IllegalLinkException (); } } } } In general, edit forms extend the associated add form so that the code to read and to validate the input data is simply inherited. After setting a different active menu item, we have to change the value of $formAction because this form, in contrast to PersonAddForm , does not create but update existing persons. As we rely on form builder, the only thing necessary in this controller is to read and validate the edit object, i.e. the edited person, which is done in readParameters() . Frontend # For the front end, that means the part with which the visitors of a website interact, we want to implement a simple sortable page that lists the people. This page should also be directly linked in the main menu. page.xml # First, let us register the page with the system because every front end page or form needs to be explicitly registered using the page package installation plugin : page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.people.PersonList\" > <pageType> system </pageType> <controller> wcf\\page\\PersonListPage </controller> <name language= \"de\" > Personen-Liste </name> <name language= \"en\" > Person List </name> <content language= \"de\" > <title> Personen </title> </content> <content language= \"en\" > <title> People </title> </content> </page> </import> </data> For more information about what each of the elements means, please refer to the page package installation plugin page . menuItem.xml # Next, we register the menu item using the menuItem package installation plugin : menuItem.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/menuItem.xsd\" > <import> <item identifier= \"com.woltlab.wcf.people.PersonList\" > <menu> com.woltlab.wcf.MainMenu </menu> <title language= \"de\" > Personen </title> <title language= \"en\" > People </title> <page> com.woltlab.wcf.people.PersonList </page> </item> </import> </data> Here, the import parts are that we register the menu item for the main menu com.woltlab.wcf.MainMenu and link the menu item with the page com.woltlab.wcf.people.PersonList , which we just registered. People List # As in the ACP, we need a controller and a template. You might notice that both the controller\u2019s (unqualified) class name and the template name are the same for the ACP and the front end. This is no problem because the qualified names of the classes differ and the files are stored in different directories and because the templates are installed by different package installation plugins and are also stored in different directories. PersonListPage # files/lib/page/PersonListPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <? php namespace wcf\\page ; use wcf\\data\\person\\PersonList ; /** * Shows the list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Page */ class PersonListPage extends SortablePage { /** * @inheritDoc */ public $defaultSortField = 'lastName' ; /** * @inheritDoc */ public $objectListClassName = PersonList :: class ; /** * @inheritDoc */ public $validSortFields = [ 'personID' , 'firstName' , 'lastName' ]; } This class is almost identical to the ACP version. In the front end, we do not need to set the active menu item manually because the system determines the active menu item automatically based on the requested page. Furthermore, $neededPermissions has not been set because in the front end, users do not need any special permission to access the page. In the front end, we explicitly set the $defaultSortField so that the people listed on the page are sorted by their last name (in ascending order) by default. personList.tpl # templates/personList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 { capture assign = 'contentTitle' }{ lang } wcf.person.list { /lang } <span class=\"badge\"> { # $items } </span> { /capture } { capture assign = 'headContent' } { if $pageNo < $pages } <link rel=\"next\" href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo + 1 }{ /link } \"> { /if } { if $pageNo > 1 } <link rel=\"prev\" href=\" { link controller = 'PersonList' }{ if $pageNo > 2 } pageNo= { @ $pageNo - 1 }{ /if }{ /link } \"> { /if } <link rel=\"canonical\" href=\" { link controller = 'PersonList' }{ if $pageNo > 1 } pageNo= { @ $pageNo }{ /if }{ /link } \"> { /capture } { capture assign = 'sidebarRight' } <section class=\"box\"> <form method=\"post\" action=\" { link controller = 'PersonList' }{ /link } \"> <h2 class=\"boxTitle\"> { lang } wcf.global.sorting { /lang } </h2> <div class=\"boxContent\"> <dl> <dt></dt> <dd> <select id=\"sortField\" name=\"sortField\"> <option value=\"firstName\" { if $sortField == 'firstName' } selected { /if } > { lang } wcf.person.firstName { /lang } </option> <option value=\"lastName\" { if $sortField == 'lastName' } selected { /if } > { lang } wcf.person.lastName { /lang } </option> { event name = 'sortField' } </select> <select name=\"sortOrder\"> <option value=\"ASC\" { if $sortOrder == 'ASC' } selected { /if } > { lang } wcf.global.sortOrder.ascending { /lang } </option> <option value=\"DESC\" { if $sortOrder == 'DESC' } selected { /if } > { lang } wcf.global.sortOrder.descending { /lang } </option> </select> </dd> </dl> <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> </div> </div> </form> </section> { /capture } { include file = 'header' } { hascontent } <div class=\"paginationTop\"> { content } { pages print = true assign = pagesLinks controller = 'PersonList' link = \"pageNo=%d&sortField=$sortField&sortOrder=$sortOrder\" } { /content } </div> { /hascontent } { if $items } <div class=\"section sectionContainerList\"> <ol class=\"containerList personList\"> { foreach from = $objects item = person } <li> <div class=\"box48\"> <span class=\"icon icon48 fa-user\"></span> <div class=\"details personInformation\"> <div class=\"containerHeadline\"> <h3> { $person } </h3> </div> { hascontent } <ul class=\"inlineList commaSeparated\"> { content }{ event name = 'personData' }{ /content } </ul> { /hascontent } { hascontent } <dl class=\"plain inlineDataList small\"> { content }{ event name = 'personStatistics' }{ /content } </dl> { /hascontent } </div> </div> </li> { /foreach } </ol> </div> { else } <p class=\"info\"> { lang } wcf.global.noItems { /lang } </p> { /if } <footer class=\"contentFooter\"> { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } { hascontent } <nav class=\"contentFooterNavigation\"> <ul> { content }{ event name = 'contentFooterNavigation' }{ /content } </ul> </nav> { /hascontent } </footer> { include file = 'footer' } If you compare this template to the one used in the ACP, you will recognize similar elements like the .paginationTop element, the p.info element if no people exist, and the .contentFooter element. Furthermore, we include a template called header before actually showing any of the page contents and terminate the template by including the footer template. Now, let us take a closer look at the differences: We do not explicitly create a .contentHeader element but simply assign the title to the contentTitle variable. The value of the assignment is simply the title of the page and a badge showing the number of listed people. The header template that we include later will handle correctly displaying the content header on its own based on the $contentTitle variable. Next, we create additional element for the HTML document\u2019s <head> element. In this case, we define the canonical link of the page and, because we are showing paginated content, add links to the previous and next page (if they exist). We want the page to be sortable but as we will not be using a table for listing the people like in the ACP, we are not able to place links to sort the people into the table head. Instead, usually a box is created in the sidebar on the right-hand side that contains select elements to determine sort field and sort order. The main part of the page is the listing of the people. We use a structure similar to the one used for displaying registered users. Here, for each person, we simply display a FontAwesome icon representing a person and show the person\u2019s full name relying on Person::__toString() . Additionally, like in the user list, we provide the initially empty ul.inlineList.commaSeparated and dl.plain.inlineDataList.small elements that can be filled by plugins using the templates events. userGroupOption.xml # We have already used the admin.content.canManagePeople permissions several times, now we need to install it using the userGroupOption package installation plugin : userGroupOption.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/userGroupOption.xsd\" > <import> <options> <option name= \"admin.content.canManagePeople\" > <categoryname> admin.content </categoryname> <optiontype> boolean </optiontype> <defaultvalue> 0 </defaultvalue> <admindefaultvalue> 1 </admindefaultvalue> <usersonly> 1 </usersonly> </option> </options> </import> </data> We use the existing admin.content user group option category for the permission as the people are \u201ccontent\u201d (similar the the ACP menu item). As the permission is for administrators only, we set defaultvalue to 0 and admindefaultvalue to 1 . This permission is only relevant for registered users so that it should not be visible when editing the guest user group. This is achieved by setting usersonly to 1 . package.xml # Lastly, we need to create the package.xml file. For more information about this kind of file, please refer to the package.xml page . package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.woltlab.wcf.people\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd\" > <packageinformation> <packagename> WoltLab Suite Core Tutorial: People </packagename> <packagedescription> Adds a simple management system for people as part of a tutorial to create packages. </packagedescription> <version> 5.4.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> WoltLab GmbH </author> <authorurl> http://www.woltlab.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"acpTemplate\" /> <instruction type= \"file\" /> <instruction type= \"database\" > acp/database/install_com.woltlab.wcf.people.php </instruction> <instruction type= \"template\" /> <instruction type= \"language\" /> <instruction type= \"acpMenu\" /> <instruction type= \"page\" /> <instruction type= \"menuItem\" /> <instruction type= \"userGroupOption\" /> </instructions> </package> As this is a package for WoltLab Suite Core 3, we need to require it using <requiredpackage> . We require the latest version (when writing this tutorial) 5.4.0 Alpha 1 . Additionally, we disallow installation of the package in the next major version 6.0 by excluding the 6.0.0 Alpha 1 version. The most important part are to installation instructions. First, we install the ACP templates, files and templates, create the database table and import the language item. Afterwards, the ACP menu items and the permission are added. Now comes the part of the instructions where the order of the instructions is crucial: In menuItem.xml , we refer to the com.woltlab.wcf.people.PersonList page that is delivered by page.xml . As the menu item package installation plugin validates the given page and throws an exception if the page does not exist, we need to install the page before the menu item! This concludes the first part of our tutorial series after which you now have a working simple package with which you can manage people in the ACP and show the visitors of your website a simple list of all created people in the front end. The complete source code of this part can be found on GitHub .","title":"Part 1"},{"location":"tutorial/series/part_1/#tutorial-series-part-1-base-structure","text":"In the first part of this tutorial series, we will lay out what the basic version of package should be able to do and how to implement these functions.","title":"Tutorial Series Part 1: Base Structure"},{"location":"tutorial/series/part_1/#package-functionality","text":"The package should provide the following possibilities/functions: Sortable list of all people in the ACP Ability to add, edit and delete people in the ACP Restrict the ability to add, edit and delete people (in short: manage people) in the ACP Sortable list of all people in the front end","title":"Package Functionality"},{"location":"tutorial/series/part_1/#used-components","text":"We will use the following package installation plugins: acpTemplate package installation plugin , acpMenu package installation plugin , database package installation plugin , file package installation plugin , language package installation plugin , menuItem package installation plugin , page package installation plugin , template package installation plugin , userGroupOption package installation plugin , use database objects , create pages and use templates .","title":"Used Components"},{"location":"tutorial/series/part_1/#package-structure","text":"The package will have the following file structure: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 \u251c\u2500\u2500 acpMenu.xml \u251c\u2500\u2500 acptemplates \u2502 \u251c\u2500\u2500 personAdd.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u251c\u2500\u2500 form \u2502 \u2502 \u2502 \u251c\u2500\u2500 PersonAddForm.class.php \u2502 \u2502 \u2502 \u2514\u2500\u2500 PersonEditForm.class.php \u2502 \u2502 \u2514\u2500\u2500 page \u2502 \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonList.class.php \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 menuItem.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u251c\u2500\u2500 templates \u2502 \u2514\u2500\u2500 personList.tpl \u2514\u2500\u2500 userGroupOption.xml","title":"Package Structure"},{"location":"tutorial/series/part_1/#person-modeling","text":"","title":"Person Modeling"},{"location":"tutorial/series/part_1/#database-table","text":"As the first step, we have to model the people we want to manage with this package. As this is only an introductory tutorial, we will keep things simple and only consider the first and last name of a person. Thus, the database table we will store the people in only contains three columns: personID is the unique numeric identifier of each person created, firstName contains the first name of the person, lastName contains the last name of the person. The first file for our package is the install_com.woltlab.wcf.people.php file used to create such a database table during package installation: files/acp/database/install_com.woltlab.wcf.people.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php use wcf\\system\\database\\table\\column\\NotNullVarchar255DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\ObjectIdDatabaseTableColumn ; use wcf\\system\\database\\table\\DatabaseTable ; use wcf\\system\\database\\table\\index\\DatabaseTablePrimaryIndex ; return [ DatabaseTable :: create ( 'wcf1_person' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'personID' ), NotNullVarchar255DatabaseTableColumn :: create ( 'firstName' ), NotNullVarchar255DatabaseTableColumn :: create ( 'lastName' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'personID' ]), ]), ];","title":"Database Table"},{"location":"tutorial/series/part_1/#database-object","text":"","title":"Database Object"},{"location":"tutorial/series/part_1/#person","text":"In our PHP code, each person will be represented by an object of the following class: files/lib/data/person/Person.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObject ; use wcf\\system\\request\\IRouteController ; /** * Represents a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @property-read int $personID unique id of the person * @property-read string $firstName first name of the person * @property-read string $lastName last name of the person */ class Person extends DatabaseObject implements IRouteController { /** * Returns the first and last name of the person if a person object is treated as a string. * * @return string */ public function __toString () { return $this -> getTitle (); } /** * @inheritDoc */ public function getTitle () { return $this -> firstName . ' ' . $this -> lastName ; } } The important thing here is that Person extends DatabaseObject . Additionally, we implement the IRouteController interface, which allows us to use Person objects to create links, and we implement PHP's magic __toString() method for convenience. For every database object, you need to implement three additional classes: an action class, an editor class and a list class.","title":"Person"},{"location":"tutorial/series/part_1/#personaction","text":"files/lib/data/person/PersonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <? php namespace wcf\\data\\person ; use wcf\\data\\AbstractDatabaseObjectAction ; /** * Executes person-related actions. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method Person create() * @method PersonEditor[] getObjects() * @method PersonEditor getSingleObject() */ class PersonAction extends AbstractDatabaseObjectAction { /** * @inheritDoc */ protected $permissionsDelete = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ protected $requireACP = [ 'delete' ]; } This implementation of AbstractDatabaseObjectAction is very basic and only sets the $permissionsDelete and $requireACP properties. This is done so that later on, when implementing the people list for the ACP, we can delete people simply via AJAX. $permissionsDelete has to be set to the permission needed in order to delete a person. We will later use the userGroupOption package installation plugin to create the admin.content.canManagePeople permission. $requireACP restricts deletion of people to the ACP.","title":"PersonAction"},{"location":"tutorial/series/part_1/#personeditor","text":"files/lib/data/person/PersonEditor.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObjectEditor ; /** * Provides functions to edit people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method static Person create(array $parameters = []) * @method Person getDecoratedObject() * @mixin Person */ class PersonEditor extends DatabaseObjectEditor { /** * @inheritDoc */ protected static $baseClass = Person :: class ; } This implementation of DatabaseObjectEditor fulfills the minimum requirement for a database object editor: setting the static $baseClass property to the database object class name.","title":"PersonEditor"},{"location":"tutorial/series/part_1/#personlist","text":"files/lib/data/person/PersonList.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObjectList ; /** * Represents a list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method Person current() * @method Person[] getObjects() * @method Person|null search($objectID) * @property Person[] $objects */ class PersonList extends DatabaseObjectList { } Due to the default implementation of DatabaseObjectList , our PersonList class just needs to extend it and everything else is either automatically set by the code of DatabaseObjectList or, in the case of properties and methods, provided by that class.","title":"PersonList"},{"location":"tutorial/series/part_1/#acp","text":"Next, we will take care of the controllers and views for the ACP. In total, we need three each: page to list people, form to add people, and form to edit people. Before we create the controllers and views, let us first create the menu items for the pages in the ACP menu.","title":"ACP"},{"location":"tutorial/series/part_1/#acp-menu","text":"We need to create three menu items: a \u201cparent\u201d menu item on the second level of the ACP menu item tree, a third level menu item for the people list page, and a fourth level menu item for the form to add new people. acpMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/acpMenu.xsd\" > <import> <acpmenuitem name= \"wcf.acp.menu.link.person\" > <parent> wcf.acp.menu.link.content </parent> </acpmenuitem> <acpmenuitem name= \"wcf.acp.menu.link.person.list\" > <controller> wcf\\acp\\page\\PersonListPage </controller> <parent> wcf.acp.menu.link.person </parent> <permissions> admin.content.canManagePeople </permissions> </acpmenuitem> <acpmenuitem name= \"wcf.acp.menu.link.person.add\" > <controller> wcf\\acp\\form\\PersonAddForm </controller> <parent> wcf.acp.menu.link.person.list </parent> <permissions> admin.content.canManagePeople </permissions> <icon> fa-plus </icon> </acpmenuitem> </import> </data> We choose wcf.acp.menu.link.content as the parent menu item for the first menu item wcf.acp.menu.link.person because the people we are managing is just one form of content. The fourth level menu item wcf.acp.menu.link.person.add will only be shown as an icon and thus needs an additional element icon which takes a FontAwesome icon class as value.","title":"ACP Menu"},{"location":"tutorial/series/part_1/#people-list","text":"To list the people in the ACP, we need a PersonListPage class and a personList template.","title":"People List"},{"location":"tutorial/series/part_1/#personlistpage","text":"files/lib/acp/page/PersonListPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\acp\\page ; use wcf\\data\\person\\PersonList ; use wcf\\page\\SortablePage ; /** * Shows the list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Page */ class PersonListPage extends SortablePage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.list' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectListClassName = PersonList :: class ; /** * @inheritDoc */ public $validSortFields = [ 'personID' , 'firstName' , 'lastName' ]; } As WoltLab Suite Core already provides a powerful default implementation of a sortable page, our work here is minimal: We need to set the active ACP menu item via the $activeMenuItem . $neededPermissions contains a list of permissions of which the user needs to have at least one in order to see the person list. We use the same permission for both the menu item and the page. The database object list class whose name is provided via $objectListClassName and that handles fetching the people from database is the PersonList class, which we have already created. To validate the sort field passed with the request, we set $validSortFields to the available database table columns.","title":"PersonListPage"},{"location":"tutorial/series/part_1/#personlisttpl","text":"acptemplates/personList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 { include file = 'header' pageTitle = 'wcf.acp.person.list' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person.list { /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonAdd' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.acp.menu.link.person.add { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { hascontent } <div class=\"paginationTop\"> { content }{ pages print = true assign = pagesLinks controller = \"PersonList\" link = \"pageNo=%d&sortField=$sortField&sortOrder=$sortOrder\" }{ /content } </div> { /hascontent } { if $objects | count } <div class=\"section tabularBox\"> <table class=\"table jsObjectActionContainer\" data-object-action-class-name=\"wcf\\data\\person\\PersonAction\"> <thead> <tr> <th class=\"columnID columnPersonID { if $sortField == 'personID' } active { @ $sortOrder }{ /if } \" colspan=\"2\"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=personID&sortOrder= { if $sortField == 'personID' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.global.objectID { /lang } </a></th> <th class=\"columnTitle columnFirstName { if $sortField == 'firstName' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=firstName&sortOrder= { if $sortField == 'firstName' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.firstName { /lang } </a></th> <th class=\"columnTitle columnLastName { if $sortField == 'lastName' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=lastName&sortOrder= { if $sortField == 'lastName' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.lastName { /lang } </a></th> { event name = 'columnHeads' } </tr> </thead> <tbody class=\"jsReloadPageWhenEmpty\"> { foreach from = $objects item = person } <tr class=\"jsObjectActionObject\" data-object-id=\" { @ $person -> getObjectID () } \"> <td class=\"columnIcon\"> <a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \" title=\" { lang } wcf.global.button.edit { /lang } \" class=\"jsTooltip\"><span class=\"icon icon16 fa-pencil\"></span></a> { objectAction action = \"delete\" objectTitle = $person -> getTitle () } { event name = 'rowButtons' } </td> <td class=\"columnID\"> { # $person -> personID } </td> <td class=\"columnTitle columnFirstName\"><a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \"> { $person -> firstName } </a></td> <td class=\"columnTitle columnLastName\"><a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \"> { $person -> lastName } </a></td> { event name = 'columns' } </tr> { /foreach } </tbody> </table> </div> <footer class=\"contentFooter\"> { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } <nav class=\"contentFooterNavigation\"> <ul> <li><a href=\" { link controller = 'PersonAdd' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.acp.menu.link.person.add { /lang } </span></a></li> { event name = 'contentFooterNavigation' } </ul> </nav> </footer> { else } <p class=\"info\"> { lang } wcf.global.noItems { /lang } </p> { /if } { include file = 'footer' } We will go piece by piece through the template code: We include the header template and set the page title wcf.acp.person.list . You have to include this template for every page! We set the content header and additional provide a button to create a new person in the content header navigation. As not all people are listed on the same page if many people have been created, we need a pagination for which we use the pages template plugin. The {hascontent}{content}{/content}{/hascontent} construct ensures the .paginationTop element is only shown if the pages template plugin has a return value, thus if a pagination is necessary. Now comes the main part of the page, the list of the people, which will only be displayed if any people exist. Otherwise, an info box is displayed using the generic wcf.global.noItems language item. The $objects template variable is automatically assigned by wcf\\page\\MultipleLinkPage and contains the PersonList object used to read the people from database. The table itself consists of a thead and a tbody element and is extendable with more columns using the template events columnHeads and columns . In general, every table should provide these events. The default structure of a table is used here so that the first column of the content rows contains icons to edit and to delete the row (and provides another standard event rowButtons ) and that the second column contains the ID of the person. The table can be sorted by clicking on the head of each column. The used variables $sortField and $sortOrder are automatically assigned to the template by SortablePage . The .contentFooter element is only shown if people exist as it basically repeats the .contentHeaderNavigation and .paginationTop element. The delete button for each person shown in the .columnIcon element relies on the global WoltLabSuite/Core/Ui/Object/Action module which only requires the jsObjectActionContainer CSS class in combination with the data-object-action-class-name attribute for the table element, the jsObjectActionObject CSS class for each person's tr element in combination with the data-object-id attribute, and lastly the delete button itself, which is created with the objectAction template plugin . The .jsReloadPageWhenEmpty CSS class on the tbody element ensures that once all persons on the page have been deleted, the page is reloaded. Lastly, the footer template is included that terminates the page. You also have to include this template for every page! Now, we have finished the page to manage the people so that we can move on to the forms with which we actually create and edit the people.","title":"personList.tpl"},{"location":"tutorial/series/part_1/#person-add-form","text":"Like the person list, the form to add new people requires a controller class and a template.","title":"Person Add Form"},{"location":"tutorial/series/part_1/#personaddform","text":"files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\TextFormField ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractFormBuilderForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * @inheritDoc */ public $formAction = 'create' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectActionClass = PersonAction :: class ; /** * @inheritDoc */ public $objectEditLinkController = PersonEditForm :: class ; /** * @inheritDoc */ protected function createForm () { parent :: createForm (); $this -> form -> appendChild ( FormContainer :: create ( 'data' ) -> label ( 'wcf.global.form.data' ) -> appendChildren ([ TextFormField :: create ( 'firstName' ) -> label ( 'wcf.person.firstName' ) -> required () -> autoFocus () -> maximumLength ( 255 ), TextFormField :: create ( 'lastName' ) -> label ( 'wcf.person.lastName' ) -> required () -> maximumLength ( 255 ), ]) ); } } The properties here consist of three types: the \u201chousekeeping\u201d properties $activeMenuItem and $neededPermissions , which fulfill the same roles as for PersonListPage , and the $objectEditLinkController property , which is used to generate a link to edit the newly created person after submitting the form, and finally $formAction and $objectActionClass required by the PHP form builder API used to generate the form. Because of using form builder, we only have to set up the two form fields for entering the first and last name, respectively: Each field is a simple single-line text field, thus we use TextFormField . The parameter of the create() method expects the id of the field/name of the database object property, which is firstName and lastName , respectively, here. The language item of the label shown in the ouput above the input field is set via the label() method. As both fields have to be filled out, required() is called, and the maximum length is set via maximumLength() . Lastly, to make it easier to fill out the form more quickly, the first field is auto-focused by calling autoFocus() .","title":"PersonAddForm"},{"location":"tutorial/series/part_1/#personaddtpl","text":"acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { @ $form -> getHtml () } { include file = 'footer' } We will now only concentrate on the new parts compared to personList.tpl : We use the $action variable to distinguish between the languages items used for adding a person and for creating a person. Because of form builder, we only have to call {@$form->getHtml()} to generate all relevant output for the form.","title":"personAdd.tpl"},{"location":"tutorial/series/part_1/#person-edit-form","text":"As mentioned before, for the form to edit existing people, we only need a new controller as the template has already been implemented in a way that it handles both, adding and editing.","title":"Person Edit Form"},{"location":"tutorial/series/part_1/#personeditform","text":"files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\system\\exception\\IllegalLinkException ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * @inheritDoc */ public $formAction = 'update' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> formObject = new Person ( $_REQUEST [ 'id' ]); if ( ! $this -> formObject -> getObjectID ()) { throw new IllegalLinkException (); } } } } In general, edit forms extend the associated add form so that the code to read and to validate the input data is simply inherited. After setting a different active menu item, we have to change the value of $formAction because this form, in contrast to PersonAddForm , does not create but update existing persons. As we rely on form builder, the only thing necessary in this controller is to read and validate the edit object, i.e. the edited person, which is done in readParameters() .","title":"PersonEditForm"},{"location":"tutorial/series/part_1/#frontend","text":"For the front end, that means the part with which the visitors of a website interact, we want to implement a simple sortable page that lists the people. This page should also be directly linked in the main menu.","title":"Frontend"},{"location":"tutorial/series/part_1/#pagexml","text":"First, let us register the page with the system because every front end page or form needs to be explicitly registered using the page package installation plugin : page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.people.PersonList\" > <pageType> system </pageType> <controller> wcf\\page\\PersonListPage </controller> <name language= \"de\" > Personen-Liste </name> <name language= \"en\" > Person List </name> <content language= \"de\" > <title> Personen </title> </content> <content language= \"en\" > <title> People </title> </content> </page> </import> </data> For more information about what each of the elements means, please refer to the page package installation plugin page .","title":"page.xml"},{"location":"tutorial/series/part_1/#menuitemxml","text":"Next, we register the menu item using the menuItem package installation plugin : menuItem.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/menuItem.xsd\" > <import> <item identifier= \"com.woltlab.wcf.people.PersonList\" > <menu> com.woltlab.wcf.MainMenu </menu> <title language= \"de\" > Personen </title> <title language= \"en\" > People </title> <page> com.woltlab.wcf.people.PersonList </page> </item> </import> </data> Here, the import parts are that we register the menu item for the main menu com.woltlab.wcf.MainMenu and link the menu item with the page com.woltlab.wcf.people.PersonList , which we just registered.","title":"menuItem.xml"},{"location":"tutorial/series/part_1/#people-list_1","text":"As in the ACP, we need a controller and a template. You might notice that both the controller\u2019s (unqualified) class name and the template name are the same for the ACP and the front end. This is no problem because the qualified names of the classes differ and the files are stored in different directories and because the templates are installed by different package installation plugins and are also stored in different directories.","title":"People List"},{"location":"tutorial/series/part_1/#personlistpage_1","text":"files/lib/page/PersonListPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <? php namespace wcf\\page ; use wcf\\data\\person\\PersonList ; /** * Shows the list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Page */ class PersonListPage extends SortablePage { /** * @inheritDoc */ public $defaultSortField = 'lastName' ; /** * @inheritDoc */ public $objectListClassName = PersonList :: class ; /** * @inheritDoc */ public $validSortFields = [ 'personID' , 'firstName' , 'lastName' ]; } This class is almost identical to the ACP version. In the front end, we do not need to set the active menu item manually because the system determines the active menu item automatically based on the requested page. Furthermore, $neededPermissions has not been set because in the front end, users do not need any special permission to access the page. In the front end, we explicitly set the $defaultSortField so that the people listed on the page are sorted by their last name (in ascending order) by default.","title":"PersonListPage"},{"location":"tutorial/series/part_1/#personlisttpl_1","text":"templates/personList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 { capture assign = 'contentTitle' }{ lang } wcf.person.list { /lang } <span class=\"badge\"> { # $items } </span> { /capture } { capture assign = 'headContent' } { if $pageNo < $pages } <link rel=\"next\" href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo + 1 }{ /link } \"> { /if } { if $pageNo > 1 } <link rel=\"prev\" href=\" { link controller = 'PersonList' }{ if $pageNo > 2 } pageNo= { @ $pageNo - 1 }{ /if }{ /link } \"> { /if } <link rel=\"canonical\" href=\" { link controller = 'PersonList' }{ if $pageNo > 1 } pageNo= { @ $pageNo }{ /if }{ /link } \"> { /capture } { capture assign = 'sidebarRight' } <section class=\"box\"> <form method=\"post\" action=\" { link controller = 'PersonList' }{ /link } \"> <h2 class=\"boxTitle\"> { lang } wcf.global.sorting { /lang } </h2> <div class=\"boxContent\"> <dl> <dt></dt> <dd> <select id=\"sortField\" name=\"sortField\"> <option value=\"firstName\" { if $sortField == 'firstName' } selected { /if } > { lang } wcf.person.firstName { /lang } </option> <option value=\"lastName\" { if $sortField == 'lastName' } selected { /if } > { lang } wcf.person.lastName { /lang } </option> { event name = 'sortField' } </select> <select name=\"sortOrder\"> <option value=\"ASC\" { if $sortOrder == 'ASC' } selected { /if } > { lang } wcf.global.sortOrder.ascending { /lang } </option> <option value=\"DESC\" { if $sortOrder == 'DESC' } selected { /if } > { lang } wcf.global.sortOrder.descending { /lang } </option> </select> </dd> </dl> <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> </div> </div> </form> </section> { /capture } { include file = 'header' } { hascontent } <div class=\"paginationTop\"> { content } { pages print = true assign = pagesLinks controller = 'PersonList' link = \"pageNo=%d&sortField=$sortField&sortOrder=$sortOrder\" } { /content } </div> { /hascontent } { if $items } <div class=\"section sectionContainerList\"> <ol class=\"containerList personList\"> { foreach from = $objects item = person } <li> <div class=\"box48\"> <span class=\"icon icon48 fa-user\"></span> <div class=\"details personInformation\"> <div class=\"containerHeadline\"> <h3> { $person } </h3> </div> { hascontent } <ul class=\"inlineList commaSeparated\"> { content }{ event name = 'personData' }{ /content } </ul> { /hascontent } { hascontent } <dl class=\"plain inlineDataList small\"> { content }{ event name = 'personStatistics' }{ /content } </dl> { /hascontent } </div> </div> </li> { /foreach } </ol> </div> { else } <p class=\"info\"> { lang } wcf.global.noItems { /lang } </p> { /if } <footer class=\"contentFooter\"> { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } { hascontent } <nav class=\"contentFooterNavigation\"> <ul> { content }{ event name = 'contentFooterNavigation' }{ /content } </ul> </nav> { /hascontent } </footer> { include file = 'footer' } If you compare this template to the one used in the ACP, you will recognize similar elements like the .paginationTop element, the p.info element if no people exist, and the .contentFooter element. Furthermore, we include a template called header before actually showing any of the page contents and terminate the template by including the footer template. Now, let us take a closer look at the differences: We do not explicitly create a .contentHeader element but simply assign the title to the contentTitle variable. The value of the assignment is simply the title of the page and a badge showing the number of listed people. The header template that we include later will handle correctly displaying the content header on its own based on the $contentTitle variable. Next, we create additional element for the HTML document\u2019s <head> element. In this case, we define the canonical link of the page and, because we are showing paginated content, add links to the previous and next page (if they exist). We want the page to be sortable but as we will not be using a table for listing the people like in the ACP, we are not able to place links to sort the people into the table head. Instead, usually a box is created in the sidebar on the right-hand side that contains select elements to determine sort field and sort order. The main part of the page is the listing of the people. We use a structure similar to the one used for displaying registered users. Here, for each person, we simply display a FontAwesome icon representing a person and show the person\u2019s full name relying on Person::__toString() . Additionally, like in the user list, we provide the initially empty ul.inlineList.commaSeparated and dl.plain.inlineDataList.small elements that can be filled by plugins using the templates events.","title":"personList.tpl"},{"location":"tutorial/series/part_1/#usergroupoptionxml","text":"We have already used the admin.content.canManagePeople permissions several times, now we need to install it using the userGroupOption package installation plugin : userGroupOption.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/userGroupOption.xsd\" > <import> <options> <option name= \"admin.content.canManagePeople\" > <categoryname> admin.content </categoryname> <optiontype> boolean </optiontype> <defaultvalue> 0 </defaultvalue> <admindefaultvalue> 1 </admindefaultvalue> <usersonly> 1 </usersonly> </option> </options> </import> </data> We use the existing admin.content user group option category for the permission as the people are \u201ccontent\u201d (similar the the ACP menu item). As the permission is for administrators only, we set defaultvalue to 0 and admindefaultvalue to 1 . This permission is only relevant for registered users so that it should not be visible when editing the guest user group. This is achieved by setting usersonly to 1 .","title":"userGroupOption.xml"},{"location":"tutorial/series/part_1/#packagexml","text":"Lastly, we need to create the package.xml file. For more information about this kind of file, please refer to the package.xml page . package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.woltlab.wcf.people\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd\" > <packageinformation> <packagename> WoltLab Suite Core Tutorial: People </packagename> <packagedescription> Adds a simple management system for people as part of a tutorial to create packages. </packagedescription> <version> 5.4.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> WoltLab GmbH </author> <authorurl> http://www.woltlab.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"acpTemplate\" /> <instruction type= \"file\" /> <instruction type= \"database\" > acp/database/install_com.woltlab.wcf.people.php </instruction> <instruction type= \"template\" /> <instruction type= \"language\" /> <instruction type= \"acpMenu\" /> <instruction type= \"page\" /> <instruction type= \"menuItem\" /> <instruction type= \"userGroupOption\" /> </instructions> </package> As this is a package for WoltLab Suite Core 3, we need to require it using <requiredpackage> . We require the latest version (when writing this tutorial) 5.4.0 Alpha 1 . Additionally, we disallow installation of the package in the next major version 6.0 by excluding the 6.0.0 Alpha 1 version. The most important part are to installation instructions. First, we install the ACP templates, files and templates, create the database table and import the language item. Afterwards, the ACP menu items and the permission are added. Now comes the part of the instructions where the order of the instructions is crucial: In menuItem.xml , we refer to the com.woltlab.wcf.people.PersonList page that is delivered by page.xml . As the menu item package installation plugin validates the given page and throws an exception if the page does not exist, we need to install the page before the menu item! This concludes the first part of our tutorial series after which you now have a working simple package with which you can manage people in the ACP and show the visitors of your website a simple list of all created people in the front end. The complete source code of this part can be found on GitHub .","title":"package.xml"},{"location":"tutorial/series/part_2/","text":"Part 2: Event and Template Listeners # In the first part of this tutorial series, we have created the base structure of our people management package. In further parts, we will use the package of the first part as a basis to directly add new features. In order to explain how event listeners and template works, however, we will not directly adding a new feature to the package by altering it in this part, but we will assume that somebody else created the package and that we want to extend it the \u201ccorrect\u201d way by creating a plugin. The goal of the small plugin that will be created in this part is to add the birthday of the managed people. As in the first part, we will not bother with careful validation of the entered date but just make sure that it is a valid date. Package Functionality # The package should provide the following possibilities/functions: List person\u2019s birthday (if set) in people list in the ACP Sort people list by birthday in the ACP Add or remove birthday when adding or editing person List person\u2019s birthday (if set) in people list in the front end Sort people list by birthday in the front end Used Components # We will use the following package installation plugins: database package installation plugin , eventListener package installation plugin , file package installation plugin , language package installation plugin , template package installation plugin , templateListener package installation plugin . For more information about the event system, please refer to the dedicated page on events . Package Structure # The package will have the following file structure: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 \u251c\u2500\u2500 eventListener.xml \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.birthday.php \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 system \u2502 \u2514\u2500\u2500 event \u2502 \u2514\u2500\u2500 listener \u2502 \u251c\u2500\u2500 BirthdayPersonAddFormListener.class.php \u2502 \u2514\u2500\u2500 BirthdaySortFieldPersonListPageListener.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 templateListener.xml \u2514\u2500\u2500 templates \u251c\u2500\u2500 __personListBirthday.tpl \u2514\u2500\u2500 __personListBirthdaySortField.tpl Extending Person Model # The existing model of a person only contains the person\u2019s first name and their last name (in additional to the id used to identify created people). To add the birthday to the model, we need to create an additional database table column using the database package installation plugin : files/acp/database/install_com.woltlab.wcf.people.birthday.php 1 2 3 4 5 6 7 8 9 10 11 <? php use wcf \\ system \\ database \\ table \\ column \\ DateDatabaseTableColumn ; use wcf \\ system \\ database \\ table \\ PartialDatabaseTable ; return [ PartialDatabaseTable :: create ( 'wcf1_person' ) -> columns ([ DateDatabaseTableColumn :: create ( 'birthday' ), ]), ]; If we have a Person object , this new property can be accessed the same way as the personID property, the firstName property, or the lastName property from the base package: $person->birthday . Setting Birthday in ACP # To set the birthday of a person, we only have to add another form field with an event listener: files/lib/system/event/listener/BirthdayPersonAddFormListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\form\\PersonAddForm ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\DateFormField ; /** * Handles setting the birthday when adding and editing people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class BirthdayPersonAddFormListener extends AbstractEventListener { /** * @see AbstractFormBuilderForm::createForm() */ protected function onCreateForm ( PersonAddForm $form ) : void { /** @var FormContainer $dataContainer */ $dataContainer = $form -> form -> getNodeById ( 'data' ); $dataContainer -> appendChild ( DateFormField :: create ( 'birthday' ) -> label ( 'wcf.person.birthday' ) -> saveValueFormat ( 'Y-m-d' ) -> nullable () ); } } registered via 1 2 3 4 5 6 7 <eventlistener name= \"createForm@wcf\\acp\\form\\PersonAddForm\" > <environment> admin </environment> <eventclassname> wcf\\acp\\form\\PersonAddForm </eventclassname> <eventname> createForm </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdayPersonAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> in eventListener.xml , see below . As BirthdayPersonAddFormListener extends AbstractEventListener and as the name of relevant event is createForm , AbstractEventListener internally automatically calls onCreateForm() with the event object as the parameter. It is important to set <inherit>1</inherit> so that the event listener is also executed for PersonEditForm , which extends PersonAddForm . The language item wcf.person.birthday used in the label is the only new one for this package: language/de.xml 1 2 3 4 5 6 <? xml version = \"1.0\" encoding = \"UTF-8\" ?> < language xmlns = \"http://www.woltlab.com\" xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi : schemaLocation = \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode = \"de\" > < category name = \"wcf.person\" > < item name = \"wcf.person.birthday\" ><! [ CDATA [ Geburtstag ]] ></ item > </ category > </ language > language/en.xml 1 2 3 4 5 6 <? xml version = \"1.0\" encoding = \"UTF-8\" ?> < language xmlns = \"http://www.woltlab.com\" xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi : schemaLocation = \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode = \"en\" > < category name = \"wcf.person\" > < item name = \"wcf.person.birthday\" ><! [ CDATA [ Birthday ]] ></ item > </ category > </ language > Adding Birthday Table Column in ACP # To add a birthday column to the person list page in the ACP, we need three parts: an event listener that makes the birthday database table column a valid sort field, a template listener that adds the birthday column to the table\u2019s head, and a template listener that adds the birthday column to the table\u2019s rows. The first part is a very simple class: files/lib/system/event/listener/BirthdaySortFieldPersonListPageListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? php namespace wcf\\system\\event\\listener ; use wcf\\page\\SortablePage ; /** * Makes people's birthday a valid sort field in the ACP and the front end. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class BirthdaySortFieldPersonListPageListener extends AbstractEventListener { /** * @see SortablePage::validateSortField() */ public function onValidateSortField ( SortablePage $page ) : void { $page -> validSortFields [] = 'birthday' ; } } We use SortablePage as a type hint instead of wcf\\acp\\page\\PersonListPage because we will be using the same event listener class in the front end to also allow sorting that list by birthday. As the relevant template codes are only one line each, we will simply put them directly in the templateListener.xml file that will be shown later on . The code for the table head is similar to the other th elements: 1 <th class=\"columnDate columnBirthday { if $sortField == 'birthday' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=birthday&sortOrder= { if $sortField == 'birthday' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.birthday { /lang } </a></th> For the table body\u2019s column, we need to make sure that the birthday is only show if it is actually set: 1 <td class=\"columnDate columnBirthday\"> { if $person -> birthday }{ @ $person -> birthday | strtotime | date }{ /if } </td> Adding Birthday in Front End # In the front end, we also want to make the list sortable by birthday and show the birthday as part of each person\u2019s \u201cstatistics\u201d. To add the birthday as a valid sort field, we use BirthdaySortFieldPersonListPageListener just as in the ACP. In the front end, we will now use a template ( __personListBirthdaySortField.tpl ) instead of a directly putting the template code in the templateListener.xml file: templates/__personListBirthdaySortField.tpl 1 <option value=\"birthday\" { if $sortField == 'birthday' } selected { /if } > { lang } wcf.person.birthday { /lang } </option> You might have noticed the two underscores at the beginning of the template file. For templates that are included via template listeners, this is the naming convention we use. Putting the template code into a file has the advantage that in the administrator is able to edit the code directly via a custom template group, even though in this case this might not be very probable. To show the birthday, we use the following template code for the personStatistics template event, which again makes sure that the birthday is only shown if it is actually set: templates/__personListBirthday.tpl 1 2 3 4 { if $person -> birthday } <dt> { lang } wcf.person.birthday { /lang } </dt> <dd> { @ $person -> birthday | strtotime | date } </dd> { /if } templateListener.xml # The following code shows the templateListener.xml file used to install all mentioned template listeners: templateListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/tornado/5.4/templateListener.xsd\" > <import> <!-- admin --> <templatelistener name= \"personListBirthdayColumnHead\" > <eventname> columnHeads </eventname> <environment> admin </environment> <templatecode> <![CDATA[<th class=\"columnDate columnBirthday{if $sortField == 'birthday'} active {@$sortOrder}{/if}\"><a href=\"{link controller='PersonList'}pageNo={@$pageNo}&sortField=birthday&sortOrder={if $sortField == 'birthday' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}\">{lang}wcf.person.birthday{/lang}</a></th>]]> </templatecode> <templatename> personList </templatename> </templatelistener> <templatelistener name= \"personListBirthdayColumn\" > <eventname> columns </eventname> <environment> admin </environment> <templatecode> <![CDATA[<td class=\"columnDate columnBirthday\">{if $person->birthday}{@$person->birthday|strtotime|date}{/if}</td>]]> </templatecode> <templatename> personList </templatename> </templatelistener> <!-- /admin --> <!-- user --> <templatelistener name= \"personListBirthday\" > <eventname> personStatistics </eventname> <environment> user </environment> <templatecode> <![CDATA[{include file='__personListBirthday'}]]> </templatecode> <templatename> personList </templatename> </templatelistener> <templatelistener name= \"personListBirthdaySortField\" > <eventname> sortField </eventname> <environment> user </environment> <templatecode> <![CDATA[{include file='__personListBirthdaySortField'}]]> </templatecode> <templatename> personList </templatename> </templatelistener> <!-- /user --> </import> </data> In cases where a template is used, we simply use the include syntax to load the template. eventListener.xml # There are two event listeners that make birthday a valid sort field in the ACP and the front end, respectively, and the third event listener takes care of setting the birthday. eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd\" > <import> <!-- admin --> <eventlistener name= \"validateSortField@wcf\\acp\\page\\PersonListPage\" > <environment> admin </environment> <eventclassname> wcf\\acp\\page\\PersonListPage </eventclassname> <eventname> validateSortField </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdaySortFieldPersonListPageListener </listenerclassname> </eventlistener> <eventlistener name= \"createForm@wcf\\acp\\form\\PersonAddForm\" > <environment> admin </environment> <eventclassname> wcf\\acp\\form\\PersonAddForm </eventclassname> <eventname> createForm </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdayPersonAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> <!-- /admin --> <!-- user --> <eventlistener name= \"validateSortField@wcf\\page\\PersonListPage\" > <environment> user </environment> <eventclassname> wcf\\page\\PersonListPage </eventclassname> <eventname> validateSortField </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdaySortFieldPersonListPageListener </listenerclassname> </eventlistener> <!-- /user --> </import> </data> package.xml # The only relevant difference between the package.xml file of the base page from part 1 and the package.xml file of this package is that this package requires the base package com.woltlab.wcf.people (see <requiredpackages> ): package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.woltlab.wcf.people.birthday\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd\" > <packageinformation> <packagename> WoltLab Suite Core Tutorial: People (Birthday) </packagename> <packagedescription> Adds a birthday field to the people management system as part of a tutorial to create packages. </packagedescription> <version> 5.4.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> WoltLab GmbH </author> <authorurl> http://www.woltlab.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> <requiredpackage minversion= \"5.4.0\" > com.woltlab.wcf.people </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"database\" > acp/database/install_com.woltlab.wcf.people.birthday.php </instruction> <instruction type= \"template\" /> <instruction type= \"language\" /> <instruction type= \"eventListener\" /> <instruction type= \"templateListener\" /> </instructions> </package> This concludes the second part of our tutorial series after which you now have extended the base package using event listeners and template listeners that allow you to enter the birthday of the people. The complete source code of this part can be found on GitHub .","title":"Part 2"},{"location":"tutorial/series/part_2/#part-2-event-and-template-listeners","text":"In the first part of this tutorial series, we have created the base structure of our people management package. In further parts, we will use the package of the first part as a basis to directly add new features. In order to explain how event listeners and template works, however, we will not directly adding a new feature to the package by altering it in this part, but we will assume that somebody else created the package and that we want to extend it the \u201ccorrect\u201d way by creating a plugin. The goal of the small plugin that will be created in this part is to add the birthday of the managed people. As in the first part, we will not bother with careful validation of the entered date but just make sure that it is a valid date.","title":"Part 2: Event and Template Listeners"},{"location":"tutorial/series/part_2/#package-functionality","text":"The package should provide the following possibilities/functions: List person\u2019s birthday (if set) in people list in the ACP Sort people list by birthday in the ACP Add or remove birthday when adding or editing person List person\u2019s birthday (if set) in people list in the front end Sort people list by birthday in the front end","title":"Package Functionality"},{"location":"tutorial/series/part_2/#used-components","text":"We will use the following package installation plugins: database package installation plugin , eventListener package installation plugin , file package installation plugin , language package installation plugin , template package installation plugin , templateListener package installation plugin . For more information about the event system, please refer to the dedicated page on events .","title":"Used Components"},{"location":"tutorial/series/part_2/#package-structure","text":"The package will have the following file structure: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 \u251c\u2500\u2500 eventListener.xml \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.birthday.php \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 system \u2502 \u2514\u2500\u2500 event \u2502 \u2514\u2500\u2500 listener \u2502 \u251c\u2500\u2500 BirthdayPersonAddFormListener.class.php \u2502 \u2514\u2500\u2500 BirthdaySortFieldPersonListPageListener.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 templateListener.xml \u2514\u2500\u2500 templates \u251c\u2500\u2500 __personListBirthday.tpl \u2514\u2500\u2500 __personListBirthdaySortField.tpl","title":"Package Structure"},{"location":"tutorial/series/part_2/#extending-person-model","text":"The existing model of a person only contains the person\u2019s first name and their last name (in additional to the id used to identify created people). To add the birthday to the model, we need to create an additional database table column using the database package installation plugin : files/acp/database/install_com.woltlab.wcf.people.birthday.php 1 2 3 4 5 6 7 8 9 10 11 <? php use wcf \\ system \\ database \\ table \\ column \\ DateDatabaseTableColumn ; use wcf \\ system \\ database \\ table \\ PartialDatabaseTable ; return [ PartialDatabaseTable :: create ( 'wcf1_person' ) -> columns ([ DateDatabaseTableColumn :: create ( 'birthday' ), ]), ]; If we have a Person object , this new property can be accessed the same way as the personID property, the firstName property, or the lastName property from the base package: $person->birthday .","title":"Extending Person Model"},{"location":"tutorial/series/part_2/#setting-birthday-in-acp","text":"To set the birthday of a person, we only have to add another form field with an event listener: files/lib/system/event/listener/BirthdayPersonAddFormListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\form\\PersonAddForm ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\DateFormField ; /** * Handles setting the birthday when adding and editing people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class BirthdayPersonAddFormListener extends AbstractEventListener { /** * @see AbstractFormBuilderForm::createForm() */ protected function onCreateForm ( PersonAddForm $form ) : void { /** @var FormContainer $dataContainer */ $dataContainer = $form -> form -> getNodeById ( 'data' ); $dataContainer -> appendChild ( DateFormField :: create ( 'birthday' ) -> label ( 'wcf.person.birthday' ) -> saveValueFormat ( 'Y-m-d' ) -> nullable () ); } } registered via 1 2 3 4 5 6 7 <eventlistener name= \"createForm@wcf\\acp\\form\\PersonAddForm\" > <environment> admin </environment> <eventclassname> wcf\\acp\\form\\PersonAddForm </eventclassname> <eventname> createForm </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdayPersonAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> in eventListener.xml , see below . As BirthdayPersonAddFormListener extends AbstractEventListener and as the name of relevant event is createForm , AbstractEventListener internally automatically calls onCreateForm() with the event object as the parameter. It is important to set <inherit>1</inherit> so that the event listener is also executed for PersonEditForm , which extends PersonAddForm . The language item wcf.person.birthday used in the label is the only new one for this package: language/de.xml 1 2 3 4 5 6 <? xml version = \"1.0\" encoding = \"UTF-8\" ?> < language xmlns = \"http://www.woltlab.com\" xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi : schemaLocation = \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode = \"de\" > < category name = \"wcf.person\" > < item name = \"wcf.person.birthday\" ><! [ CDATA [ Geburtstag ]] ></ item > </ category > </ language > language/en.xml 1 2 3 4 5 6 <? xml version = \"1.0\" encoding = \"UTF-8\" ?> < language xmlns = \"http://www.woltlab.com\" xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi : schemaLocation = \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode = \"en\" > < category name = \"wcf.person\" > < item name = \"wcf.person.birthday\" ><! [ CDATA [ Birthday ]] ></ item > </ category > </ language >","title":"Setting Birthday in ACP"},{"location":"tutorial/series/part_2/#adding-birthday-table-column-in-acp","text":"To add a birthday column to the person list page in the ACP, we need three parts: an event listener that makes the birthday database table column a valid sort field, a template listener that adds the birthday column to the table\u2019s head, and a template listener that adds the birthday column to the table\u2019s rows. The first part is a very simple class: files/lib/system/event/listener/BirthdaySortFieldPersonListPageListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? php namespace wcf\\system\\event\\listener ; use wcf\\page\\SortablePage ; /** * Makes people's birthday a valid sort field in the ACP and the front end. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class BirthdaySortFieldPersonListPageListener extends AbstractEventListener { /** * @see SortablePage::validateSortField() */ public function onValidateSortField ( SortablePage $page ) : void { $page -> validSortFields [] = 'birthday' ; } } We use SortablePage as a type hint instead of wcf\\acp\\page\\PersonListPage because we will be using the same event listener class in the front end to also allow sorting that list by birthday. As the relevant template codes are only one line each, we will simply put them directly in the templateListener.xml file that will be shown later on . The code for the table head is similar to the other th elements: 1 <th class=\"columnDate columnBirthday { if $sortField == 'birthday' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=birthday&sortOrder= { if $sortField == 'birthday' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.birthday { /lang } </a></th> For the table body\u2019s column, we need to make sure that the birthday is only show if it is actually set: 1 <td class=\"columnDate columnBirthday\"> { if $person -> birthday }{ @ $person -> birthday | strtotime | date }{ /if } </td>","title":"Adding Birthday Table Column in ACP"},{"location":"tutorial/series/part_2/#adding-birthday-in-front-end","text":"In the front end, we also want to make the list sortable by birthday and show the birthday as part of each person\u2019s \u201cstatistics\u201d. To add the birthday as a valid sort field, we use BirthdaySortFieldPersonListPageListener just as in the ACP. In the front end, we will now use a template ( __personListBirthdaySortField.tpl ) instead of a directly putting the template code in the templateListener.xml file: templates/__personListBirthdaySortField.tpl 1 <option value=\"birthday\" { if $sortField == 'birthday' } selected { /if } > { lang } wcf.person.birthday { /lang } </option> You might have noticed the two underscores at the beginning of the template file. For templates that are included via template listeners, this is the naming convention we use. Putting the template code into a file has the advantage that in the administrator is able to edit the code directly via a custom template group, even though in this case this might not be very probable. To show the birthday, we use the following template code for the personStatistics template event, which again makes sure that the birthday is only shown if it is actually set: templates/__personListBirthday.tpl 1 2 3 4 { if $person -> birthday } <dt> { lang } wcf.person.birthday { /lang } </dt> <dd> { @ $person -> birthday | strtotime | date } </dd> { /if }","title":"Adding Birthday in Front End"},{"location":"tutorial/series/part_2/#templatelistenerxml","text":"The following code shows the templateListener.xml file used to install all mentioned template listeners: templateListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/tornado/5.4/templateListener.xsd\" > <import> <!-- admin --> <templatelistener name= \"personListBirthdayColumnHead\" > <eventname> columnHeads </eventname> <environment> admin </environment> <templatecode> <![CDATA[<th class=\"columnDate columnBirthday{if $sortField == 'birthday'} active {@$sortOrder}{/if}\"><a href=\"{link controller='PersonList'}pageNo={@$pageNo}&sortField=birthday&sortOrder={if $sortField == 'birthday' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}\">{lang}wcf.person.birthday{/lang}</a></th>]]> </templatecode> <templatename> personList </templatename> </templatelistener> <templatelistener name= \"personListBirthdayColumn\" > <eventname> columns </eventname> <environment> admin </environment> <templatecode> <![CDATA[<td class=\"columnDate columnBirthday\">{if $person->birthday}{@$person->birthday|strtotime|date}{/if}</td>]]> </templatecode> <templatename> personList </templatename> </templatelistener> <!-- /admin --> <!-- user --> <templatelistener name= \"personListBirthday\" > <eventname> personStatistics </eventname> <environment> user </environment> <templatecode> <![CDATA[{include file='__personListBirthday'}]]> </templatecode> <templatename> personList </templatename> </templatelistener> <templatelistener name= \"personListBirthdaySortField\" > <eventname> sortField </eventname> <environment> user </environment> <templatecode> <![CDATA[{include file='__personListBirthdaySortField'}]]> </templatecode> <templatename> personList </templatename> </templatelistener> <!-- /user --> </import> </data> In cases where a template is used, we simply use the include syntax to load the template.","title":"templateListener.xml"},{"location":"tutorial/series/part_2/#eventlistenerxml","text":"There are two event listeners that make birthday a valid sort field in the ACP and the front end, respectively, and the third event listener takes care of setting the birthday. eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd\" > <import> <!-- admin --> <eventlistener name= \"validateSortField@wcf\\acp\\page\\PersonListPage\" > <environment> admin </environment> <eventclassname> wcf\\acp\\page\\PersonListPage </eventclassname> <eventname> validateSortField </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdaySortFieldPersonListPageListener </listenerclassname> </eventlistener> <eventlistener name= \"createForm@wcf\\acp\\form\\PersonAddForm\" > <environment> admin </environment> <eventclassname> wcf\\acp\\form\\PersonAddForm </eventclassname> <eventname> createForm </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdayPersonAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> <!-- /admin --> <!-- user --> <eventlistener name= \"validateSortField@wcf\\page\\PersonListPage\" > <environment> user </environment> <eventclassname> wcf\\page\\PersonListPage </eventclassname> <eventname> validateSortField </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdaySortFieldPersonListPageListener </listenerclassname> </eventlistener> <!-- /user --> </import> </data>","title":"eventListener.xml"},{"location":"tutorial/series/part_2/#packagexml","text":"The only relevant difference between the package.xml file of the base page from part 1 and the package.xml file of this package is that this package requires the base package com.woltlab.wcf.people (see <requiredpackages> ): package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.woltlab.wcf.people.birthday\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd\" > <packageinformation> <packagename> WoltLab Suite Core Tutorial: People (Birthday) </packagename> <packagedescription> Adds a birthday field to the people management system as part of a tutorial to create packages. </packagedescription> <version> 5.4.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> WoltLab GmbH </author> <authorurl> http://www.woltlab.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> <requiredpackage minversion= \"5.4.0\" > com.woltlab.wcf.people </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"database\" > acp/database/install_com.woltlab.wcf.people.birthday.php </instruction> <instruction type= \"template\" /> <instruction type= \"language\" /> <instruction type= \"eventListener\" /> <instruction type= \"templateListener\" /> </instructions> </package> This concludes the second part of our tutorial series after which you now have extended the base package using event listeners and template listeners that allow you to enter the birthday of the people. The complete source code of this part can be found on GitHub .","title":"package.xml"},{"location":"tutorial/series/part_3/","text":"Part 3: Person Page and Comments # In this part of our tutorial series, we will add a new front end page to our package that is dedicated to each person and shows their personal details. To make good use of this new page and introduce a new API of WoltLab Suite, we will add the opportunity for users to comment on the person using WoltLab Suite\u2019s reusable comment functionality. Package Functionality # In addition to the existing functions from part 1 , the package will provide the following possibilities/functions after this part of the tutorial: Details page for each person linked in the front end person list Comment on people on their respective page (can be disabled per person) User online location for person details page with name and link to person details page Create menu items linking to specific person details pages Used Components # In addition to the components used in part 1 , we will use the objectType package installation plugin , use the comment API , create a runtime cache , and create a page handler. Package Structure # The complete package will have the following file structure (including the files from part 1 ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 \u251c\u2500\u2500 acpMenu.xml \u251c\u2500\u2500 acptemplates \u2502 \u251c\u2500\u2500 personAdd.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u251c\u2500\u2500 form \u2502 \u2502 \u2502 \u251c\u2500\u2500 PersonAddForm.class.php \u2502 \u2502 \u2502 \u2514\u2500\u2500 PersonEditForm.class.php \u2502 \u2502 \u2514\u2500\u2500 page \u2502 \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonList.class.php \u2502 \u251c\u2500\u2500 page \u2502 \u2502 \u251c\u2500\u2500 PersonListPage.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonPage.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 cache \u2502 \u2502 \u2514\u2500\u2500 runtime \u2502 \u2502 \u2514\u2500\u2500 PersonRuntimeCache.class.php \u2502 \u251c\u2500\u2500 comment \u2502 \u2502 \u2514\u2500\u2500 manager \u2502 \u2502 \u2514\u2500\u2500 PersonCommentManager.class.php \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 handler \u2502 \u2514\u2500\u2500 PersonPageHandler.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 menuItem.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u251c\u2500\u2500 templates \u2502 \u251c\u2500\u2500 person.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u2514\u2500\u2500 userGroupOption.xml We will not mention every code change between the first part and this part, as we only want to focus on the important, new parts of the code. For example, there is a new Person::getLink() method and new language items have been added. For all changes, please refer to the source code on GitHub . Runtime Cache # To reduce the number of database queries when different APIs require person objects, we implement a runtime cache for people: files/lib/system/cache/runtime/PersonRuntimeCache.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <? php namespace wcf\\system\\cache\\runtime ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonList ; /** * Runtime cache implementation for people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cache\\Runtime * * @method Person[] getCachedObjects() * @method Person getObject($objectID) * @method Person[] getObjects(array $objectIDs) */ class PersonRuntimeCache extends AbstractRuntimeCache { /** * @inheritDoc */ protected $listClassName = PersonList :: class ; } Comments # To allow users to comment on people, we need to tell the system that people support comments. This is done by registering a com.woltlab.wcf.comment.commentableContent object type whose processor implements ICommentManager : objectType.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/objectType.xsd\" > <import> <type> <name> com.woltlab.wcf.person.personComment </name> <definitionname> com.woltlab.wcf.comment.commentableContent </definitionname> <classname> wcf\\system\\comment\\manager\\PersonCommentManager </classname> </type> </import> </data> The PersonCommentManager class extended ICommentManager \u2019s default implementation AbstractCommentManager : files/lib/system/comment/manager/PersonCommentManager.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 <? php namespace wcf\\system\\comment\\manager ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonEditor ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\WCF ; /** * Comment manager implementation for people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Comment\\Manager */ class PersonCommentManager extends AbstractCommentManager { /** * @inheritDoc */ protected $permissionAdd = 'user.person.canAddComment' ; /** * @inheritDoc */ protected $permissionAddWithoutModeration = 'user.person.canAddCommentWithoutModeration' ; /** * @inheritDoc */ protected $permissionCanModerate = 'mod.person.canModerateComment' ; /** * @inheritDoc */ protected $permissionDelete = 'user.person.canDeleteComment' ; /** * @inheritDoc */ protected $permissionEdit = 'user.person.canEditComment' ; /** * @inheritDoc */ protected $permissionModDelete = 'mod.person.canDeleteComment' ; /** * @inheritDoc */ protected $permissionModEdit = 'mod.person.canEditComment' ; /** * @inheritDoc */ public function getLink ( $objectTypeID , $objectID ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) -> getLink (); } /** * @inheritDoc */ public function isAccessible ( $objectID , $validateWritePermission = false ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) !== null ; } /** * @inheritDoc */ public function getTitle ( $objectTypeID , $objectID , $isResponse = false ) { if ( $isResponse ) { return WCF :: getLanguage () -> get ( 'wcf.person.commentResponse' ); } return WCF :: getLanguage () -> getDynamicVariable ( 'wcf.person.comment' ); } /** * @inheritDoc */ public function updateCounter ( $objectID , $value ) { ( new PersonEditor ( new Person ( $objectID ))) -> updateCounters ([ 'comments' => $value ]); } } First, the system is told the names of the permissions via the $permission* properties. More information about comment permissions can be found here . The getLink() method returns the link to the person with the passed comment id. As in isAccessible() , PersonRuntimeCache is used to potentially save database queries. The isAccessible() method checks if the active user can access the relevant person. As we do not have any special restrictions for accessing people, we only need to check if the person exists. The getTitle() method returns the title used for comments and responses, which is just a generic language item in this case. The updateCounter() updates the comments\u2019 counter of the person. We have added a new comments database table column to the wcf1_person database table in order to keep track on the number of comments. Additionally, we have added a new enableComments database table column to the wcf1_person database table whose value can be set when creating or editing a person in the ACP. With this option, comments on individual people can be disabled. Liking comments is already built-in and only requires some extra code in the PersonPage class for showing the likes of pre-loaded comments. Person Page # PersonPage # files/lib/page/PersonPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 <? php namespace wcf\\page ; use wcf\\data\\comment\\StructuredCommentList ; use wcf\\data\\person\\Person ; use wcf\\system\\comment\\CommentHandler ; use wcf\\system\\comment\\manager\\PersonCommentManager ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\WCF ; /** * Shows the details of a certain person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Page */ class PersonPage extends AbstractPage { /** * list of comments * @var StructuredCommentList */ public $commentList ; /** * person comment manager object * @var PersonCommentManager */ public $commentManager ; /** * id of the person comment object type * @var int */ public $commentObjectTypeID = 0 ; /** * shown person * @var Person */ public $person ; /** * id of the shown person * @var int */ public $personID = 0 ; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'commentCanAdd' => WCF :: getSession () -> getPermission ( 'user.person.canAddComment' ), 'commentList' => $this -> commentList , 'commentObjectTypeID' => $this -> commentObjectTypeID , 'lastCommentTime' => $this -> commentList ? $this -> commentList -> getMinCommentTime () : 0 , 'likeData' => MODULE_LIKE && $this -> commentList ? $this -> commentList -> getLikeData () : [], 'person' => $this -> person , ]); } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( $this -> person -> enableComments ) { $this -> commentObjectTypeID = CommentHandler :: getInstance () -> getObjectTypeID ( 'com.woltlab.wcf.person.personComment' ); $this -> commentManager = CommentHandler :: getInstance () -> getObjectType ( $this -> commentObjectTypeID ) -> getProcessor (); $this -> commentList = CommentHandler :: getInstance () -> getCommentList ( $this -> commentManager , $this -> commentObjectTypeID , $this -> person -> personID ); } } /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> personID = \\intval ( $_REQUEST [ 'id' ]); } $this -> person = new Person ( $this -> personID ); if ( ! $this -> person -> personID ) { throw new IllegalLinkException (); } } } The PersonPage class is similar to the PersonEditForm in the ACP in that it reads the id of the requested person from the request data and validates the id in readParameters() . The rest of the code only handles fetching the list of comments on the requested person. In readData() , this list is fetched using CommentHandler::getCommentList() if comments are enabled for the person. The assignVariables() method assigns some additional template variables like $commentCanAdd , which is 1 if the active person can add comments and is 0 otherwise, $lastCommentTime , which contains the UNIX timestamp of the last comment, and $likeData , which contains data related to the likes for the disabled comments. person.tpl # templates/person.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 {capture assign='pageTitle'}{$person} - {lang}wcf.person.list{/lang}{/capture} {capture assign='contentTitle'}{$person}{/capture} {include file='header'} {if $person->enableComments} {if $commentList|count || $commentCanAdd} <section id=\"comments\" class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> {lang}wcf.person.comments{/lang} {if $person->comments}<span class=\"badge\">{#$person->comments}</span>{/if} </h2> </header> {include file='__commentJavaScript' commentContainerID='personCommentList'} <div class=\"personComments\"> <ul id=\"personCommentList\" class=\"commentList containerList\" {* *}data-can-add=\"{if $commentCanAdd}true{else}false{/if}\" {* *}data-object-id=\"{@$person->personID}\" {* *}data-object-type-id=\"{@$commentObjectTypeID}\" {* *}data-comments=\"{if $person->comments}{@$commentList->countObjects()}{else}0{/if}\" {* *}data-last-comment-time=\"{@$lastCommentTime}\" {* *}> {include file='commentListAddComment' wysiwygSelector='personCommentListAddComment'} {include file='commentList'} </ul> </div> </section> {/if} {/if} <footer class=\"contentFooter\"> {hascontent} <nav class=\"contentFooterNavigation\"> <ul> {content}{event name='contentFooterNavigation'}{/content} </ul> </nav> {/hascontent} </footer> {include file='footer'} For now, the person template is still very empty and only shows the comments in the content area. The template code shown for comments is very generic and used in this form in many locations as it only sets the header of the comment list and the container ul#personCommentList element for the comments shown by commentList template. The ul#personCommentList elements has five additional data- attributes required by the JavaScript API for comments for loading more comments or creating new ones. The commentListAddComment template adds the WYSIWYG support. The attribute wysiwygSelector should be the id of the comment list personCommentList with an additional AddComment suffix. page.xml # page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.people.PersonList\" > <pageType> system </pageType> <controller> wcf\\page\\PersonListPage </controller> <name language= \"de\" > Personen-Liste </name> <name language= \"en\" > Person List </name> <content language= \"de\" > <title> Personen </title> </content> <content language= \"en\" > <title> People </title> </content> </page> <page identifier= \"com.woltlab.wcf.people.Person\" > <pageType> system </pageType> <controller> wcf\\page\\PersonPage </controller> <handler> wcf\\system\\page\\handler\\PersonPageHandler </handler> <name language= \"de\" > Person </name> <name language= \"en\" > Person </name> <requireObjectID> 1 </requireObjectID> <parent> com.woltlab.wcf.people.PersonList </parent> </page> </import> </data> The page.xml file has been extended for the new person page with identifier com.woltlab.wcf.people.Person . Compared to the pre-existing com.woltlab.wcf.people.PersonList page, there are four differences: It has a <handler> element with a class name as value. This aspect will be discussed in more detail in the next section. There are no <content> elements because, both, the title and the content of the page are dynamically generated in the template. The <requireObjectID> tells the system that this page requires an object id to properly work, in this case a valid person id. This page has a <parent> page, the person list page. In general, the details page for any type of object that is listed on a different page has the list page as its parent. PersonPageHandler # files/lib/system/page/handler/PersonPageHandler.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 <? php namespace wcf\\system\\page\\handler ; use wcf\\data\\page\\Page ; use wcf\\data\\person\\PersonList ; use wcf\\data\\user\\online\\UserOnline ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\database\\util\\PreparedStatementConditionBuilder ; use wcf\\system\\WCF ; /** * Page handler implementation for person page. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Page\\Handler */ class PersonPageHandler extends AbstractLookupPageHandler implements IOnlineLocationPageHandler { use TOnlineLocationPageHandler ; /** * @inheritDoc */ public function getLink ( $objectID ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) -> getLink (); } /** * Returns the textual description if a user is currently online viewing this page. * * @see IOnlineLocationPageHandler::getOnlineLocation() * * @param Page $page visited page * @param UserOnline $user user online object with request data * @return string */ public function getOnlineLocation ( Page $page , UserOnline $user ) { if ( $user -> pageObjectID === null ) { return '' ; } $person = PersonRuntimeCache :: getInstance () -> getObject ( $user -> pageObjectID ); if ( $person === null ) { return '' ; } return WCF :: getLanguage () -> getDynamicVariable ( 'wcf.page.onlineLocation.' . $page -> identifier , [ 'person' => $person ]); } /** * @inheritDoc */ public function isValid ( $objectID = null ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) !== null ; } /** * @inheritDoc */ public function lookup ( $searchString ) { $conditionBuilder = new PreparedStatementConditionBuilder ( false , 'OR' ); $conditionBuilder -> add ( 'person.firstName LIKE ?' , [ '%' . $searchString . '%' ]); $conditionBuilder -> add ( 'person.lastName LIKE ?' , [ '%' . $searchString . '%' ]); $personList = new PersonList (); $personList -> getConditionBuilder () -> add ( $conditionBuilder , $conditionBuilder -> getParameters ()); $personList -> readObjects (); $results = []; foreach ( $personList as $person ) { $results [] = [ 'image' => 'fa-user' , 'link' => $person -> getLink (), 'objectID' => $person -> personID , 'title' => $person -> getTitle (), ]; } return $results ; } /** * Prepares fetching all necessary data for the textual description if a user is currently online * viewing this page. * * @see IOnlineLocationPageHandler::prepareOnlineLocation() * * @param Page $page visited page * @param UserOnline $user user online object with request data */ public function prepareOnlineLocation ( Page $page , UserOnline $user ) { if ( $user -> pageObjectID !== null ) { PersonRuntimeCache :: getInstance () -> cacheObjectID ( $user -> pageObjectID ); } } } Like any page handler, the PersonPageHandler class has to implement the IMenuPageHandler interface, which should be done by extending the AbstractMenuPageHandler class. As we want administrators to link to specific people in menus, for example, we have to also implement the ILookupPageHandler interface by extending the AbstractLookupPageHandler class. For the ILookupPageHandler interface, we need to implement three methods: getLink($objectID) returns the link to the person page with the given id. In this case, we simply delegate this method call to the Person object returned by PersonRuntimeCache::getObject() . isValid($objectID) returns true if the person with the given id exists, otherwise false . Here, we use PersonRuntimeCache::getObject() again and check if the return value is null , which is the case for non-existing people. lookup($searchString) is used when setting up an internal link and when searching for the linked person. This method simply searches the first and last name of the people and returns an array with the person data. While the link , the objectID , and the title element are self-explanatory, the image element can either contain an HTML <img> tag, which is displayed next to the search result (WoltLab Suite uses an image tag for users showing their avatar, for example), or a FontAwesome icon class (starting with fa- ). Additionally, the class also implements IOnlineLocationPageHandler which is used to determine the online location of users. To ensure upwards-compatibility if the IOnlineLocationPageHandler interface changes, the TOnlineLocationPageHandler trait is used. The IOnlineLocationPageHandler interface requires two methods to be implemented: getOnlineLocation(Page $page, UserOnline $user) returns the textual description of the online location. The language item for the user online locations should use the pattern wcf.page.onlineLocation.{page identifier} . prepareOnlineLocation(Page $page, UserOnline $user) is called for each user online before the getOnlineLocation() calls. In this case, calling prepareOnlineLocation() first enables us to add all relevant person ids to the person runtime cache so that for all getOnlineLocation() calls combined, only one database query is necessary to fetch all person objects. This concludes the third part of our tutorial series after which each person has a dedicated page on which people can comment on the person. The complete source code of this part can be found on GitHub .","title":"Part 3"},{"location":"tutorial/series/part_3/#part-3-person-page-and-comments","text":"In this part of our tutorial series, we will add a new front end page to our package that is dedicated to each person and shows their personal details. To make good use of this new page and introduce a new API of WoltLab Suite, we will add the opportunity for users to comment on the person using WoltLab Suite\u2019s reusable comment functionality.","title":"Part 3: Person Page and Comments"},{"location":"tutorial/series/part_3/#package-functionality","text":"In addition to the existing functions from part 1 , the package will provide the following possibilities/functions after this part of the tutorial: Details page for each person linked in the front end person list Comment on people on their respective page (can be disabled per person) User online location for person details page with name and link to person details page Create menu items linking to specific person details pages","title":"Package Functionality"},{"location":"tutorial/series/part_3/#used-components","text":"In addition to the components used in part 1 , we will use the objectType package installation plugin , use the comment API , create a runtime cache , and create a page handler.","title":"Used Components"},{"location":"tutorial/series/part_3/#package-structure","text":"The complete package will have the following file structure (including the files from part 1 ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 \u251c\u2500\u2500 acpMenu.xml \u251c\u2500\u2500 acptemplates \u2502 \u251c\u2500\u2500 personAdd.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u251c\u2500\u2500 form \u2502 \u2502 \u2502 \u251c\u2500\u2500 PersonAddForm.class.php \u2502 \u2502 \u2502 \u2514\u2500\u2500 PersonEditForm.class.php \u2502 \u2502 \u2514\u2500\u2500 page \u2502 \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonList.class.php \u2502 \u251c\u2500\u2500 page \u2502 \u2502 \u251c\u2500\u2500 PersonListPage.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonPage.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 cache \u2502 \u2502 \u2514\u2500\u2500 runtime \u2502 \u2502 \u2514\u2500\u2500 PersonRuntimeCache.class.php \u2502 \u251c\u2500\u2500 comment \u2502 \u2502 \u2514\u2500\u2500 manager \u2502 \u2502 \u2514\u2500\u2500 PersonCommentManager.class.php \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 handler \u2502 \u2514\u2500\u2500 PersonPageHandler.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 menuItem.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u251c\u2500\u2500 templates \u2502 \u251c\u2500\u2500 person.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u2514\u2500\u2500 userGroupOption.xml We will not mention every code change between the first part and this part, as we only want to focus on the important, new parts of the code. For example, there is a new Person::getLink() method and new language items have been added. For all changes, please refer to the source code on GitHub .","title":"Package Structure"},{"location":"tutorial/series/part_3/#runtime-cache","text":"To reduce the number of database queries when different APIs require person objects, we implement a runtime cache for people: files/lib/system/cache/runtime/PersonRuntimeCache.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <? php namespace wcf\\system\\cache\\runtime ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonList ; /** * Runtime cache implementation for people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cache\\Runtime * * @method Person[] getCachedObjects() * @method Person getObject($objectID) * @method Person[] getObjects(array $objectIDs) */ class PersonRuntimeCache extends AbstractRuntimeCache { /** * @inheritDoc */ protected $listClassName = PersonList :: class ; }","title":"Runtime Cache"},{"location":"tutorial/series/part_3/#comments","text":"To allow users to comment on people, we need to tell the system that people support comments. This is done by registering a com.woltlab.wcf.comment.commentableContent object type whose processor implements ICommentManager : objectType.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/objectType.xsd\" > <import> <type> <name> com.woltlab.wcf.person.personComment </name> <definitionname> com.woltlab.wcf.comment.commentableContent </definitionname> <classname> wcf\\system\\comment\\manager\\PersonCommentManager </classname> </type> </import> </data> The PersonCommentManager class extended ICommentManager \u2019s default implementation AbstractCommentManager : files/lib/system/comment/manager/PersonCommentManager.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 <? php namespace wcf\\system\\comment\\manager ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonEditor ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\WCF ; /** * Comment manager implementation for people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Comment\\Manager */ class PersonCommentManager extends AbstractCommentManager { /** * @inheritDoc */ protected $permissionAdd = 'user.person.canAddComment' ; /** * @inheritDoc */ protected $permissionAddWithoutModeration = 'user.person.canAddCommentWithoutModeration' ; /** * @inheritDoc */ protected $permissionCanModerate = 'mod.person.canModerateComment' ; /** * @inheritDoc */ protected $permissionDelete = 'user.person.canDeleteComment' ; /** * @inheritDoc */ protected $permissionEdit = 'user.person.canEditComment' ; /** * @inheritDoc */ protected $permissionModDelete = 'mod.person.canDeleteComment' ; /** * @inheritDoc */ protected $permissionModEdit = 'mod.person.canEditComment' ; /** * @inheritDoc */ public function getLink ( $objectTypeID , $objectID ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) -> getLink (); } /** * @inheritDoc */ public function isAccessible ( $objectID , $validateWritePermission = false ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) !== null ; } /** * @inheritDoc */ public function getTitle ( $objectTypeID , $objectID , $isResponse = false ) { if ( $isResponse ) { return WCF :: getLanguage () -> get ( 'wcf.person.commentResponse' ); } return WCF :: getLanguage () -> getDynamicVariable ( 'wcf.person.comment' ); } /** * @inheritDoc */ public function updateCounter ( $objectID , $value ) { ( new PersonEditor ( new Person ( $objectID ))) -> updateCounters ([ 'comments' => $value ]); } } First, the system is told the names of the permissions via the $permission* properties. More information about comment permissions can be found here . The getLink() method returns the link to the person with the passed comment id. As in isAccessible() , PersonRuntimeCache is used to potentially save database queries. The isAccessible() method checks if the active user can access the relevant person. As we do not have any special restrictions for accessing people, we only need to check if the person exists. The getTitle() method returns the title used for comments and responses, which is just a generic language item in this case. The updateCounter() updates the comments\u2019 counter of the person. We have added a new comments database table column to the wcf1_person database table in order to keep track on the number of comments. Additionally, we have added a new enableComments database table column to the wcf1_person database table whose value can be set when creating or editing a person in the ACP. With this option, comments on individual people can be disabled. Liking comments is already built-in and only requires some extra code in the PersonPage class for showing the likes of pre-loaded comments.","title":"Comments"},{"location":"tutorial/series/part_3/#person-page","text":"","title":"Person Page"},{"location":"tutorial/series/part_3/#personpage","text":"files/lib/page/PersonPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 <? php namespace wcf\\page ; use wcf\\data\\comment\\StructuredCommentList ; use wcf\\data\\person\\Person ; use wcf\\system\\comment\\CommentHandler ; use wcf\\system\\comment\\manager\\PersonCommentManager ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\WCF ; /** * Shows the details of a certain person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Page */ class PersonPage extends AbstractPage { /** * list of comments * @var StructuredCommentList */ public $commentList ; /** * person comment manager object * @var PersonCommentManager */ public $commentManager ; /** * id of the person comment object type * @var int */ public $commentObjectTypeID = 0 ; /** * shown person * @var Person */ public $person ; /** * id of the shown person * @var int */ public $personID = 0 ; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'commentCanAdd' => WCF :: getSession () -> getPermission ( 'user.person.canAddComment' ), 'commentList' => $this -> commentList , 'commentObjectTypeID' => $this -> commentObjectTypeID , 'lastCommentTime' => $this -> commentList ? $this -> commentList -> getMinCommentTime () : 0 , 'likeData' => MODULE_LIKE && $this -> commentList ? $this -> commentList -> getLikeData () : [], 'person' => $this -> person , ]); } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( $this -> person -> enableComments ) { $this -> commentObjectTypeID = CommentHandler :: getInstance () -> getObjectTypeID ( 'com.woltlab.wcf.person.personComment' ); $this -> commentManager = CommentHandler :: getInstance () -> getObjectType ( $this -> commentObjectTypeID ) -> getProcessor (); $this -> commentList = CommentHandler :: getInstance () -> getCommentList ( $this -> commentManager , $this -> commentObjectTypeID , $this -> person -> personID ); } } /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> personID = \\intval ( $_REQUEST [ 'id' ]); } $this -> person = new Person ( $this -> personID ); if ( ! $this -> person -> personID ) { throw new IllegalLinkException (); } } } The PersonPage class is similar to the PersonEditForm in the ACP in that it reads the id of the requested person from the request data and validates the id in readParameters() . The rest of the code only handles fetching the list of comments on the requested person. In readData() , this list is fetched using CommentHandler::getCommentList() if comments are enabled for the person. The assignVariables() method assigns some additional template variables like $commentCanAdd , which is 1 if the active person can add comments and is 0 otherwise, $lastCommentTime , which contains the UNIX timestamp of the last comment, and $likeData , which contains data related to the likes for the disabled comments.","title":"PersonPage"},{"location":"tutorial/series/part_3/#persontpl","text":"templates/person.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 {capture assign='pageTitle'}{$person} - {lang}wcf.person.list{/lang}{/capture} {capture assign='contentTitle'}{$person}{/capture} {include file='header'} {if $person->enableComments} {if $commentList|count || $commentCanAdd} <section id=\"comments\" class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> {lang}wcf.person.comments{/lang} {if $person->comments}<span class=\"badge\">{#$person->comments}</span>{/if} </h2> </header> {include file='__commentJavaScript' commentContainerID='personCommentList'} <div class=\"personComments\"> <ul id=\"personCommentList\" class=\"commentList containerList\" {* *}data-can-add=\"{if $commentCanAdd}true{else}false{/if}\" {* *}data-object-id=\"{@$person->personID}\" {* *}data-object-type-id=\"{@$commentObjectTypeID}\" {* *}data-comments=\"{if $person->comments}{@$commentList->countObjects()}{else}0{/if}\" {* *}data-last-comment-time=\"{@$lastCommentTime}\" {* *}> {include file='commentListAddComment' wysiwygSelector='personCommentListAddComment'} {include file='commentList'} </ul> </div> </section> {/if} {/if} <footer class=\"contentFooter\"> {hascontent} <nav class=\"contentFooterNavigation\"> <ul> {content}{event name='contentFooterNavigation'}{/content} </ul> </nav> {/hascontent} </footer> {include file='footer'} For now, the person template is still very empty and only shows the comments in the content area. The template code shown for comments is very generic and used in this form in many locations as it only sets the header of the comment list and the container ul#personCommentList element for the comments shown by commentList template. The ul#personCommentList elements has five additional data- attributes required by the JavaScript API for comments for loading more comments or creating new ones. The commentListAddComment template adds the WYSIWYG support. The attribute wysiwygSelector should be the id of the comment list personCommentList with an additional AddComment suffix.","title":"person.tpl"},{"location":"tutorial/series/part_3/#pagexml","text":"page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.people.PersonList\" > <pageType> system </pageType> <controller> wcf\\page\\PersonListPage </controller> <name language= \"de\" > Personen-Liste </name> <name language= \"en\" > Person List </name> <content language= \"de\" > <title> Personen </title> </content> <content language= \"en\" > <title> People </title> </content> </page> <page identifier= \"com.woltlab.wcf.people.Person\" > <pageType> system </pageType> <controller> wcf\\page\\PersonPage </controller> <handler> wcf\\system\\page\\handler\\PersonPageHandler </handler> <name language= \"de\" > Person </name> <name language= \"en\" > Person </name> <requireObjectID> 1 </requireObjectID> <parent> com.woltlab.wcf.people.PersonList </parent> </page> </import> </data> The page.xml file has been extended for the new person page with identifier com.woltlab.wcf.people.Person . Compared to the pre-existing com.woltlab.wcf.people.PersonList page, there are four differences: It has a <handler> element with a class name as value. This aspect will be discussed in more detail in the next section. There are no <content> elements because, both, the title and the content of the page are dynamically generated in the template. The <requireObjectID> tells the system that this page requires an object id to properly work, in this case a valid person id. This page has a <parent> page, the person list page. In general, the details page for any type of object that is listed on a different page has the list page as its parent.","title":"page.xml"},{"location":"tutorial/series/part_3/#personpagehandler","text":"files/lib/system/page/handler/PersonPageHandler.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 <? php namespace wcf\\system\\page\\handler ; use wcf\\data\\page\\Page ; use wcf\\data\\person\\PersonList ; use wcf\\data\\user\\online\\UserOnline ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\database\\util\\PreparedStatementConditionBuilder ; use wcf\\system\\WCF ; /** * Page handler implementation for person page. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Page\\Handler */ class PersonPageHandler extends AbstractLookupPageHandler implements IOnlineLocationPageHandler { use TOnlineLocationPageHandler ; /** * @inheritDoc */ public function getLink ( $objectID ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) -> getLink (); } /** * Returns the textual description if a user is currently online viewing this page. * * @see IOnlineLocationPageHandler::getOnlineLocation() * * @param Page $page visited page * @param UserOnline $user user online object with request data * @return string */ public function getOnlineLocation ( Page $page , UserOnline $user ) { if ( $user -> pageObjectID === null ) { return '' ; } $person = PersonRuntimeCache :: getInstance () -> getObject ( $user -> pageObjectID ); if ( $person === null ) { return '' ; } return WCF :: getLanguage () -> getDynamicVariable ( 'wcf.page.onlineLocation.' . $page -> identifier , [ 'person' => $person ]); } /** * @inheritDoc */ public function isValid ( $objectID = null ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) !== null ; } /** * @inheritDoc */ public function lookup ( $searchString ) { $conditionBuilder = new PreparedStatementConditionBuilder ( false , 'OR' ); $conditionBuilder -> add ( 'person.firstName LIKE ?' , [ '%' . $searchString . '%' ]); $conditionBuilder -> add ( 'person.lastName LIKE ?' , [ '%' . $searchString . '%' ]); $personList = new PersonList (); $personList -> getConditionBuilder () -> add ( $conditionBuilder , $conditionBuilder -> getParameters ()); $personList -> readObjects (); $results = []; foreach ( $personList as $person ) { $results [] = [ 'image' => 'fa-user' , 'link' => $person -> getLink (), 'objectID' => $person -> personID , 'title' => $person -> getTitle (), ]; } return $results ; } /** * Prepares fetching all necessary data for the textual description if a user is currently online * viewing this page. * * @see IOnlineLocationPageHandler::prepareOnlineLocation() * * @param Page $page visited page * @param UserOnline $user user online object with request data */ public function prepareOnlineLocation ( Page $page , UserOnline $user ) { if ( $user -> pageObjectID !== null ) { PersonRuntimeCache :: getInstance () -> cacheObjectID ( $user -> pageObjectID ); } } } Like any page handler, the PersonPageHandler class has to implement the IMenuPageHandler interface, which should be done by extending the AbstractMenuPageHandler class. As we want administrators to link to specific people in menus, for example, we have to also implement the ILookupPageHandler interface by extending the AbstractLookupPageHandler class. For the ILookupPageHandler interface, we need to implement three methods: getLink($objectID) returns the link to the person page with the given id. In this case, we simply delegate this method call to the Person object returned by PersonRuntimeCache::getObject() . isValid($objectID) returns true if the person with the given id exists, otherwise false . Here, we use PersonRuntimeCache::getObject() again and check if the return value is null , which is the case for non-existing people. lookup($searchString) is used when setting up an internal link and when searching for the linked person. This method simply searches the first and last name of the people and returns an array with the person data. While the link , the objectID , and the title element are self-explanatory, the image element can either contain an HTML <img> tag, which is displayed next to the search result (WoltLab Suite uses an image tag for users showing their avatar, for example), or a FontAwesome icon class (starting with fa- ). Additionally, the class also implements IOnlineLocationPageHandler which is used to determine the online location of users. To ensure upwards-compatibility if the IOnlineLocationPageHandler interface changes, the TOnlineLocationPageHandler trait is used. The IOnlineLocationPageHandler interface requires two methods to be implemented: getOnlineLocation(Page $page, UserOnline $user) returns the textual description of the online location. The language item for the user online locations should use the pattern wcf.page.onlineLocation.{page identifier} . prepareOnlineLocation(Page $page, UserOnline $user) is called for each user online before the getOnlineLocation() calls. In this case, calling prepareOnlineLocation() first enables us to add all relevant person ids to the person runtime cache so that for all getOnlineLocation() calls combined, only one database query is necessary to fetch all person objects. This concludes the third part of our tutorial series after which each person has a dedicated page on which people can comment on the person. The complete source code of this part can be found on GitHub .","title":"PersonPageHandler"},{"location":"tutorial/series/part_4/","text":"Part 4: Box and Box Conditions # In this part of our tutorial series, we add support for creating boxes listing people. Package Functionality # In addition to the existing functions from part 3 , the package will provide the following functionality after this part of the tutorial: Creating boxes dynamically listing people Filtering the people listed in boxes using conditions Used Components # In addition to the components used in previous parts, we will use the objectTypeDefinition package installation plugin and use the box and condition APIs. To pre-install a specific person list box, we refer to the documentation of the box package installation plugin . Package Structure # The complete package will have the following file structure ( excluding unchanged files from part 3 ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 box \u2502 \u2502 \u2514\u2500\u2500 PersonListBoxController.class.php \u2502 \u2514\u2500\u2500 condition \u2502 \u2514\u2500\u2500 person \u2502 \u251c\u2500\u2500 PersonFirstNameTextPropertyCondition.class.php \u2502 \u2514\u2500\u2500 PersonLastNameTextPropertyCondition.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 objectTypeDefinition.xml \u2514\u2500\u2500 templates \u2514\u2500\u2500 boxPersonList.tpl For all changes, please refer to the source code on GitHub . Box Controller # In addition to static boxes with fixed contents, administrators are able to create dynamic boxes with contents from the database. In our case here, we want administrators to be able to create boxes listing people. To do so, we first have to register a new object type for this person list box controller for the object type definition com.woltlab.wcf.boxController : 1 2 3 4 5 <type> <name> com.woltlab.wcf.personList </name> <definitionname> com.woltlab.wcf.boxController </definitionname> <classname> wcf\\system\\box\\PersonListBoxController </classname> </type> The com.woltlab.wcf.boxController object type definition requires the provided class to implement wcf\\system\\box\\IBoxController : files/lib/system/box/PersonListBoxController.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <? php namespace wcf\\system\\box ; use wcf\\data\\person\\PersonList ; use wcf\\system\\WCF ; /** * Dynamic box controller implementation for a list of persons. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Box */ class PersonListBoxController extends AbstractDatabaseObjectListBoxController { /** * @inheritDoc */ protected $conditionDefinition = 'com.woltlab.wcf.box.personList.condition' ; /** * @inheritDoc */ public $defaultLimit = 5 ; /** * @inheritDoc */ protected $sortFieldLanguageItemPrefix = 'wcf.person' ; /** * @inheritDoc */ protected static $supportedPositions = [ 'sidebarLeft' , 'sidebarRight' , ]; /** * @inheritDoc */ public $validSortFields = [ 'firstName' , 'lastName' , 'comments' , ]; /** * @inheritDoc */ protected function getObjectList () { return new PersonList (); } /** * @inheritDoc */ protected function getTemplate () { return WCF :: getTPL () -> fetch ( 'boxPersonList' , 'wcf' , [ 'boxPersonList' => $this -> objectList , 'boxSortField' => $this -> sortField , 'boxPosition' => $this -> box -> position , ], true ); } } By extending AbstractDatabaseObjectListBoxController , we only have to provide minimal data ourself and rely mostly on the default implementation provided by AbstractDatabaseObjectListBoxController : As we will support conditions for the listed people, we have to set the relevant condition definition via $conditionDefinition . AbstractDatabaseObjectListBoxController already supports restricting the number of listed objects. To do so, you only have to specify the default number of listed objects via $defaultLimit . AbstractDatabaseObjectListBoxController also supports setting the sort order of the listed objects. You have to provide the supported sort fields via $validSortFields and specify the prefix used for the language items of the sort fields via $sortFieldLanguageItemPrefix so that for every $validSortField in $validSortFields , the language item {$sortFieldLanguageItemPrefix}.{$validSortField} must exist. The box system supports different positions . Each box controller specifies the positions it supports via $supportedPositions . To keep the implementation simple here as different positions might require different output in the template, we restrict ourselves to sidebars. getObjectList() returns an instance of DatabaseObjectList that is used to read the listed objects. getObjectList() itself must not call readObjects() , as AbstractDatabaseObjectListBoxController takes care of calling the method after adding the conditions and setting the sort order. getTemplate() returns the contents of the box relying on the boxPersonList template here: templates/boxPersonList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <ul class=\"sidebarItemList\"> { foreach from = $boxPersonList item = boxPerson } <li class=\"box24\"> <span class=\"icon icon24 fa-user\"></span> <div class=\"sidebarItemTitle\"> <h3> { anchor object = $boxPerson } </h3> { capture assign = '__boxPersonDescription' }{ lang __optional = true } wcf.person.boxList.description. { $boxSortField }{ /lang }{ /capture } { if $__boxPersonDescription } <small> { @ $__boxPersonDescription } </small> { /if } </div> </li> { /foreach } </ul> The template relies on a .sidebarItemList element, which is generally used for sidebar listings. (If different box positions were supported, we either have to generate different output by considering the value of $boxPosition in the template or by using different templates in getTemplate() .) One specific piece of code is the $__boxPersonDescription variable, which supports an optional description below the person's name relying on the optional language item wcf.person.boxList.description.{$boxSortField} . We only add one such language item when sorting the people by comments: In such a case, the number of comments will be shown. (When sorting by first and last name, there are no additional useful information that could be shown here, though the plugin from part 2 adding support for birthdays might also show the birthday when sorting by first or last name.) Lastly, we also provide the language item wcf.acp.box.boxController.com.woltlab.wcf.personList , which is used in the list of available box controllers. Conditions # The condition system can be used to generally filter a list of objects. In our case, the box system supports conditions to filter the objects shown in a specific box. Admittedly, our current person implementation only contains minimal data so that filtering might not make the most sense here but it will still show how to use the condition system for boxes. We will support filtering the people by their first and last name so that, for example, a box can be created listing all people with a specific first name. The first step for condition support is to register a object type definition for the relevant conditions requiring the IObjectListCondition interface: objectTypeDefinition.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/objectTypeDefinition.xsd\" > <import> <definition> <name> com.woltlab.wcf.box.personList.condition </name> <interfacename> wcf\\system\\condition\\IObjectListCondition </interfacename> </definition> </import> </data> Next, we register the specific conditions for filtering by the first and last name using this object type condition: 1 2 3 4 5 6 7 8 9 10 <type> <name> com.woltlab.wcf.people.firstName </name> <definitionname> com.woltlab.wcf.box.personList.condition </definitionname> <classname> wcf\\system\\condition\\person\\PersonFirstNameTextPropertyCondition </classname> </type> <type> <name> com.woltlab.wcf.people.lastName </name> <definitionname> com.woltlab.wcf.box.personList.condition </definitionname> <classname> wcf\\system\\condition\\person\\PersonLastNameTextPropertyCondition </classname> </type> PersonFirstNameTextPropertyCondition and PersonLastNameTextPropertyCondition only differ minimally so that we only focus on PersonFirstNameTextPropertyCondition here, which relies on the default implementation AbstractObjectTextPropertyCondition and only requires specifying different object properties: files/lib/system/condition/person/PersonFirstNameTextPropertyCondition.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <? php namespace wcf\\system\\condition\\person ; use wcf\\data\\person\\Person ; use wcf\\system\\condition\\AbstractObjectTextPropertyCondition ; /** * Condition implementation for the first name of a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Core\\System\\Condition */ class PersonFirstNameTextPropertyCondition extends AbstractObjectTextPropertyCondition { /** * @inheritDoc */ protected $className = Person :: class ; /** * @inheritDoc */ protected $description = 'wcf.person.condition.firstName.description' ; /** * @inheritDoc */ protected $fieldName = 'personFirstName' ; /** * @inheritDoc */ protected $label = 'wcf.person.firstName' ; /** * @inheritDoc */ protected $propertyName = 'firstName' ; /** * @inheritDoc */ protected $supportsMultipleValues = true ; } $className contains the class name of the relevant database object from which the class name of the database object list is derived and $propertyName is the name of the database object's property that contains the value used for filtering. By setting $supportsMultipleValues to true , multiple comma-separated values can be specified so that, for example, a box can also only list people with either of two specific first names. $description (optional), $fieldName , and $label are used in the output of the form field. (The implementation here is specific for AbstractObjectTextPropertyCondition . The wcf\\system\\condition namespace also contains several other default condition implementations.)","title":"Part 4"},{"location":"tutorial/series/part_4/#part-4-box-and-box-conditions","text":"In this part of our tutorial series, we add support for creating boxes listing people.","title":"Part 4: Box and Box Conditions"},{"location":"tutorial/series/part_4/#package-functionality","text":"In addition to the existing functions from part 3 , the package will provide the following functionality after this part of the tutorial: Creating boxes dynamically listing people Filtering the people listed in boxes using conditions","title":"Package Functionality"},{"location":"tutorial/series/part_4/#used-components","text":"In addition to the components used in previous parts, we will use the objectTypeDefinition package installation plugin and use the box and condition APIs. To pre-install a specific person list box, we refer to the documentation of the box package installation plugin .","title":"Used Components"},{"location":"tutorial/series/part_4/#package-structure","text":"The complete package will have the following file structure ( excluding unchanged files from part 3 ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 box \u2502 \u2502 \u2514\u2500\u2500 PersonListBoxController.class.php \u2502 \u2514\u2500\u2500 condition \u2502 \u2514\u2500\u2500 person \u2502 \u251c\u2500\u2500 PersonFirstNameTextPropertyCondition.class.php \u2502 \u2514\u2500\u2500 PersonLastNameTextPropertyCondition.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 objectTypeDefinition.xml \u2514\u2500\u2500 templates \u2514\u2500\u2500 boxPersonList.tpl For all changes, please refer to the source code on GitHub .","title":"Package Structure"},{"location":"tutorial/series/part_4/#box-controller","text":"In addition to static boxes with fixed contents, administrators are able to create dynamic boxes with contents from the database. In our case here, we want administrators to be able to create boxes listing people. To do so, we first have to register a new object type for this person list box controller for the object type definition com.woltlab.wcf.boxController : 1 2 3 4 5 <type> <name> com.woltlab.wcf.personList </name> <definitionname> com.woltlab.wcf.boxController </definitionname> <classname> wcf\\system\\box\\PersonListBoxController </classname> </type> The com.woltlab.wcf.boxController object type definition requires the provided class to implement wcf\\system\\box\\IBoxController : files/lib/system/box/PersonListBoxController.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <? php namespace wcf\\system\\box ; use wcf\\data\\person\\PersonList ; use wcf\\system\\WCF ; /** * Dynamic box controller implementation for a list of persons. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Box */ class PersonListBoxController extends AbstractDatabaseObjectListBoxController { /** * @inheritDoc */ protected $conditionDefinition = 'com.woltlab.wcf.box.personList.condition' ; /** * @inheritDoc */ public $defaultLimit = 5 ; /** * @inheritDoc */ protected $sortFieldLanguageItemPrefix = 'wcf.person' ; /** * @inheritDoc */ protected static $supportedPositions = [ 'sidebarLeft' , 'sidebarRight' , ]; /** * @inheritDoc */ public $validSortFields = [ 'firstName' , 'lastName' , 'comments' , ]; /** * @inheritDoc */ protected function getObjectList () { return new PersonList (); } /** * @inheritDoc */ protected function getTemplate () { return WCF :: getTPL () -> fetch ( 'boxPersonList' , 'wcf' , [ 'boxPersonList' => $this -> objectList , 'boxSortField' => $this -> sortField , 'boxPosition' => $this -> box -> position , ], true ); } } By extending AbstractDatabaseObjectListBoxController , we only have to provide minimal data ourself and rely mostly on the default implementation provided by AbstractDatabaseObjectListBoxController : As we will support conditions for the listed people, we have to set the relevant condition definition via $conditionDefinition . AbstractDatabaseObjectListBoxController already supports restricting the number of listed objects. To do so, you only have to specify the default number of listed objects via $defaultLimit . AbstractDatabaseObjectListBoxController also supports setting the sort order of the listed objects. You have to provide the supported sort fields via $validSortFields and specify the prefix used for the language items of the sort fields via $sortFieldLanguageItemPrefix so that for every $validSortField in $validSortFields , the language item {$sortFieldLanguageItemPrefix}.{$validSortField} must exist. The box system supports different positions . Each box controller specifies the positions it supports via $supportedPositions . To keep the implementation simple here as different positions might require different output in the template, we restrict ourselves to sidebars. getObjectList() returns an instance of DatabaseObjectList that is used to read the listed objects. getObjectList() itself must not call readObjects() , as AbstractDatabaseObjectListBoxController takes care of calling the method after adding the conditions and setting the sort order. getTemplate() returns the contents of the box relying on the boxPersonList template here: templates/boxPersonList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <ul class=\"sidebarItemList\"> { foreach from = $boxPersonList item = boxPerson } <li class=\"box24\"> <span class=\"icon icon24 fa-user\"></span> <div class=\"sidebarItemTitle\"> <h3> { anchor object = $boxPerson } </h3> { capture assign = '__boxPersonDescription' }{ lang __optional = true } wcf.person.boxList.description. { $boxSortField }{ /lang }{ /capture } { if $__boxPersonDescription } <small> { @ $__boxPersonDescription } </small> { /if } </div> </li> { /foreach } </ul> The template relies on a .sidebarItemList element, which is generally used for sidebar listings. (If different box positions were supported, we either have to generate different output by considering the value of $boxPosition in the template or by using different templates in getTemplate() .) One specific piece of code is the $__boxPersonDescription variable, which supports an optional description below the person's name relying on the optional language item wcf.person.boxList.description.{$boxSortField} . We only add one such language item when sorting the people by comments: In such a case, the number of comments will be shown. (When sorting by first and last name, there are no additional useful information that could be shown here, though the plugin from part 2 adding support for birthdays might also show the birthday when sorting by first or last name.) Lastly, we also provide the language item wcf.acp.box.boxController.com.woltlab.wcf.personList , which is used in the list of available box controllers.","title":"Box Controller"},{"location":"tutorial/series/part_4/#conditions","text":"The condition system can be used to generally filter a list of objects. In our case, the box system supports conditions to filter the objects shown in a specific box. Admittedly, our current person implementation only contains minimal data so that filtering might not make the most sense here but it will still show how to use the condition system for boxes. We will support filtering the people by their first and last name so that, for example, a box can be created listing all people with a specific first name. The first step for condition support is to register a object type definition for the relevant conditions requiring the IObjectListCondition interface: objectTypeDefinition.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/objectTypeDefinition.xsd\" > <import> <definition> <name> com.woltlab.wcf.box.personList.condition </name> <interfacename> wcf\\system\\condition\\IObjectListCondition </interfacename> </definition> </import> </data> Next, we register the specific conditions for filtering by the first and last name using this object type condition: 1 2 3 4 5 6 7 8 9 10 <type> <name> com.woltlab.wcf.people.firstName </name> <definitionname> com.woltlab.wcf.box.personList.condition </definitionname> <classname> wcf\\system\\condition\\person\\PersonFirstNameTextPropertyCondition </classname> </type> <type> <name> com.woltlab.wcf.people.lastName </name> <definitionname> com.woltlab.wcf.box.personList.condition </definitionname> <classname> wcf\\system\\condition\\person\\PersonLastNameTextPropertyCondition </classname> </type> PersonFirstNameTextPropertyCondition and PersonLastNameTextPropertyCondition only differ minimally so that we only focus on PersonFirstNameTextPropertyCondition here, which relies on the default implementation AbstractObjectTextPropertyCondition and only requires specifying different object properties: files/lib/system/condition/person/PersonFirstNameTextPropertyCondition.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <? php namespace wcf\\system\\condition\\person ; use wcf\\data\\person\\Person ; use wcf\\system\\condition\\AbstractObjectTextPropertyCondition ; /** * Condition implementation for the first name of a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Core\\System\\Condition */ class PersonFirstNameTextPropertyCondition extends AbstractObjectTextPropertyCondition { /** * @inheritDoc */ protected $className = Person :: class ; /** * @inheritDoc */ protected $description = 'wcf.person.condition.firstName.description' ; /** * @inheritDoc */ protected $fieldName = 'personFirstName' ; /** * @inheritDoc */ protected $label = 'wcf.person.firstName' ; /** * @inheritDoc */ protected $propertyName = 'firstName' ; /** * @inheritDoc */ protected $supportsMultipleValues = true ; } $className contains the class name of the relevant database object from which the class name of the database object list is derived and $propertyName is the name of the database object's property that contains the value used for filtering. By setting $supportsMultipleValues to true , multiple comma-separated values can be specified so that, for example, a box can also only list people with either of two specific first names. $description (optional), $fieldName , and $label are used in the output of the form field. (The implementation here is specific for AbstractObjectTextPropertyCondition . The wcf\\system\\condition namespace also contains several other default condition implementations.)","title":"Conditions"},{"location":"tutorial/series/part_5/","text":"Part 5: Person Information # This part of our tutorial series lays the foundation for future parts in which we will be using additional APIs, which we have not used in this series yet. To make use of those APIs, we need content generated by users in the frontend. Package Functionality # In addition to the existing functions from part 4 , the package will provide the following functionality after this part of the tutorial: Users are able to add information on the people in the frontend. Users are able to edit and delete the pieces of information they added. Moderators are able to edit and delete all pieces of information. Used Components # In addition to the components used in previous parts, we will use the form builder API to create forms shown in dialogs instead of dedicated pages and we will, for the first time, add TypeScript code . Package Structure # The package will have the following file structure excluding unchanged files from previous parts: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u251c\u2500\u2500 js \u2502 \u2502 \u2514\u2500\u2500 WoltLabSuite \u2502 \u2502 \u2514\u2500\u2500 Core \u2502 \u2502 \u2514\u2500\u2500 Controller \u2502 \u2502 \u2514\u2500\u2500 Person.js \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u2514\u2500\u2500 information \u2502 \u2502 \u251c\u2500\u2500 PersonInformation.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonInformationAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonInformationEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonInformationList.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u2514\u2500\u2500 worker \u2502 \u2514\u2500\u2500 PersonRebuildDataWorker.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 templates \u2502 \u251c\u2500\u2500 person.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 ts \u2502 \u2514\u2500\u2500 WoltLabSuite \u2502 \u2514\u2500\u2500 Core \u2502 \u2514\u2500\u2500 Controller \u2502 \u2514\u2500\u2500 Person.ts \u2514\u2500\u2500 userGroupOption.xml For all changes, please refer to the source code on GitHub . Miscellaneous # Before we focus on the main aspects of this part, we mention some minor aspects that will be used later on: Several new user group options and the relevant language items have been added related to creating, editing, and deleting information: mod.person.canEditInformation and mod.person.canDeleteInformation are moderative permissions to edit and delete any piece of information, regardless of who created it. user.person.canAddInformation is the permission for users to add new pieces of information. user.person.canEditInformation and user.person.canDeleteInformation are the user permissions to edit and the piece of information they created. The actual information text will be entered via a WYSIWYG editor, which requires an object type of the definition com.woltlab.wcf.message : com.woltlab.wcf.people.information . personList.tpl has been adjusted to show the number of pieces of information in the person statistics section. We have not updated the person list box to also support sorting by the number of pieces of information added for each person. Person Information Model # The PHP file with the database layout has been updated as follows: files/acp/database/install_com.woltlab.wcf.people.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 <? php use wcf\\system\\database\\table\\column\\DefaultTrueBooleanDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\IntDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\NotNullInt10DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\NotNullVarchar255DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\ObjectIdDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\SmallintDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\TextDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\VarcharDatabaseTableColumn ; use wcf\\system\\database\\table\\DatabaseTable ; use wcf\\system\\database\\table\\index\\DatabaseTableForeignKey ; use wcf\\system\\database\\table\\index\\DatabaseTablePrimaryIndex ; return [ DatabaseTable :: create ( 'wcf1_person' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'personID' ), NotNullVarchar255DatabaseTableColumn :: create ( 'firstName' ), NotNullVarchar255DatabaseTableColumn :: create ( 'lastName' ), NotNullInt10DatabaseTableColumn :: create ( 'informationCount' ) -> defaultValue ( 0 ), SmallintDatabaseTableColumn :: create ( 'comments' ) -> length ( 5 ) -> notNull () -> defaultValue ( 0 ), DefaultTrueBooleanDatabaseTableColumn :: create ( 'enableComments' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'personID' ]), ]), DatabaseTable :: create ( 'wcf1_person_information' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'informationID' ), NotNullInt10DatabaseTableColumn :: create ( 'personID' ), TextDatabaseTableColumn :: create ( 'information' ), IntDatabaseTableColumn :: create ( 'userID' ) -> length ( 10 ), NotNullVarchar255DatabaseTableColumn :: create ( 'username' ), VarcharDatabaseTableColumn :: create ( 'ipAddress' ) -> length ( 39 ) -> notNull ( true ) -> defaultValue ( '' ), NotNullInt10DatabaseTableColumn :: create ( 'time' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'informationID' ]), ]) -> foreignKeys ([ DatabaseTableForeignKey :: create () -> columns ([ 'personID' ]) -> referencedTable ( 'wcf1_person' ) -> referencedColumns ([ 'personID' ]) -> onDelete ( 'CASCADE' ), DatabaseTableForeignKey :: create () -> columns ([ 'userID' ]) -> referencedTable ( 'wcf1_user' ) -> referencedColumns ([ 'userID' ]) -> onDelete ( 'SET NULL' ), ]), ]; The number of pieces of information per person is tracked via the new informationCount column. The wcf1_person_information table has been added for the PersonInformation model. The meaning of the different columns is explained in the property documentation part of PersonInformation 's documentation (see below). The two foreign keys ensure that if a person is deleted, all of their information is also deleted, and that if a user is deleted, the userID column is set to NULL . files/lib/data/person/information/PersonInformation.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\DatabaseObject ; use wcf\\data\\person\\Person ; use wcf\\data\\user\\UserProfile ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\cache\\runtime\\UserProfileRuntimeCache ; use wcf\\system\\html\\output\\HtmlOutputProcessor ; use wcf\\system\\WCF ; /** * Represents a piece of information for a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person\\Information * * @property-read int $informationID unique id of the information * @property-read int $personID id of the person the information belongs to * @property-read string $information information text * @property-read int|null $userID id of the user who added the information or `null` if the user no longer exists * @property-read string $username name of the user who added the information * @property-read int $time timestamp at which the information was created */ class PersonInformation extends DatabaseObject { /** * Returns `true` if the active user can delete this piece of information and `false` otherwise. */ public function canDelete () : bool { if ( WCF :: getUser () -> userID && WCF :: getUser () -> userID == $this -> userID && WCF :: getSession () -> getPermission ( 'user.person.canDeleteInformation' ) ) { return true ; } return WCF :: getSession () -> getPermission ( 'mod.person.canDeleteInformation' ); } /** * Returns `true` if the active user can edit this piece of information and `false` otherwise. */ public function canEdit () : bool { if ( WCF :: getUser () -> userID && WCF :: getUser () -> userID == $this -> userID && WCF :: getSession () -> getPermission ( 'user.person.canEditInformation' ) ) { return true ; } return WCF :: getSession () -> getPermission ( 'mod.person.canEditInformation' ); } /** * Returns the formatted information. */ public function getFormattedInformation () : string { $processor = new HtmlOutputProcessor (); $processor -> process ( $this -> information , 'com.woltlab.wcf.people.information' , $this -> informationID ); return $processor -> getHtml (); } /** * Returns the person the information belongs to. */ public function getPerson () : Person { return PersonRuntimeCache :: getInstance () -> getObject ( $this -> personID ); } /** * Returns the user profile of the user who added the information. */ public function getUserProfile () : UserProfile { if ( $this -> userID ) { return UserProfileRuntimeCache :: getInstance () -> getObject ( $this -> userID ); } else { return UserProfile :: getGuestUserProfile ( $this -> username ); } } } PersonInformation provides two methods, canDelete() and canEdit() , to check whether the active user can delete or edit a specific piece of information. In both cases, it is checked if the current user has created the relevant piece of information to check the user-specific permissions or to fall back to the moderator-specific permissions. There also two getter methods for the person, the piece of information belongs to ( getPerson() ), and for the user profile of the user who created the information ( getUserProfile() ). In both cases, we use runtime caches, though in getUserProfile() , we also have to consider the case of the user who created the information being deleted, i.e. userID being null . For such a case, we also save the name of the user who created the information in username , so that we can return a guest user profile object in this case. The most interesting method is getFormattedInformation() , which returns the HTML code of the information text meant for output. To generate such an output, HtmlOutputProcessor::process() is used and here is where we first use the associated message object type com.woltlab.wcf.people.information mentioned before . While PersonInformationEditor is simply the default implementation and thus not explicitly shown here, PersonInformationList::readObjects() caches the relevant ids of the associated people and users who created the pieces of information using runtime caches: files/lib/data/person/information/PersonInformationList.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\DatabaseObjectList ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\cache\\runtime\\UserProfileRuntimeCache ; /** * Represents a list of person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\PersonInformation * * @method PersonInformation current() * @method PersonInformation[] getObjects() * @method PersonInformation|null search($objectID) * @property PersonInformation[] $objects */ class PersonInformationList extends DatabaseObjectList { public function readObjects () { parent :: readObjects (); UserProfileRuntimeCache :: getInstance () -> cacheObjectIDs ( \\array_unique ( \\array_filter ( \\array_column ( $this -> objects , 'userID' )))); PersonRuntimeCache :: getInstance () -> cacheObjectIDs ( \\array_unique ( \\array_column ( $this -> objects , 'personID' ))); } } Listing and Deleting Person Information # The person.tpl template has been updated to include a block for listing the information at the beginning: templates/person.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 { capture assign = 'pageTitle' }{ $person } - { lang } wcf.person.list { /lang }{ /capture } { capture assign = 'contentTitle' }{ $person }{ /capture } { include file = 'header' } { if $person -> informationCount || $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } <section class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> { lang } wcf.person.information.list { /lang } { if $person -> informationCount } <span class=\"badge\"> { # $person -> informationCount } </span> { /if } </h2> </header> <ul class=\"commentList containerList personInformationList jsObjectActionContainer\" { * * } data-object-action-class-name=\"wcf\\data\\person\\information\\PersonInformationAction\" { * * } > { if $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } <li class=\"containerListButtonGroup\"> <ul class=\"buttonGroup\"> <li> <a href=\"#\" class=\"button\" id=\"personInformationAddButton\"> <span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.person.information.add { /lang } </span> </a> </li> </ul> </li> { /if } { foreach from = $person -> getInformation () item = $information } <li class=\"comment personInformation jsObjectActionObject\" data-object-id=\" { @ $information -> getObjectID () } \"> <div class=\"box48 { if $__wcf -> getUserProfileHandler ()-> isIgnoredUser ( $information -> userID , 2 ) } ignoredUserContent { /if } \"> { user object = $information -> getUserProfile () type = 'avatar48' ariaHidden = 'true' tabindex = '-1' } <div class=\"commentContentContainer\"> <div class=\"commentContent\"> <div class=\"containerHeadline\"> <h3> { if $information -> userID } { user object = $information -> getUserProfile () } { else } <span> { $information -> username } </span> { /if } <small class=\"separatorLeft\"> { @ $information -> time | time } </small> </h3> </div> <div class=\"htmlContent userMessage\" id=\"personInformation { @ $information -> getObjectID () } \"> { @ $information -> getFormattedInformation () } </div> <nav class=\"jsMobileNavigation buttonGroupNavigation\"> <ul class=\"buttonList iconList\"> { if $information -> canEdit () } <li class=\"jsOnly\"> <a href=\"#\" title=\" { lang } wcf.global.button.edit { /lang } \" class=\"jsEditInformation jsTooltip\"> <span class=\"icon icon16 fa-pencil\"></span> <span class=\"invisible\"> { lang } wcf.global.button.edit { /lang } </span> </a> </li> { /if } { if $information -> canDelete () } <li class=\"jsOnly\"> <a href=\"#\" title=\" { lang } wcf.global.button.delete { /lang } \" class=\"jsObjectAction jsTooltip\" data-object-action=\"delete\" data-confirm-message=\" { lang } wcf.person.information.delete.confirmMessage { /lang } \"> <span class=\"icon icon16 fa-times\"></span> <span class=\"invisible\"> { lang } wcf.global.button.edit { /lang } </span> </a> </li> { /if } { event name = 'informationOptions' } </ul> </nav> </div> </div> </div> </li> { /foreach } </ul> </section> { /if } { if $person -> enableComments } { if $commentList | count || $commentCanAdd } <section id=\"comments\" class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> { lang } wcf.person.comments { /lang } { if $person -> comments } <span class=\"badge\"> { # $person -> comments } </span> { /if } </h2> </header> { include file = '__commentJavaScript' commentContainerID = 'personCommentList' } <div class=\"personComments\"> <ul id=\"personCommentList\" class=\"commentList containerList\" { * * } data-can-add=\" { if $commentCanAdd } true { else } false { /if } \" { * * } data-object-id=\" { @ $person -> personID } \" { * * } data-object-type-id=\" { @ $commentObjectTypeID } \" { * * } data-comments=\" { if $person -> comments }{ @ $commentList -> countObjects () }{ else } 0 { /if } \" { * * } data-last-comment-time=\" { @ $lastCommentTime } \" { * * } > { include file = 'commentListAddComment' wysiwygSelector = 'personCommentListAddComment' } { include file = 'commentList' } </ul> </div> </section> { /if } { /if } <footer class=\"contentFooter\"> { hascontent } <nav class=\"contentFooterNavigation\"> <ul> { content }{ event name = 'contentFooterNavigation' }{ /content } </ul> </nav> { /hascontent } </footer> <script data-relocate=\"true\"> require(['Language', 'WoltLabSuite/Core/Controller/Person'], (Language, ControllerPerson) => { Language . addObject ( { 'wcf.person.information.add' : '{jslang}wcf.person.information.add{/jslang}' , 'wcf.person.information.add.success' : '{jslang}wcf.person.information.add.success{/jslang}' , 'wcf.person.information.edit' : '{jslang}wcf.person.information.edit{/jslang}' , 'wcf.person.information.edit.success' : '{jslang}wcf.person.information.edit.success{/jslang}' , } ); ControllerPerson . init ( { @ $person -> personID } , { canAddInformation : { if $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } true { else } false { / if } , } ); } ); </script> { include file = 'footer' } To keep things simple here, we reuse the structure and CSS classes used for comments. Additionally, we always list all pieces of information. If there are many pieces of information, a nicer solution would be a pagination or loading more pieces of information with JavaScript. First, we note the jsObjectActionContainer class in combination with the data-object-action-class-name attribute, which are needed for the delete button for each piece of information, as explained here . In PersonInformationAction , we have overridden the default implementations of validateDelete() and delete() which are called after clicking on a delete button. In validateDelete() , we call PersonInformation::canDelete() on all pieces of information to be deleted for proper permission validation, and in delete() , we update the informationCount values of the people the deleted pieces of information belong to (see below). The button to add a new piece of information, #personInformationAddButton , and the buttons to edit existing pieces of information, .jsEditInformation , are controlled with JavaScript code initialized at the very end of the template. Lastly, in create() we provide default values for the time , userID , username , and ipAddress for cases like here when creating a new piece of information, where do not explicitly provide this data. Additionally, we extract the information text from the information_htmlInputProcessor parameter provided by the associated WYSIWYG form field and update the number of pieces of information created for the relevant person. Creating and Editing Person Information # To create new pieces of information or editing existing ones, we do not add new form controllers but instead use dialogs generated by the form builder API so that the user does not have to leave the person page. When clicking on the add button or on any of the edit buttons, a dialog opens with the relevant form: ts/WoltLabSuite/Core/Controller/Person.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 /** * Provides the JavaScript code for the person page. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @module WoltLabSuite/Core/Controller/Person */ import FormBuilderDialog from \"WoltLabSuite/Core/Form/Builder/Dialog\" ; import * as Language from \"WoltLabSuite/Core/Language\" ; import * as UiNotification from \"WoltLabSuite/Core/Ui/Notification\" ; let addDialog : FormBuilderDialog ; const editDialogs = new Map < string , FormBuilderDialog > (); interface EditReturnValues { formattedInformation : string ; informationID : number ; } interface Options { canAddInformation : true ; } /** * Opens the edit dialog after clicking on the edit button for a piece of information. */ function editInformation ( event : Event ) : void { event . preventDefault (); const currentTarget = event . currentTarget as HTMLElement ; const information = currentTarget . closest ( \".jsObjectActionObject\" ) as HTMLElement ; const informationId = information . dataset . objectId ! ; if ( ! editDialogs . has ( informationId )) { editDialogs . set ( informationId , new FormBuilderDialog ( `personInformationEditDialog ${ informationId } ` , \"wcf\\\\data\\\\person\\\\information\\\\PersonInformationAction\" , \"getEditDialog\" , { actionParameters : { informationID : informationId , }, dialog : { title : Language.get ( \"wcf.person.information.edit\" ), }, submitActionName : \"submitEditDialog\" , successCallback ( returnValues : EditReturnValues ) { document . getElementById ( `personInformation ${ returnValues . informationID } ` ) ! . innerHTML = returnValues . formattedInformation ; UiNotification . show ( Language . get ( \"wcf.person.information.edit.success\" )); }, }, ), ); } editDialogs . get ( informationId ) ! . open (); } /** * Initializes the JavaScript code for the person page. */ export function init ( personId : number , options : Options ) : void { if ( options . canAddInformation ) { // Initialize the dialog to add new information. addDialog = new FormBuilderDialog ( \"personInformationAddDialog\" , \"wcf\\\\data\\\\person\\\\information\\\\PersonInformationAction\" , \"getAddDialog\" , { actionParameters : { personID : personId , }, dialog : { title : Language.get ( \"wcf.person.information.add\" ), }, submitActionName : \"submitAddDialog\" , successCallback () { UiNotification . show ( Language . get ( \"wcf.person.information.add.success\" ), () => window . location . reload ()); }, }, ); document . getElementById ( \"personInformationAddButton\" ) ! . addEventListener ( \"click\" , ( event ) => { event . preventDefault (); addDialog . open (); }); } document . querySelectorAll ( \".jsEditInformation\" ) . forEach (( el ) => el . addEventListener ( \"click\" , ( ev ) => editInformation ( ev ))); } We use the WoltLabSuite/Core/Form/Builder/Dialog module , which takes care of the internal handling with regard to these dialogs. We only have to provide some data during for initializing these objects and call the open() function after a button has been clicked. Explanation of the initialization arguments for WoltLabSuite/Core/Form/Builder/Dialog used here: The first argument is the id of the dialog used to identify it. The second argument is the PHP class name which provides the contents of the dialog's form and handles the data after the form is submitted. The third argument is the name of the method in the referenced PHP class in the previous argument that returns the dialog form. The fourth argument contains additional options: actionParameters are additional parameters send during each AJAX request. Here, we either pass the id of the person for who a new piece of information is added or the id of the edited piece of information. dialog contains the options for the dialog, see the DialogOptions interface. Here, we only provide the title of the dialog. submitActionName is the name of the method in the referenced PHP class that is called with the form data after submitting the form. successCallback is called after the submit AJAX request was successful. After adding a new piece of information, we reload the page, and after editing an existing piece of information, we update the existing information text with the updated text. (Dynamically inserting a newly added piece of information instead of reloading the page would also be possible, of course, but for this tutorial series, we kept things simple.) Next, we focus on PersonInformationAction , which actually provides the contents of these dialogs and creates and edits the information: files/lib/data/person/information/PersonInformationAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\AbstractDatabaseObjectAction ; use wcf\\data\\person\\PersonAction ; use wcf\\data\\person\\PersonEditor ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\event\\EventHandler ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\exception\\PermissionDeniedException ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\form\\builder\\container\\wysiwyg\\WysiwygFormContainer ; use wcf\\system\\form\\builder\\DialogFormDocument ; use wcf\\system\\html\\input\\HtmlInputProcessor ; use wcf\\system\\WCF ; use wcf\\util\\UserUtil ; /** * Executes person information-related actions. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person\\Information * * @method PersonInformationEditor[] getObjects() * @method PersonInformationEditor getSingleObject() */ class PersonInformationAction extends AbstractDatabaseObjectAction { /** * @var DialogFormDocument */ public $dialog ; /** * @var PersonInformation */ public $information ; /** * @return PersonInformation */ public function create () { if ( ! isset ( $this -> parameters [ 'data' ][ 'time' ])) { $this -> parameters [ 'data' ][ 'time' ] = TIME_NOW ; } if ( ! isset ( $this -> parameters [ 'data' ][ 'userID' ])) { $this -> parameters [ 'data' ][ 'userID' ] = WCF :: getUser () -> userID ; $this -> parameters [ 'data' ][ 'username' ] = WCF :: getUser () -> username ; } if ( LOG_IP_ADDRESS ) { if ( ! isset ( $this -> parameters [ 'data' ][ 'ipAddress' ])) { $this -> parameters [ 'data' ][ 'ipAddress' ] = UserUtil :: getIpAddress (); } } else { unset ( $this -> parameters [ 'data' ][ 'ipAddress' ]); } if ( ! empty ( $this -> parameters [ 'information_htmlInputProcessor' ])) { /** @var HtmlInputProcessor $htmlInputProcessor */ $htmlInputProcessor = $this -> parameters [ 'information_htmlInputProcessor' ]; $this -> parameters [ 'data' ][ 'information' ] = $htmlInputProcessor -> getHtml (); } /** @var PersonInformation $information */ $information = parent :: create (); ( new PersonAction ([ $information -> personID ], 'update' , [ 'counters' => [ 'informationCount' => 1 , ], ])) -> executeAction (); return $information ; } /** * @inheritDoc */ public function update () { if ( ! empty ( $this -> parameters [ 'information_htmlInputProcessor' ])) { /** @var HtmlInputProcessor $htmlInputProcessor */ $htmlInputProcessor = $this -> parameters [ 'information_htmlInputProcessor' ]; $this -> parameters [ 'data' ][ 'information' ] = $htmlInputProcessor -> getHtml (); } parent :: update (); } /** * @inheritDoc */ public function validateDelete () { if ( empty ( $this -> objects )) { $this -> readObjects (); if ( empty ( $this -> objects )) { throw new UserInputException ( 'objectIDs' ); } } foreach ( $this -> getObjects () as $informationEditor ) { if ( ! $informationEditor -> canDelete ()) { throw new PermissionDeniedException (); } } } /** * @inheritDoc */ public function delete () { $deleteCount = parent :: delete (); if ( ! $deleteCount ) { return $deleteCount ; } $counterUpdates = []; foreach ( $this -> getObjects () as $informationEditor ) { if ( ! isset ( $counterUpdates [ $informationEditor -> personID ])) { $counterUpdates [ $informationEditor -> personID ] = 0 ; } $counterUpdates [ $informationEditor -> personID ] -- ; } WCF :: getDB () -> beginTransaction (); foreach ( $counterUpdates as $personID => $counterUpdate ) { ( new PersonEditor ( PersonRuntimeCache :: getInstance () -> getObject ( $personID ))) -> updateCounters ([ 'informationCount' => $counterUpdate , ]); } WCF :: getDB () -> commitTransaction (); return $deleteCount ; } /** * Validates the `getAddDialog` action. */ public function validateGetAddDialog () : void { WCF :: getSession () -> checkPermissions ([ 'user.person.canAddInformation' ]); $this -> readInteger ( 'personID' ); if ( PersonRuntimeCache :: getInstance () -> getObject ( $this -> parameters [ 'personID' ]) === null ) { throw new UserInputException ( 'personID' ); } } /** * Returns the data to show the dialog to add a new piece of information on a person. * * @return string[] */ public function getAddDialog () : array { $this -> buildDialog (); return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } /** * Validates the `submitAddDialog` action. */ public function validateSubmitAddDialog () : void { $this -> validateGetAddDialog (); $this -> buildDialog (); $this -> dialog -> requestData ( $_POST [ 'parameters' ][ 'data' ] ?? []); $this -> dialog -> readValues (); $this -> dialog -> validate (); } /** * Creates a new piece of information on a person after submitting the dialog. * * @return string[] */ public function submitAddDialog () : array { // If there are any validation errors, show the form again. if ( $this -> dialog -> hasValidationErrors ()) { return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } ( new static ([], 'create' , \\array_merge ( $this -> dialog -> getData (), [ 'data' => [ 'personID' => $this -> parameters [ 'personID' ], ], ]))) -> executeAction (); return []; } /** * Validates the `getEditDialog` action. */ public function validateGetEditDialog () : void { WCF :: getSession () -> checkPermissions ([ 'user.person.canAddInformation' ]); $this -> readInteger ( 'informationID' ); $this -> information = new PersonInformation ( $this -> parameters [ 'informationID' ]); if ( ! $this -> information -> getObjectID ()) { throw new UserInputException ( 'informationID' ); } if ( ! $this -> information -> canEdit ()) { throw new IllegalLinkException (); } } /** * Returns the data to show the dialog to edit a piece of information on a person. * * @return string[] */ public function getEditDialog () : array { $this -> buildDialog (); $this -> dialog -> updatedObject ( $this -> information ); return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } /** * Validates the `submitEditDialog` action. */ public function validateSubmitEditDialog () : void { $this -> validateGetEditDialog (); $this -> buildDialog (); $this -> dialog -> updatedObject ( $this -> information , false ); $this -> dialog -> requestData ( $_POST [ 'parameters' ][ 'data' ] ?? []); $this -> dialog -> readValues (); $this -> dialog -> validate (); } /** * Updates a piece of information on a person after submitting the edit dialog. * * @return string[] */ public function submitEditDialog () : array { // If there are any validation errors, show the form again. if ( $this -> dialog -> hasValidationErrors ()) { return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } ( new static ([ $this -> information ], 'update' , $this -> dialog -> getData ())) -> executeAction (); // Reload the information with the updated data. $information = new PersonInformation ( $this -> information -> getObjectID ()); return [ 'formattedInformation' => $information -> getFormattedInformation (), 'informationID' => $this -> information -> getObjectID (), ]; } /** * Builds the dialog to create or edit person information. */ protected function buildDialog () : void { if ( $this -> dialog !== null ) { return ; } $this -> dialog = DialogFormDocument :: create ( 'personInformationAddDialog' ) -> appendChild ( WysiwygFormContainer :: create ( 'information' ) -> messageObjectType ( 'com.woltlab.wcf.people.information' ) -> required () ); EventHandler :: getInstance () -> fireAction ( $this , 'buildDialog' ); $this -> dialog -> build (); } } When setting up the WoltLabSuite/Core/Form/Builder/Dialog object for adding new pieces of information, we specified getAddDialog and submitAddDialog as the names of the dialog getter and submit handler. In addition to these two methods, the matching validation methods validateGetAddDialog() and validateGetAddDialog() are also added. As the forms for adding and editing pieces of information have the same structure, this form is created in buildDialog() using a DialogFormDocument object, which is intended for forms in dialogs. We fire an event in buildDialog() so that plugins are able to easily extend the dialog with additional data. validateGetAddDialog() checks if the user has the permission to create new pieces of information and if a valid id for the person, the information will belong to, is given. The method configured in the WoltLabSuite/Core/Form/Builder/Dialog object returning the dialog is expected to return two values: the id of the form ( formId ) and the contents of form shown in the dialog ( dialog ). This data is returned by getAddDialog using the dialog build previously by buildDialog() . After the form is submitted, validateSubmitAddDialog() has to do the same basic validation as validateGetAddDialog() so that validateGetAddDialog() is simply called. Additionally, the form data is read and validated. In submitAddDialog() , we first check if there have been any validation errors: If any error occured during validation, we return the same data as in getAddDialog() so that the dialog is shown again with the erroneous fields marked as such. Otherwise, if the validation succeeded, the form data is used to create the new piece of information. In addition to the form data, we manually add the id of the person to whom the information belongs to. Lastly, we could return some data that we could access in the JavaScript callback function after successfully submitting the dialog. As we will simply be reloading the page, no such data is returned. An alternative to reloading to the page would be dynamically inserting the new piece of information in the list so that we would have to return the rendered list item for the new piece of information. The process for getting and submitting the dialog to edit existing pieces of information is similar to the process for adding new pieces of information. Instead of the id of the person, however, we now pass the id of the edited piece of information and in submitEditDialog() , we update the edited information instead of creating a new one like in submitAddDialog() . After editing a piece of information, we do not reload the page but dynamically update the text of the information in the TypeScript code so that we return the updated rendered information text and id of the edited pieced of information in submitAddDialog() . Rebuild Data Worker # To ensure the integrity of the person data, PersonRebuildDataWorker updates the informationCount counter: files/lib/system/worker/PersonRebuildDataWorker.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 <? php namespace wcf\\system\\worker ; use wcf\\data\\person\\PersonList ; use wcf\\system\\WCF ; /** * Worker implementation for updating people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Worker * * @method PersonList getObjectList() */ class PersonRebuildDataWorker extends AbstractRebuildDataWorker { /** * @inheritDoc */ protected $limit = 500 ; /** * @inheritDoc */ protected $objectListClassName = PersonList :: class ; /** * @inheritDoc */ protected function initObjectList () { parent :: initObjectList (); $this -> objectList -> sqlOrderBy = 'person.personID' ; } /** * @inheritDoc */ public function execute () { parent :: execute (); if ( ! \\count ( $this -> objectList )) { return ; } $sql = \"UPDATE wcf\" . WCF_N . \"_person person SET informationCount = ( SELECT COUNT(*) FROM wcf\" . WCF_N . \"_person_information person_information WHERE person_information.personID = person.personID ) WHERE person.personID = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); WCF :: getDB () -> beginTransaction (); foreach ( $this -> getObjectList () as $person ) { $statement -> execute ([ $person -> personID ]); } WCF :: getDB () -> commitTransaction (); } } Username and IP Address Event Listeners # As we store the name of the user who create a new piece of information and store their IP address, we have to add event listeners to properly handle the following scenarios: If the user is renamed, the value of username stored with the person information has to be updated, which can be achieved by a simple event listener that only has to specify the name of relevant database table if AbstractUserActionRenameListener is extended: files/lib/system/event/listener/PersonUserActionRenameListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; /** * Updates person information during user renaming. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserActionRenameListener extends AbstractUserActionRenameListener { /** * @inheritDoc */ protected $databaseTables = [ 'wcf{WCF_N}_person_information' , ]; } If users are merged, all pieces of information need to be assigned to the target user of the merging. Again, we only have to specify the name of relevant database table if AbstractUserMergeListener is extended: files/lib/system/event/listener/PersonUserMergeListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; /** * Updates person information during user merging. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserMergeListener extends AbstractUserMergeListener { /** * @inheritDoc */ protected $databaseTables = [ 'wcf{WCF_N}_person_information' , ]; } If the option to prune stored ip addresses after a certain period of time is enabled, we also have to prune them in the person information database table. Here we also only have to specify the name of the relevant database table and provide the mapping from the ipAddress column to the time column: files/lib/system/event/listener/PersonPruneIpAddressesCronjobListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\cronjob\\PruneIpAddressesCronjob ; /** * Prunes old ip addresses. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonPruneIpAddressesCronjobListener extends AbstractEventListener { protected function onExecute ( PruneIpAddressesCronjob $cronjob ) : void { $cronjob -> columns [ 'wcf' . WCF_N . '_person_information' ][ 'ipAddress' ] = 'time' ; } } The ip addresses in the person information database table also have to be considered for the user data export which can also be done with minimal effort by providing the name of the relevant database table: files/lib/system/event/listener/PersonUserExportGdprListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\action\\UserExportGdprAction ; /** * Adds the ip addresses stored with the person information during user data export. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserExportGdprListener extends AbstractEventListener { protected function onExport ( UserExportGdprAction $action ) : void { $action -> ipAddresses [ 'com.woltlab.wcf.people' ] = [ 'wcf' . WCF_N . '_person_information' ]; } } Lastly, we present the updated eventListener.xml file with new entries for all of these event listeners: eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd\" > <import> <eventlistener name= \"rename@wcf\\data\\user\\UserAction\" > <eventclassname> wcf\\data\\user\\UserAction </eventclassname> <eventname> rename </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserActionRenameListener </listenerclassname> <environment> all </environment> </eventlistener> <eventlistener name= \"save@wcf\\acp\\form\\UserMergeForm\" > <eventclassname> wcf\\acp\\form\\UserMergeForm </eventclassname> <eventname> save </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserMergeListener </listenerclassname> <environment> admin </environment> </eventlistener> <eventlistener name= \"execute@wcf\\system\\cronjob\\PruneIpAddressesCronjob\" > <eventclassname> wcf\\system\\cronjob\\PruneIpAddressesCronjob </eventclassname> <eventname> execute </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonPruneIpAddressesCronjobListener </listenerclassname> <environment> all </environment> </eventlistener> <eventlistener name= \"export@wcf\\acp\\action\\UserExportGdprAction\" > <eventclassname> wcf\\acp\\action\\UserExportGdprAction </eventclassname> <eventname> export </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserExportGdprListener </listenerclassname> <environment> admin </environment> </eventlistener> </import> </data>","title":"Part 5"},{"location":"tutorial/series/part_5/#part-5-person-information","text":"This part of our tutorial series lays the foundation for future parts in which we will be using additional APIs, which we have not used in this series yet. To make use of those APIs, we need content generated by users in the frontend.","title":"Part 5: Person Information"},{"location":"tutorial/series/part_5/#package-functionality","text":"In addition to the existing functions from part 4 , the package will provide the following functionality after this part of the tutorial: Users are able to add information on the people in the frontend. Users are able to edit and delete the pieces of information they added. Moderators are able to edit and delete all pieces of information.","title":"Package Functionality"},{"location":"tutorial/series/part_5/#used-components","text":"In addition to the components used in previous parts, we will use the form builder API to create forms shown in dialogs instead of dedicated pages and we will, for the first time, add TypeScript code .","title":"Used Components"},{"location":"tutorial/series/part_5/#package-structure","text":"The package will have the following file structure excluding unchanged files from previous parts: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u251c\u2500\u2500 js \u2502 \u2502 \u2514\u2500\u2500 WoltLabSuite \u2502 \u2502 \u2514\u2500\u2500 Core \u2502 \u2502 \u2514\u2500\u2500 Controller \u2502 \u2502 \u2514\u2500\u2500 Person.js \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u2514\u2500\u2500 information \u2502 \u2502 \u251c\u2500\u2500 PersonInformation.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonInformationAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonInformationEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonInformationList.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u2514\u2500\u2500 worker \u2502 \u2514\u2500\u2500 PersonRebuildDataWorker.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 templates \u2502 \u251c\u2500\u2500 person.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 ts \u2502 \u2514\u2500\u2500 WoltLabSuite \u2502 \u2514\u2500\u2500 Core \u2502 \u2514\u2500\u2500 Controller \u2502 \u2514\u2500\u2500 Person.ts \u2514\u2500\u2500 userGroupOption.xml For all changes, please refer to the source code on GitHub .","title":"Package Structure"},{"location":"tutorial/series/part_5/#miscellaneous","text":"Before we focus on the main aspects of this part, we mention some minor aspects that will be used later on: Several new user group options and the relevant language items have been added related to creating, editing, and deleting information: mod.person.canEditInformation and mod.person.canDeleteInformation are moderative permissions to edit and delete any piece of information, regardless of who created it. user.person.canAddInformation is the permission for users to add new pieces of information. user.person.canEditInformation and user.person.canDeleteInformation are the user permissions to edit and the piece of information they created. The actual information text will be entered via a WYSIWYG editor, which requires an object type of the definition com.woltlab.wcf.message : com.woltlab.wcf.people.information . personList.tpl has been adjusted to show the number of pieces of information in the person statistics section. We have not updated the person list box to also support sorting by the number of pieces of information added for each person.","title":"Miscellaneous"},{"location":"tutorial/series/part_5/#person-information-model","text":"The PHP file with the database layout has been updated as follows: files/acp/database/install_com.woltlab.wcf.people.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 <? php use wcf\\system\\database\\table\\column\\DefaultTrueBooleanDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\IntDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\NotNullInt10DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\NotNullVarchar255DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\ObjectIdDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\SmallintDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\TextDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\VarcharDatabaseTableColumn ; use wcf\\system\\database\\table\\DatabaseTable ; use wcf\\system\\database\\table\\index\\DatabaseTableForeignKey ; use wcf\\system\\database\\table\\index\\DatabaseTablePrimaryIndex ; return [ DatabaseTable :: create ( 'wcf1_person' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'personID' ), NotNullVarchar255DatabaseTableColumn :: create ( 'firstName' ), NotNullVarchar255DatabaseTableColumn :: create ( 'lastName' ), NotNullInt10DatabaseTableColumn :: create ( 'informationCount' ) -> defaultValue ( 0 ), SmallintDatabaseTableColumn :: create ( 'comments' ) -> length ( 5 ) -> notNull () -> defaultValue ( 0 ), DefaultTrueBooleanDatabaseTableColumn :: create ( 'enableComments' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'personID' ]), ]), DatabaseTable :: create ( 'wcf1_person_information' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'informationID' ), NotNullInt10DatabaseTableColumn :: create ( 'personID' ), TextDatabaseTableColumn :: create ( 'information' ), IntDatabaseTableColumn :: create ( 'userID' ) -> length ( 10 ), NotNullVarchar255DatabaseTableColumn :: create ( 'username' ), VarcharDatabaseTableColumn :: create ( 'ipAddress' ) -> length ( 39 ) -> notNull ( true ) -> defaultValue ( '' ), NotNullInt10DatabaseTableColumn :: create ( 'time' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'informationID' ]), ]) -> foreignKeys ([ DatabaseTableForeignKey :: create () -> columns ([ 'personID' ]) -> referencedTable ( 'wcf1_person' ) -> referencedColumns ([ 'personID' ]) -> onDelete ( 'CASCADE' ), DatabaseTableForeignKey :: create () -> columns ([ 'userID' ]) -> referencedTable ( 'wcf1_user' ) -> referencedColumns ([ 'userID' ]) -> onDelete ( 'SET NULL' ), ]), ]; The number of pieces of information per person is tracked via the new informationCount column. The wcf1_person_information table has been added for the PersonInformation model. The meaning of the different columns is explained in the property documentation part of PersonInformation 's documentation (see below). The two foreign keys ensure that if a person is deleted, all of their information is also deleted, and that if a user is deleted, the userID column is set to NULL . files/lib/data/person/information/PersonInformation.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\DatabaseObject ; use wcf\\data\\person\\Person ; use wcf\\data\\user\\UserProfile ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\cache\\runtime\\UserProfileRuntimeCache ; use wcf\\system\\html\\output\\HtmlOutputProcessor ; use wcf\\system\\WCF ; /** * Represents a piece of information for a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person\\Information * * @property-read int $informationID unique id of the information * @property-read int $personID id of the person the information belongs to * @property-read string $information information text * @property-read int|null $userID id of the user who added the information or `null` if the user no longer exists * @property-read string $username name of the user who added the information * @property-read int $time timestamp at which the information was created */ class PersonInformation extends DatabaseObject { /** * Returns `true` if the active user can delete this piece of information and `false` otherwise. */ public function canDelete () : bool { if ( WCF :: getUser () -> userID && WCF :: getUser () -> userID == $this -> userID && WCF :: getSession () -> getPermission ( 'user.person.canDeleteInformation' ) ) { return true ; } return WCF :: getSession () -> getPermission ( 'mod.person.canDeleteInformation' ); } /** * Returns `true` if the active user can edit this piece of information and `false` otherwise. */ public function canEdit () : bool { if ( WCF :: getUser () -> userID && WCF :: getUser () -> userID == $this -> userID && WCF :: getSession () -> getPermission ( 'user.person.canEditInformation' ) ) { return true ; } return WCF :: getSession () -> getPermission ( 'mod.person.canEditInformation' ); } /** * Returns the formatted information. */ public function getFormattedInformation () : string { $processor = new HtmlOutputProcessor (); $processor -> process ( $this -> information , 'com.woltlab.wcf.people.information' , $this -> informationID ); return $processor -> getHtml (); } /** * Returns the person the information belongs to. */ public function getPerson () : Person { return PersonRuntimeCache :: getInstance () -> getObject ( $this -> personID ); } /** * Returns the user profile of the user who added the information. */ public function getUserProfile () : UserProfile { if ( $this -> userID ) { return UserProfileRuntimeCache :: getInstance () -> getObject ( $this -> userID ); } else { return UserProfile :: getGuestUserProfile ( $this -> username ); } } } PersonInformation provides two methods, canDelete() and canEdit() , to check whether the active user can delete or edit a specific piece of information. In both cases, it is checked if the current user has created the relevant piece of information to check the user-specific permissions or to fall back to the moderator-specific permissions. There also two getter methods for the person, the piece of information belongs to ( getPerson() ), and for the user profile of the user who created the information ( getUserProfile() ). In both cases, we use runtime caches, though in getUserProfile() , we also have to consider the case of the user who created the information being deleted, i.e. userID being null . For such a case, we also save the name of the user who created the information in username , so that we can return a guest user profile object in this case. The most interesting method is getFormattedInformation() , which returns the HTML code of the information text meant for output. To generate such an output, HtmlOutputProcessor::process() is used and here is where we first use the associated message object type com.woltlab.wcf.people.information mentioned before . While PersonInformationEditor is simply the default implementation and thus not explicitly shown here, PersonInformationList::readObjects() caches the relevant ids of the associated people and users who created the pieces of information using runtime caches: files/lib/data/person/information/PersonInformationList.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\DatabaseObjectList ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\cache\\runtime\\UserProfileRuntimeCache ; /** * Represents a list of person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\PersonInformation * * @method PersonInformation current() * @method PersonInformation[] getObjects() * @method PersonInformation|null search($objectID) * @property PersonInformation[] $objects */ class PersonInformationList extends DatabaseObjectList { public function readObjects () { parent :: readObjects (); UserProfileRuntimeCache :: getInstance () -> cacheObjectIDs ( \\array_unique ( \\array_filter ( \\array_column ( $this -> objects , 'userID' )))); PersonRuntimeCache :: getInstance () -> cacheObjectIDs ( \\array_unique ( \\array_column ( $this -> objects , 'personID' ))); } }","title":"Person Information Model"},{"location":"tutorial/series/part_5/#listing-and-deleting-person-information","text":"The person.tpl template has been updated to include a block for listing the information at the beginning: templates/person.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 { capture assign = 'pageTitle' }{ $person } - { lang } wcf.person.list { /lang }{ /capture } { capture assign = 'contentTitle' }{ $person }{ /capture } { include file = 'header' } { if $person -> informationCount || $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } <section class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> { lang } wcf.person.information.list { /lang } { if $person -> informationCount } <span class=\"badge\"> { # $person -> informationCount } </span> { /if } </h2> </header> <ul class=\"commentList containerList personInformationList jsObjectActionContainer\" { * * } data-object-action-class-name=\"wcf\\data\\person\\information\\PersonInformationAction\" { * * } > { if $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } <li class=\"containerListButtonGroup\"> <ul class=\"buttonGroup\"> <li> <a href=\"#\" class=\"button\" id=\"personInformationAddButton\"> <span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.person.information.add { /lang } </span> </a> </li> </ul> </li> { /if } { foreach from = $person -> getInformation () item = $information } <li class=\"comment personInformation jsObjectActionObject\" data-object-id=\" { @ $information -> getObjectID () } \"> <div class=\"box48 { if $__wcf -> getUserProfileHandler ()-> isIgnoredUser ( $information -> userID , 2 ) } ignoredUserContent { /if } \"> { user object = $information -> getUserProfile () type = 'avatar48' ariaHidden = 'true' tabindex = '-1' } <div class=\"commentContentContainer\"> <div class=\"commentContent\"> <div class=\"containerHeadline\"> <h3> { if $information -> userID } { user object = $information -> getUserProfile () } { else } <span> { $information -> username } </span> { /if } <small class=\"separatorLeft\"> { @ $information -> time | time } </small> </h3> </div> <div class=\"htmlContent userMessage\" id=\"personInformation { @ $information -> getObjectID () } \"> { @ $information -> getFormattedInformation () } </div> <nav class=\"jsMobileNavigation buttonGroupNavigation\"> <ul class=\"buttonList iconList\"> { if $information -> canEdit () } <li class=\"jsOnly\"> <a href=\"#\" title=\" { lang } wcf.global.button.edit { /lang } \" class=\"jsEditInformation jsTooltip\"> <span class=\"icon icon16 fa-pencil\"></span> <span class=\"invisible\"> { lang } wcf.global.button.edit { /lang } </span> </a> </li> { /if } { if $information -> canDelete () } <li class=\"jsOnly\"> <a href=\"#\" title=\" { lang } wcf.global.button.delete { /lang } \" class=\"jsObjectAction jsTooltip\" data-object-action=\"delete\" data-confirm-message=\" { lang } wcf.person.information.delete.confirmMessage { /lang } \"> <span class=\"icon icon16 fa-times\"></span> <span class=\"invisible\"> { lang } wcf.global.button.edit { /lang } </span> </a> </li> { /if } { event name = 'informationOptions' } </ul> </nav> </div> </div> </div> </li> { /foreach } </ul> </section> { /if } { if $person -> enableComments } { if $commentList | count || $commentCanAdd } <section id=\"comments\" class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> { lang } wcf.person.comments { /lang } { if $person -> comments } <span class=\"badge\"> { # $person -> comments } </span> { /if } </h2> </header> { include file = '__commentJavaScript' commentContainerID = 'personCommentList' } <div class=\"personComments\"> <ul id=\"personCommentList\" class=\"commentList containerList\" { * * } data-can-add=\" { if $commentCanAdd } true { else } false { /if } \" { * * } data-object-id=\" { @ $person -> personID } \" { * * } data-object-type-id=\" { @ $commentObjectTypeID } \" { * * } data-comments=\" { if $person -> comments }{ @ $commentList -> countObjects () }{ else } 0 { /if } \" { * * } data-last-comment-time=\" { @ $lastCommentTime } \" { * * } > { include file = 'commentListAddComment' wysiwygSelector = 'personCommentListAddComment' } { include file = 'commentList' } </ul> </div> </section> { /if } { /if } <footer class=\"contentFooter\"> { hascontent } <nav class=\"contentFooterNavigation\"> <ul> { content }{ event name = 'contentFooterNavigation' }{ /content } </ul> </nav> { /hascontent } </footer> <script data-relocate=\"true\"> require(['Language', 'WoltLabSuite/Core/Controller/Person'], (Language, ControllerPerson) => { Language . addObject ( { 'wcf.person.information.add' : '{jslang}wcf.person.information.add{/jslang}' , 'wcf.person.information.add.success' : '{jslang}wcf.person.information.add.success{/jslang}' , 'wcf.person.information.edit' : '{jslang}wcf.person.information.edit{/jslang}' , 'wcf.person.information.edit.success' : '{jslang}wcf.person.information.edit.success{/jslang}' , } ); ControllerPerson . init ( { @ $person -> personID } , { canAddInformation : { if $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } true { else } false { / if } , } ); } ); </script> { include file = 'footer' } To keep things simple here, we reuse the structure and CSS classes used for comments. Additionally, we always list all pieces of information. If there are many pieces of information, a nicer solution would be a pagination or loading more pieces of information with JavaScript. First, we note the jsObjectActionContainer class in combination with the data-object-action-class-name attribute, which are needed for the delete button for each piece of information, as explained here . In PersonInformationAction , we have overridden the default implementations of validateDelete() and delete() which are called after clicking on a delete button. In validateDelete() , we call PersonInformation::canDelete() on all pieces of information to be deleted for proper permission validation, and in delete() , we update the informationCount values of the people the deleted pieces of information belong to (see below). The button to add a new piece of information, #personInformationAddButton , and the buttons to edit existing pieces of information, .jsEditInformation , are controlled with JavaScript code initialized at the very end of the template. Lastly, in create() we provide default values for the time , userID , username , and ipAddress for cases like here when creating a new piece of information, where do not explicitly provide this data. Additionally, we extract the information text from the information_htmlInputProcessor parameter provided by the associated WYSIWYG form field and update the number of pieces of information created for the relevant person.","title":"Listing and Deleting Person Information"},{"location":"tutorial/series/part_5/#creating-and-editing-person-information","text":"To create new pieces of information or editing existing ones, we do not add new form controllers but instead use dialogs generated by the form builder API so that the user does not have to leave the person page. When clicking on the add button or on any of the edit buttons, a dialog opens with the relevant form: ts/WoltLabSuite/Core/Controller/Person.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 /** * Provides the JavaScript code for the person page. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @module WoltLabSuite/Core/Controller/Person */ import FormBuilderDialog from \"WoltLabSuite/Core/Form/Builder/Dialog\" ; import * as Language from \"WoltLabSuite/Core/Language\" ; import * as UiNotification from \"WoltLabSuite/Core/Ui/Notification\" ; let addDialog : FormBuilderDialog ; const editDialogs = new Map < string , FormBuilderDialog > (); interface EditReturnValues { formattedInformation : string ; informationID : number ; } interface Options { canAddInformation : true ; } /** * Opens the edit dialog after clicking on the edit button for a piece of information. */ function editInformation ( event : Event ) : void { event . preventDefault (); const currentTarget = event . currentTarget as HTMLElement ; const information = currentTarget . closest ( \".jsObjectActionObject\" ) as HTMLElement ; const informationId = information . dataset . objectId ! ; if ( ! editDialogs . has ( informationId )) { editDialogs . set ( informationId , new FormBuilderDialog ( `personInformationEditDialog ${ informationId } ` , \"wcf\\\\data\\\\person\\\\information\\\\PersonInformationAction\" , \"getEditDialog\" , { actionParameters : { informationID : informationId , }, dialog : { title : Language.get ( \"wcf.person.information.edit\" ), }, submitActionName : \"submitEditDialog\" , successCallback ( returnValues : EditReturnValues ) { document . getElementById ( `personInformation ${ returnValues . informationID } ` ) ! . innerHTML = returnValues . formattedInformation ; UiNotification . show ( Language . get ( \"wcf.person.information.edit.success\" )); }, }, ), ); } editDialogs . get ( informationId ) ! . open (); } /** * Initializes the JavaScript code for the person page. */ export function init ( personId : number , options : Options ) : void { if ( options . canAddInformation ) { // Initialize the dialog to add new information. addDialog = new FormBuilderDialog ( \"personInformationAddDialog\" , \"wcf\\\\data\\\\person\\\\information\\\\PersonInformationAction\" , \"getAddDialog\" , { actionParameters : { personID : personId , }, dialog : { title : Language.get ( \"wcf.person.information.add\" ), }, submitActionName : \"submitAddDialog\" , successCallback () { UiNotification . show ( Language . get ( \"wcf.person.information.add.success\" ), () => window . location . reload ()); }, }, ); document . getElementById ( \"personInformationAddButton\" ) ! . addEventListener ( \"click\" , ( event ) => { event . preventDefault (); addDialog . open (); }); } document . querySelectorAll ( \".jsEditInformation\" ) . forEach (( el ) => el . addEventListener ( \"click\" , ( ev ) => editInformation ( ev ))); } We use the WoltLabSuite/Core/Form/Builder/Dialog module , which takes care of the internal handling with regard to these dialogs. We only have to provide some data during for initializing these objects and call the open() function after a button has been clicked. Explanation of the initialization arguments for WoltLabSuite/Core/Form/Builder/Dialog used here: The first argument is the id of the dialog used to identify it. The second argument is the PHP class name which provides the contents of the dialog's form and handles the data after the form is submitted. The third argument is the name of the method in the referenced PHP class in the previous argument that returns the dialog form. The fourth argument contains additional options: actionParameters are additional parameters send during each AJAX request. Here, we either pass the id of the person for who a new piece of information is added or the id of the edited piece of information. dialog contains the options for the dialog, see the DialogOptions interface. Here, we only provide the title of the dialog. submitActionName is the name of the method in the referenced PHP class that is called with the form data after submitting the form. successCallback is called after the submit AJAX request was successful. After adding a new piece of information, we reload the page, and after editing an existing piece of information, we update the existing information text with the updated text. (Dynamically inserting a newly added piece of information instead of reloading the page would also be possible, of course, but for this tutorial series, we kept things simple.) Next, we focus on PersonInformationAction , which actually provides the contents of these dialogs and creates and edits the information: files/lib/data/person/information/PersonInformationAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\AbstractDatabaseObjectAction ; use wcf\\data\\person\\PersonAction ; use wcf\\data\\person\\PersonEditor ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\event\\EventHandler ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\exception\\PermissionDeniedException ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\form\\builder\\container\\wysiwyg\\WysiwygFormContainer ; use wcf\\system\\form\\builder\\DialogFormDocument ; use wcf\\system\\html\\input\\HtmlInputProcessor ; use wcf\\system\\WCF ; use wcf\\util\\UserUtil ; /** * Executes person information-related actions. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person\\Information * * @method PersonInformationEditor[] getObjects() * @method PersonInformationEditor getSingleObject() */ class PersonInformationAction extends AbstractDatabaseObjectAction { /** * @var DialogFormDocument */ public $dialog ; /** * @var PersonInformation */ public $information ; /** * @return PersonInformation */ public function create () { if ( ! isset ( $this -> parameters [ 'data' ][ 'time' ])) { $this -> parameters [ 'data' ][ 'time' ] = TIME_NOW ; } if ( ! isset ( $this -> parameters [ 'data' ][ 'userID' ])) { $this -> parameters [ 'data' ][ 'userID' ] = WCF :: getUser () -> userID ; $this -> parameters [ 'data' ][ 'username' ] = WCF :: getUser () -> username ; } if ( LOG_IP_ADDRESS ) { if ( ! isset ( $this -> parameters [ 'data' ][ 'ipAddress' ])) { $this -> parameters [ 'data' ][ 'ipAddress' ] = UserUtil :: getIpAddress (); } } else { unset ( $this -> parameters [ 'data' ][ 'ipAddress' ]); } if ( ! empty ( $this -> parameters [ 'information_htmlInputProcessor' ])) { /** @var HtmlInputProcessor $htmlInputProcessor */ $htmlInputProcessor = $this -> parameters [ 'information_htmlInputProcessor' ]; $this -> parameters [ 'data' ][ 'information' ] = $htmlInputProcessor -> getHtml (); } /** @var PersonInformation $information */ $information = parent :: create (); ( new PersonAction ([ $information -> personID ], 'update' , [ 'counters' => [ 'informationCount' => 1 , ], ])) -> executeAction (); return $information ; } /** * @inheritDoc */ public function update () { if ( ! empty ( $this -> parameters [ 'information_htmlInputProcessor' ])) { /** @var HtmlInputProcessor $htmlInputProcessor */ $htmlInputProcessor = $this -> parameters [ 'information_htmlInputProcessor' ]; $this -> parameters [ 'data' ][ 'information' ] = $htmlInputProcessor -> getHtml (); } parent :: update (); } /** * @inheritDoc */ public function validateDelete () { if ( empty ( $this -> objects )) { $this -> readObjects (); if ( empty ( $this -> objects )) { throw new UserInputException ( 'objectIDs' ); } } foreach ( $this -> getObjects () as $informationEditor ) { if ( ! $informationEditor -> canDelete ()) { throw new PermissionDeniedException (); } } } /** * @inheritDoc */ public function delete () { $deleteCount = parent :: delete (); if ( ! $deleteCount ) { return $deleteCount ; } $counterUpdates = []; foreach ( $this -> getObjects () as $informationEditor ) { if ( ! isset ( $counterUpdates [ $informationEditor -> personID ])) { $counterUpdates [ $informationEditor -> personID ] = 0 ; } $counterUpdates [ $informationEditor -> personID ] -- ; } WCF :: getDB () -> beginTransaction (); foreach ( $counterUpdates as $personID => $counterUpdate ) { ( new PersonEditor ( PersonRuntimeCache :: getInstance () -> getObject ( $personID ))) -> updateCounters ([ 'informationCount' => $counterUpdate , ]); } WCF :: getDB () -> commitTransaction (); return $deleteCount ; } /** * Validates the `getAddDialog` action. */ public function validateGetAddDialog () : void { WCF :: getSession () -> checkPermissions ([ 'user.person.canAddInformation' ]); $this -> readInteger ( 'personID' ); if ( PersonRuntimeCache :: getInstance () -> getObject ( $this -> parameters [ 'personID' ]) === null ) { throw new UserInputException ( 'personID' ); } } /** * Returns the data to show the dialog to add a new piece of information on a person. * * @return string[] */ public function getAddDialog () : array { $this -> buildDialog (); return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } /** * Validates the `submitAddDialog` action. */ public function validateSubmitAddDialog () : void { $this -> validateGetAddDialog (); $this -> buildDialog (); $this -> dialog -> requestData ( $_POST [ 'parameters' ][ 'data' ] ?? []); $this -> dialog -> readValues (); $this -> dialog -> validate (); } /** * Creates a new piece of information on a person after submitting the dialog. * * @return string[] */ public function submitAddDialog () : array { // If there are any validation errors, show the form again. if ( $this -> dialog -> hasValidationErrors ()) { return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } ( new static ([], 'create' , \\array_merge ( $this -> dialog -> getData (), [ 'data' => [ 'personID' => $this -> parameters [ 'personID' ], ], ]))) -> executeAction (); return []; } /** * Validates the `getEditDialog` action. */ public function validateGetEditDialog () : void { WCF :: getSession () -> checkPermissions ([ 'user.person.canAddInformation' ]); $this -> readInteger ( 'informationID' ); $this -> information = new PersonInformation ( $this -> parameters [ 'informationID' ]); if ( ! $this -> information -> getObjectID ()) { throw new UserInputException ( 'informationID' ); } if ( ! $this -> information -> canEdit ()) { throw new IllegalLinkException (); } } /** * Returns the data to show the dialog to edit a piece of information on a person. * * @return string[] */ public function getEditDialog () : array { $this -> buildDialog (); $this -> dialog -> updatedObject ( $this -> information ); return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } /** * Validates the `submitEditDialog` action. */ public function validateSubmitEditDialog () : void { $this -> validateGetEditDialog (); $this -> buildDialog (); $this -> dialog -> updatedObject ( $this -> information , false ); $this -> dialog -> requestData ( $_POST [ 'parameters' ][ 'data' ] ?? []); $this -> dialog -> readValues (); $this -> dialog -> validate (); } /** * Updates a piece of information on a person after submitting the edit dialog. * * @return string[] */ public function submitEditDialog () : array { // If there are any validation errors, show the form again. if ( $this -> dialog -> hasValidationErrors ()) { return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } ( new static ([ $this -> information ], 'update' , $this -> dialog -> getData ())) -> executeAction (); // Reload the information with the updated data. $information = new PersonInformation ( $this -> information -> getObjectID ()); return [ 'formattedInformation' => $information -> getFormattedInformation (), 'informationID' => $this -> information -> getObjectID (), ]; } /** * Builds the dialog to create or edit person information. */ protected function buildDialog () : void { if ( $this -> dialog !== null ) { return ; } $this -> dialog = DialogFormDocument :: create ( 'personInformationAddDialog' ) -> appendChild ( WysiwygFormContainer :: create ( 'information' ) -> messageObjectType ( 'com.woltlab.wcf.people.information' ) -> required () ); EventHandler :: getInstance () -> fireAction ( $this , 'buildDialog' ); $this -> dialog -> build (); } } When setting up the WoltLabSuite/Core/Form/Builder/Dialog object for adding new pieces of information, we specified getAddDialog and submitAddDialog as the names of the dialog getter and submit handler. In addition to these two methods, the matching validation methods validateGetAddDialog() and validateGetAddDialog() are also added. As the forms for adding and editing pieces of information have the same structure, this form is created in buildDialog() using a DialogFormDocument object, which is intended for forms in dialogs. We fire an event in buildDialog() so that plugins are able to easily extend the dialog with additional data. validateGetAddDialog() checks if the user has the permission to create new pieces of information and if a valid id for the person, the information will belong to, is given. The method configured in the WoltLabSuite/Core/Form/Builder/Dialog object returning the dialog is expected to return two values: the id of the form ( formId ) and the contents of form shown in the dialog ( dialog ). This data is returned by getAddDialog using the dialog build previously by buildDialog() . After the form is submitted, validateSubmitAddDialog() has to do the same basic validation as validateGetAddDialog() so that validateGetAddDialog() is simply called. Additionally, the form data is read and validated. In submitAddDialog() , we first check if there have been any validation errors: If any error occured during validation, we return the same data as in getAddDialog() so that the dialog is shown again with the erroneous fields marked as such. Otherwise, if the validation succeeded, the form data is used to create the new piece of information. In addition to the form data, we manually add the id of the person to whom the information belongs to. Lastly, we could return some data that we could access in the JavaScript callback function after successfully submitting the dialog. As we will simply be reloading the page, no such data is returned. An alternative to reloading to the page would be dynamically inserting the new piece of information in the list so that we would have to return the rendered list item for the new piece of information. The process for getting and submitting the dialog to edit existing pieces of information is similar to the process for adding new pieces of information. Instead of the id of the person, however, we now pass the id of the edited piece of information and in submitEditDialog() , we update the edited information instead of creating a new one like in submitAddDialog() . After editing a piece of information, we do not reload the page but dynamically update the text of the information in the TypeScript code so that we return the updated rendered information text and id of the edited pieced of information in submitAddDialog() .","title":"Creating and Editing Person Information"},{"location":"tutorial/series/part_5/#rebuild-data-worker","text":"To ensure the integrity of the person data, PersonRebuildDataWorker updates the informationCount counter: files/lib/system/worker/PersonRebuildDataWorker.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 <? php namespace wcf\\system\\worker ; use wcf\\data\\person\\PersonList ; use wcf\\system\\WCF ; /** * Worker implementation for updating people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Worker * * @method PersonList getObjectList() */ class PersonRebuildDataWorker extends AbstractRebuildDataWorker { /** * @inheritDoc */ protected $limit = 500 ; /** * @inheritDoc */ protected $objectListClassName = PersonList :: class ; /** * @inheritDoc */ protected function initObjectList () { parent :: initObjectList (); $this -> objectList -> sqlOrderBy = 'person.personID' ; } /** * @inheritDoc */ public function execute () { parent :: execute (); if ( ! \\count ( $this -> objectList )) { return ; } $sql = \"UPDATE wcf\" . WCF_N . \"_person person SET informationCount = ( SELECT COUNT(*) FROM wcf\" . WCF_N . \"_person_information person_information WHERE person_information.personID = person.personID ) WHERE person.personID = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); WCF :: getDB () -> beginTransaction (); foreach ( $this -> getObjectList () as $person ) { $statement -> execute ([ $person -> personID ]); } WCF :: getDB () -> commitTransaction (); } }","title":"Rebuild Data Worker"},{"location":"tutorial/series/part_5/#username-and-ip-address-event-listeners","text":"As we store the name of the user who create a new piece of information and store their IP address, we have to add event listeners to properly handle the following scenarios: If the user is renamed, the value of username stored with the person information has to be updated, which can be achieved by a simple event listener that only has to specify the name of relevant database table if AbstractUserActionRenameListener is extended: files/lib/system/event/listener/PersonUserActionRenameListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; /** * Updates person information during user renaming. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserActionRenameListener extends AbstractUserActionRenameListener { /** * @inheritDoc */ protected $databaseTables = [ 'wcf{WCF_N}_person_information' , ]; } If users are merged, all pieces of information need to be assigned to the target user of the merging. Again, we only have to specify the name of relevant database table if AbstractUserMergeListener is extended: files/lib/system/event/listener/PersonUserMergeListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; /** * Updates person information during user merging. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserMergeListener extends AbstractUserMergeListener { /** * @inheritDoc */ protected $databaseTables = [ 'wcf{WCF_N}_person_information' , ]; } If the option to prune stored ip addresses after a certain period of time is enabled, we also have to prune them in the person information database table. Here we also only have to specify the name of the relevant database table and provide the mapping from the ipAddress column to the time column: files/lib/system/event/listener/PersonPruneIpAddressesCronjobListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\cronjob\\PruneIpAddressesCronjob ; /** * Prunes old ip addresses. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonPruneIpAddressesCronjobListener extends AbstractEventListener { protected function onExecute ( PruneIpAddressesCronjob $cronjob ) : void { $cronjob -> columns [ 'wcf' . WCF_N . '_person_information' ][ 'ipAddress' ] = 'time' ; } } The ip addresses in the person information database table also have to be considered for the user data export which can also be done with minimal effort by providing the name of the relevant database table: files/lib/system/event/listener/PersonUserExportGdprListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\action\\UserExportGdprAction ; /** * Adds the ip addresses stored with the person information during user data export. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserExportGdprListener extends AbstractEventListener { protected function onExport ( UserExportGdprAction $action ) : void { $action -> ipAddresses [ 'com.woltlab.wcf.people' ] = [ 'wcf' . WCF_N . '_person_information' ]; } } Lastly, we present the updated eventListener.xml file with new entries for all of these event listeners: eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd\" > <import> <eventlistener name= \"rename@wcf\\data\\user\\UserAction\" > <eventclassname> wcf\\data\\user\\UserAction </eventclassname> <eventname> rename </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserActionRenameListener </listenerclassname> <environment> all </environment> </eventlistener> <eventlistener name= \"save@wcf\\acp\\form\\UserMergeForm\" > <eventclassname> wcf\\acp\\form\\UserMergeForm </eventclassname> <eventname> save </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserMergeListener </listenerclassname> <environment> admin </environment> </eventlistener> <eventlistener name= \"execute@wcf\\system\\cronjob\\PruneIpAddressesCronjob\" > <eventclassname> wcf\\system\\cronjob\\PruneIpAddressesCronjob </eventclassname> <eventname> execute </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonPruneIpAddressesCronjobListener </listenerclassname> <environment> all </environment> </eventlistener> <eventlistener name= \"export@wcf\\acp\\action\\UserExportGdprAction\" > <eventclassname> wcf\\acp\\action\\UserExportGdprAction </eventclassname> <eventname> export </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserExportGdprListener </listenerclassname> <environment> admin </environment> </eventlistener> </import> </data>","title":"Username and IP Address Event Listeners"},{"location":"tutorial/series/part_6/","text":"Part 6: Activity Points and Activity Events # In this part of our tutorial series, we use the person information added in the previous part to award activity points to users adding new pieces of information and to also create activity events for these pieces of information. Package Functionality # In addition to the existing functions from part 5 , the package will provide the following functionality after this part of the tutorial: Users are awarded activity points for adding new pieces of information for people. If users add new pieces of information for people, activity events are added which are then shown in the list of recent activities. Used Components # In addition to the components used in previous parts, we will use the user activity points API and the user activity events API. Package Structure # The package will have the following file structure excluding unchanged files from previous parts: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u2514\u2500\u2500 information \u2502 \u2502 \u251c\u2500\u2500 PersonInformation.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonInformationAction.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 user \u2502 \u2502 \u2514\u2500\u2500 activity \u2502 \u2502 \u2514\u2500\u2500 event \u2502 \u2502 \u2514\u2500\u2500 PersonInformationUserActivityEvent.class.php \u2502 \u2514\u2500\u2500 worker \u2502 \u251c\u2500\u2500 PersonInformationRebuildDataWorker.class.php \u2502 \u2514\u2500\u2500 PersonRebuildDataWorker.class.php \u251c\u2500\u2500 eventListener.xml \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u2514\u2500\u2500 objectType.xml For all changes, please refer to the source code on GitHub . User Activity Points # The first step to support activity points is to register an object type for the com.woltlab.wcf.user.activityPointEvent object type definition for created person information and specify the default number of points awarded per piece of information: objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.user.activityPointEvent </definitionname> <points> 2 </points> </type> Additionally, the phrase wcf.user.activityPoint.objectType.com.woltlab.wcf.people.information (in general: wcf.user.activityPoint.objectType.{objectType} ) has to be added. The activity points are awarded when new pieces are created via PersonInformation::create() using UserActivityPointHandler::fireEvent() and removed in PersonInformation::create() via UserActivityPointHandler::removeEvents() if pieces of information are deleted. Lastly, we have to add two components for updating data: First, we register a new rebuild data worker objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.rebuildData </definitionname> <classname> wcf\\system\\worker\\PersonInformationRebuildDataWorker </classname> </type> files/lib/system/worker/PersonInformationRebuildDataWorker.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 <? php namespace wcf\\system\\worker ; use wcf\\data\\person\\information\\PersonInformationList ; use wcf\\system\\user\\activity\\point\\UserActivityPointHandler ; /** * Worker implementation for updating person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Worker * * @method PersonInformationList getObjectList() */ class PersonInformationRebuildDataWorker extends AbstractRebuildDataWorker { /** * @inheritDoc */ protected $objectListClassName = PersonInformationList :: class ; /** * @inheritDoc */ protected $limit = 500 ; /** * @inheritDoc */ protected function initObjectList () { parent :: initObjectList (); $this -> objectList -> sqlOrderBy = 'person_information.personID' ; } /** * @inheritDoc */ public function execute () { parent :: execute (); if ( ! $this -> loopCount ) { UserActivityPointHandler :: getInstance () -> reset ( 'com.woltlab.wcf.people.information' ); } if ( ! \\count ( $this -> objectList )) { return ; } $itemsToUser = []; foreach ( $this -> getObjectList () as $personInformation ) { if ( $personInformation -> userID ) { if ( ! isset ( $itemsToUser [ $personInformation -> userID ])) { $itemsToUser [ $personInformation -> userID ] = 0 ; } $itemsToUser [ $personInformation -> userID ] ++ ; } } UserActivityPointHandler :: getInstance () -> fireEvents ( 'com.woltlab.wcf.people.information' , $itemsToUser , false ); } } which updates the number of instances for which any user received person information activity points. (This data worker also requires the phrases wcf.acp.rebuildData.com.woltlab.wcf.people.information and wcf.acp.rebuildData.com.woltlab.wcf.people.information.description ). Second, we add an event listener for UserActivityPointItemsRebuildDataWorker to update the total user activity points awarded for person information: eventListener.xml 1 2 3 4 5 6 <eventlistener name= \"execute@wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker\" > <eventclassname> wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker </eventclassname> <eventname> execute </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserActivityPointItemsRebuildDataWorkerListener </listenerclassname> <environment> admin </environment> </eventlistener> files/lib/system/event/listener/PersonUserActivityPointItemsRebuildDataWorkerListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\database\\util\\PreparedStatementConditionBuilder ; use wcf\\system\\user\\activity\\point\\UserActivityPointHandler ; use wcf\\system\\WCF ; use wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker ; /** * Updates the user activity point items counter for person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserActivityPointItemsRebuildDataWorkerListener extends AbstractEventListener { protected function onExecute ( UserActivityPointItemsRebuildDataWorker $worker ) : void { $objectType = UserActivityPointHandler :: getInstance () -> getObjectTypeByName ( 'com.woltlab.wcf.people.information' ); $conditionBuilder = new PreparedStatementConditionBuilder (); $conditionBuilder -> add ( 'user_activity_point.objectTypeID = ?' , [ $objectType -> objectTypeID ]); $conditionBuilder -> add ( 'user_activity_point.userID IN (?)' , [ $worker -> getObjectList () -> getObjectIDs ()]); $sql = \"UPDATE wcf\" . WCF_N . \"_user_activity_point user_activity_point SET user_activity_point.items = ( SELECT COUNT(*) FROM wcf\" . WCF_N . \"_person_information person_information WHERE person_information.userID = user_activity_point.userID ), user_activity_point.activityPoints = user_activity_point.items * ? { $conditionBuilder } \" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ( \\array_merge ( [ $objectType -> points ], $conditionBuilder -> getParameters () )); } } User Activity Events # To support user activity events, an object type for com.woltlab.wcf.user.recentActivityEvent has to be registered with a class implementing wcf\\system\\user\\activity\\event\\IUserActivityEvent : objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.user.recentActivityEvent </definitionname> <classname> wcf\\system\\user\\activity\\event\\PersonInformationUserActivityEvent </classname> </type> files/lib/system/user/activity/event/PersonInformationUserActivityEvent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <? php namespace wcf\\system\\user\\activity\\event ; use wcf\\data\\person\\information\\PersonInformationList ; use wcf\\system\\SingletonFactory ; use wcf\\system\\WCF ; /** * User activity event implementation for person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\User\\Activity\\Event */ class PersonInformationUserActivityEvent extends SingletonFactory implements IUserActivityEvent { /** * @inheritDoc */ public function prepare ( array $events ) { $objectIDs = \\array_column ( $events , 'objectID' ); $informationList = new PersonInformationList (); $informationList -> setObjectIDs ( $objectIDs ); $informationList -> readObjects (); $information = $informationList -> getObjects (); foreach ( $events as $event ) { if ( isset ( $information [ $event -> objectID ])) { $personInformation = $information [ $event -> objectID ]; $event -> setIsAccessible (); $event -> setTitle ( WCF :: getLanguage () -> getDynamicVariable ( 'wcf.user.profile.recentActivity.personInformation' , [ 'person' => $personInformation -> getPerson (), 'personInformation' => $personInformation , ] ) ); $event -> setDescription ( $personInformation -> getFormattedExcerpt ()); } } } } PersonInformationUserActivityEvent::prepare() must check for all events whether the associated piece of information still exists and if it is the case, mark the event as accessible via the setIsAccessible() method, set the title of the activity event via setTitle() , and set a description of the event via setDescription() for which we use the newly added PersonInformation::getFormattedExcerpt() method. Lastly, we have to add the phrase wcf.user.recentActivity.com.woltlab.wcf.people.information , which is shown in the list of activity events as the type of activity event.","title":"Part 6"},{"location":"tutorial/series/part_6/#part-6-activity-points-and-activity-events","text":"In this part of our tutorial series, we use the person information added in the previous part to award activity points to users adding new pieces of information and to also create activity events for these pieces of information.","title":"Part 6: Activity Points and Activity Events"},{"location":"tutorial/series/part_6/#package-functionality","text":"In addition to the existing functions from part 5 , the package will provide the following functionality after this part of the tutorial: Users are awarded activity points for adding new pieces of information for people. If users add new pieces of information for people, activity events are added which are then shown in the list of recent activities.","title":"Package Functionality"},{"location":"tutorial/series/part_6/#used-components","text":"In addition to the components used in previous parts, we will use the user activity points API and the user activity events API.","title":"Used Components"},{"location":"tutorial/series/part_6/#package-structure","text":"The package will have the following file structure excluding unchanged files from previous parts: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u2514\u2500\u2500 information \u2502 \u2502 \u251c\u2500\u2500 PersonInformation.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonInformationAction.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 user \u2502 \u2502 \u2514\u2500\u2500 activity \u2502 \u2502 \u2514\u2500\u2500 event \u2502 \u2502 \u2514\u2500\u2500 PersonInformationUserActivityEvent.class.php \u2502 \u2514\u2500\u2500 worker \u2502 \u251c\u2500\u2500 PersonInformationRebuildDataWorker.class.php \u2502 \u2514\u2500\u2500 PersonRebuildDataWorker.class.php \u251c\u2500\u2500 eventListener.xml \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u2514\u2500\u2500 objectType.xml For all changes, please refer to the source code on GitHub .","title":"Package Structure"},{"location":"tutorial/series/part_6/#user-activity-points","text":"The first step to support activity points is to register an object type for the com.woltlab.wcf.user.activityPointEvent object type definition for created person information and specify the default number of points awarded per piece of information: objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.user.activityPointEvent </definitionname> <points> 2 </points> </type> Additionally, the phrase wcf.user.activityPoint.objectType.com.woltlab.wcf.people.information (in general: wcf.user.activityPoint.objectType.{objectType} ) has to be added. The activity points are awarded when new pieces are created via PersonInformation::create() using UserActivityPointHandler::fireEvent() and removed in PersonInformation::create() via UserActivityPointHandler::removeEvents() if pieces of information are deleted. Lastly, we have to add two components for updating data: First, we register a new rebuild data worker objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.rebuildData </definitionname> <classname> wcf\\system\\worker\\PersonInformationRebuildDataWorker </classname> </type> files/lib/system/worker/PersonInformationRebuildDataWorker.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 <? php namespace wcf\\system\\worker ; use wcf\\data\\person\\information\\PersonInformationList ; use wcf\\system\\user\\activity\\point\\UserActivityPointHandler ; /** * Worker implementation for updating person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Worker * * @method PersonInformationList getObjectList() */ class PersonInformationRebuildDataWorker extends AbstractRebuildDataWorker { /** * @inheritDoc */ protected $objectListClassName = PersonInformationList :: class ; /** * @inheritDoc */ protected $limit = 500 ; /** * @inheritDoc */ protected function initObjectList () { parent :: initObjectList (); $this -> objectList -> sqlOrderBy = 'person_information.personID' ; } /** * @inheritDoc */ public function execute () { parent :: execute (); if ( ! $this -> loopCount ) { UserActivityPointHandler :: getInstance () -> reset ( 'com.woltlab.wcf.people.information' ); } if ( ! \\count ( $this -> objectList )) { return ; } $itemsToUser = []; foreach ( $this -> getObjectList () as $personInformation ) { if ( $personInformation -> userID ) { if ( ! isset ( $itemsToUser [ $personInformation -> userID ])) { $itemsToUser [ $personInformation -> userID ] = 0 ; } $itemsToUser [ $personInformation -> userID ] ++ ; } } UserActivityPointHandler :: getInstance () -> fireEvents ( 'com.woltlab.wcf.people.information' , $itemsToUser , false ); } } which updates the number of instances for which any user received person information activity points. (This data worker also requires the phrases wcf.acp.rebuildData.com.woltlab.wcf.people.information and wcf.acp.rebuildData.com.woltlab.wcf.people.information.description ). Second, we add an event listener for UserActivityPointItemsRebuildDataWorker to update the total user activity points awarded for person information: eventListener.xml 1 2 3 4 5 6 <eventlistener name= \"execute@wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker\" > <eventclassname> wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker </eventclassname> <eventname> execute </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserActivityPointItemsRebuildDataWorkerListener </listenerclassname> <environment> admin </environment> </eventlistener> files/lib/system/event/listener/PersonUserActivityPointItemsRebuildDataWorkerListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\database\\util\\PreparedStatementConditionBuilder ; use wcf\\system\\user\\activity\\point\\UserActivityPointHandler ; use wcf\\system\\WCF ; use wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker ; /** * Updates the user activity point items counter for person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserActivityPointItemsRebuildDataWorkerListener extends AbstractEventListener { protected function onExecute ( UserActivityPointItemsRebuildDataWorker $worker ) : void { $objectType = UserActivityPointHandler :: getInstance () -> getObjectTypeByName ( 'com.woltlab.wcf.people.information' ); $conditionBuilder = new PreparedStatementConditionBuilder (); $conditionBuilder -> add ( 'user_activity_point.objectTypeID = ?' , [ $objectType -> objectTypeID ]); $conditionBuilder -> add ( 'user_activity_point.userID IN (?)' , [ $worker -> getObjectList () -> getObjectIDs ()]); $sql = \"UPDATE wcf\" . WCF_N . \"_user_activity_point user_activity_point SET user_activity_point.items = ( SELECT COUNT(*) FROM wcf\" . WCF_N . \"_person_information person_information WHERE person_information.userID = user_activity_point.userID ), user_activity_point.activityPoints = user_activity_point.items * ? { $conditionBuilder } \" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ( \\array_merge ( [ $objectType -> points ], $conditionBuilder -> getParameters () )); } }","title":"User Activity Points"},{"location":"tutorial/series/part_6/#user-activity-events","text":"To support user activity events, an object type for com.woltlab.wcf.user.recentActivityEvent has to be registered with a class implementing wcf\\system\\user\\activity\\event\\IUserActivityEvent : objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.user.recentActivityEvent </definitionname> <classname> wcf\\system\\user\\activity\\event\\PersonInformationUserActivityEvent </classname> </type> files/lib/system/user/activity/event/PersonInformationUserActivityEvent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <? php namespace wcf\\system\\user\\activity\\event ; use wcf\\data\\person\\information\\PersonInformationList ; use wcf\\system\\SingletonFactory ; use wcf\\system\\WCF ; /** * User activity event implementation for person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\User\\Activity\\Event */ class PersonInformationUserActivityEvent extends SingletonFactory implements IUserActivityEvent { /** * @inheritDoc */ public function prepare ( array $events ) { $objectIDs = \\array_column ( $events , 'objectID' ); $informationList = new PersonInformationList (); $informationList -> setObjectIDs ( $objectIDs ); $informationList -> readObjects (); $information = $informationList -> getObjects (); foreach ( $events as $event ) { if ( isset ( $information [ $event -> objectID ])) { $personInformation = $information [ $event -> objectID ]; $event -> setIsAccessible (); $event -> setTitle ( WCF :: getLanguage () -> getDynamicVariable ( 'wcf.user.profile.recentActivity.personInformation' , [ 'person' => $personInformation -> getPerson (), 'personInformation' => $personInformation , ] ) ); $event -> setDescription ( $personInformation -> getFormattedExcerpt ()); } } } } PersonInformationUserActivityEvent::prepare() must check for all events whether the associated piece of information still exists and if it is the case, mark the event as accessible via the setIsAccessible() method, set the title of the activity event via setTitle() , and set a description of the event via setDescription() for which we use the newly added PersonInformation::getFormattedExcerpt() method. Lastly, we have to add the phrase wcf.user.recentActivity.com.woltlab.wcf.people.information , which is shown in the list of activity events as the type of activity event.","title":"User Activity Events"},{"location":"view/css/","text":"CSS # SCSS and CSS # SCSS is a scripting language that features a syntax similar to CSS and compiles into native CSS at runtime. It provides many great additions to CSS such as declaration nesting and variables, it is recommended to read the official guide to learn more. You can create .scss files containing only pure CSS code and it will work just fine, you are at no point required to write actual SCSS code. File Location # Please place your style files in a subdirectory of the style/ directory of the target application or the Core's style directory, for example style/layout/pageHeader.scss . Variables # You can access variables with $myVariable , variable interpolation (variables inside strings) is accomplished with #{$myVariable} . Linking images # Images used within a style must be located in the style's image folder. To get the folder name within the CSS the SCSS variable #{$style_image_path} can be used. The value will contain a trailing slash. Media Breakpoints # Media breakpoints instruct the browser to apply different CSS depending on the viewport dimensions, e.g. serving a desktop PC a different view than when viewed on a smartphone. 1 2 3 4 5 6 7 8 9 10 11 12 13 /* red background color for desktop pc */ @include screen-lg { body { background-color : red ; } } /* green background color on smartphones and tablets */ @include screen-md-down { body { background-color : green ; } } Available Breakpoints # Some very large smartphones, for example the Apple iPhone 7 Plus, do match the media query for Tablets (portrait) when viewed in landscape mode. Name Devices @media equivalent screen-xs Smartphones only (max-width: 544px) screen-sm Tablets (portrait) (min-width: 545px) and (max-width: 768px) screen-sm-down Tablets (portrait) and smartphones (max-width: 768px) screen-sm-up Tablets and desktop PC (min-width: 545px) screen-sm-md Tablets only (min-width: 545px) and (max-width: 1024px) screen-md Tablets (landscape) (min-width: 769px) and (max-width: 1024px) screen-md-down Smartphones and tablets (max-width: 1024px) screen-md-up Tablets (landscape) and desktop PC (min-width: 769px) screen-lg Desktop PC (min-width: 1025px) screen-lg-only Desktop PC (min-width: 1025px) and (max-width: 1280px) screen-lg-down Smartphones, tablets, and desktop PC (max-width: 1280px) screen-xl Desktop PC (min-width: 1281px) Asset Preloading # WoltLab Suite\u2019s SCSS compiler supports adding preloading metadata to the CSS. To communicate the preloading intent to the compiler, the --woltlab-suite-preload CSS variable is set to the result of the preload() function: 1 2 3 4 5 6 7 8 9 10 .fooBar { --woltlab-suite-preload : # { preload ( ' #{ $style_image_path } custom/background.png' , $ as : \"image\" , $ crossorigin : false , $ type : \"image/png\" ) } ; background : url ( ' #{ $style_image_path } custom/background.png' ); } The parameters of the preload() function map directly to the preloading properties that are used within the <link> tag and the link: HTTP response header. The above example will result in a <link> similar to the following being added to the generated HTML: 1 <link rel=\"preload\" href=\"https://example.com/images/style-1/custom/background.png\" as=\"image\" type=\"image/png\"> Use preloading sparingly for the most important resources where you can be certain that the browser will need them. Unused preloaded resources will unnecessarily waste bandwidth.","title":"CSS"},{"location":"view/css/#css","text":"","title":"CSS"},{"location":"view/css/#scss-and-css","text":"SCSS is a scripting language that features a syntax similar to CSS and compiles into native CSS at runtime. It provides many great additions to CSS such as declaration nesting and variables, it is recommended to read the official guide to learn more. You can create .scss files containing only pure CSS code and it will work just fine, you are at no point required to write actual SCSS code.","title":"SCSS and CSS"},{"location":"view/css/#file-location","text":"Please place your style files in a subdirectory of the style/ directory of the target application or the Core's style directory, for example style/layout/pageHeader.scss .","title":"File Location"},{"location":"view/css/#variables","text":"You can access variables with $myVariable , variable interpolation (variables inside strings) is accomplished with #{$myVariable} .","title":"Variables"},{"location":"view/css/#linking-images","text":"Images used within a style must be located in the style's image folder. To get the folder name within the CSS the SCSS variable #{$style_image_path} can be used. The value will contain a trailing slash.","title":"Linking images"},{"location":"view/css/#media-breakpoints","text":"Media breakpoints instruct the browser to apply different CSS depending on the viewport dimensions, e.g. serving a desktop PC a different view than when viewed on a smartphone. 1 2 3 4 5 6 7 8 9 10 11 12 13 /* red background color for desktop pc */ @include screen-lg { body { background-color : red ; } } /* green background color on smartphones and tablets */ @include screen-md-down { body { background-color : green ; } }","title":"Media Breakpoints"},{"location":"view/css/#available-breakpoints","text":"Some very large smartphones, for example the Apple iPhone 7 Plus, do match the media query for Tablets (portrait) when viewed in landscape mode. Name Devices @media equivalent screen-xs Smartphones only (max-width: 544px) screen-sm Tablets (portrait) (min-width: 545px) and (max-width: 768px) screen-sm-down Tablets (portrait) and smartphones (max-width: 768px) screen-sm-up Tablets and desktop PC (min-width: 545px) screen-sm-md Tablets only (min-width: 545px) and (max-width: 1024px) screen-md Tablets (landscape) (min-width: 769px) and (max-width: 1024px) screen-md-down Smartphones and tablets (max-width: 1024px) screen-md-up Tablets (landscape) and desktop PC (min-width: 769px) screen-lg Desktop PC (min-width: 1025px) screen-lg-only Desktop PC (min-width: 1025px) and (max-width: 1280px) screen-lg-down Smartphones, tablets, and desktop PC (max-width: 1280px) screen-xl Desktop PC (min-width: 1281px)","title":"Available Breakpoints"},{"location":"view/css/#asset-preloading","text":"WoltLab Suite\u2019s SCSS compiler supports adding preloading metadata to the CSS. To communicate the preloading intent to the compiler, the --woltlab-suite-preload CSS variable is set to the result of the preload() function: 1 2 3 4 5 6 7 8 9 10 .fooBar { --woltlab-suite-preload : # { preload ( ' #{ $style_image_path } custom/background.png' , $ as : \"image\" , $ crossorigin : false , $ type : \"image/png\" ) } ; background : url ( ' #{ $style_image_path } custom/background.png' ); } The parameters of the preload() function map directly to the preloading properties that are used within the <link> tag and the link: HTTP response header. The above example will result in a <link> similar to the following being added to the generated HTML: 1 <link rel=\"preload\" href=\"https://example.com/images/style-1/custom/background.png\" as=\"image\" type=\"image/png\"> Use preloading sparingly for the most important resources where you can be certain that the browser will need them. Unused preloaded resources will unnecessarily waste bandwidth.","title":"Asset Preloading"},{"location":"view/languages-naming-conventions/","text":"Language Naming Conventions # This page contains general rules for naming language items and for their values. API-specific rules are listed on the relevant API page: Comments Forms # Fields # If you have an application foo and a database object foo\\data\\bar\\Bar with a property baz that can be set via a form field, the name of the corresponding language item has to be foo.bar.baz . If you want to add an additional description below the field, use the language item foo.bar.baz.description . Error Texts # If an error of type {error type} for the previously mentioned form field occurs during validation, you have to use the language item foo.bar.baz.error.{error type} for the language item describing the error. Exception to this rule: There are several general error messages like wcf.global.form.error.empty that have to be used for general errors like an empty field that may not be empty to avoid duplication of the same error message text over and over again in different language items. Naming Conventions # If the entered text does not conform to some special rules, i.e. if the text is invalid, use invalid as error type. If the entered text is required to be unique but is already used for another object, use notUnique as error type. Confirmation messages # If the language item for an action is foo.bar.action , the language item for the confirmation message has to be foo.bar.action.confirmMessage instead of foo.bar.action.sure which is still used by some older language items. Type-Specific Deletion Confirmation Message # German # 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} {element type} wirklich l\u00f6schen? Example: 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} das Icon wirklich l\u00f6schen? English # 1 Do you really want delete the {element type}? Example: 1 Do you really want delete the icon? Object-Specific Deletion Confirmation Message # German # 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} {element type} <span class=\"confirmationObject\">{object name}</span> wirklich l\u00f6schen? Example: 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} den Artikel <span class=\"confirmationObject\">{$article->getTitle()}</span> wirklich l\u00f6schen? English # 1 Do you really want to delete the {element type} <span class=\"confirmationObject\">{object name}</span>? Example: 1 Do you really want to delete the article <span class=\"confirmationObject\">{$article->getTitle()}</span>? User Group Options # Comments # German # group type action example permission name language item user adding user.foo.canAddComment Kann Kommentare erstellen user deleting user.foo.canDeleteComment Kann eigene Kommentare l\u00f6schen user editing user.foo.canEditComment Kann eigene Kommentare bearbeiten moderator deleting mod.foo.canDeleteComment Kann Kommentare l\u00f6schen moderator editing mod.foo.canEditComment Kann Kommentare bearbeiten moderator moderating mod.foo.canModerateComment Kann Kommentare moderieren English # group type action example permission name language item user adding user.foo.canAddComment Can create comments user deleting user.foo.canDeleteComment Can delete their comments user editing user.foo.canEditComment Can edit their comments moderator deleting mod.foo.canDeleteComment Can delete comments moderator editing mod.foo.canEditComment Can edit comments moderator moderating mod.foo.canModerateComment Can moderate comments","title":"Language Naming Conventions"},{"location":"view/languages-naming-conventions/#language-naming-conventions","text":"This page contains general rules for naming language items and for their values. API-specific rules are listed on the relevant API page: Comments","title":"Language Naming Conventions"},{"location":"view/languages-naming-conventions/#forms","text":"","title":"Forms"},{"location":"view/languages-naming-conventions/#fields","text":"If you have an application foo and a database object foo\\data\\bar\\Bar with a property baz that can be set via a form field, the name of the corresponding language item has to be foo.bar.baz . If you want to add an additional description below the field, use the language item foo.bar.baz.description .","title":"Fields"},{"location":"view/languages-naming-conventions/#error-texts","text":"If an error of type {error type} for the previously mentioned form field occurs during validation, you have to use the language item foo.bar.baz.error.{error type} for the language item describing the error. Exception to this rule: There are several general error messages like wcf.global.form.error.empty that have to be used for general errors like an empty field that may not be empty to avoid duplication of the same error message text over and over again in different language items.","title":"Error Texts"},{"location":"view/languages-naming-conventions/#naming-conventions","text":"If the entered text does not conform to some special rules, i.e. if the text is invalid, use invalid as error type. If the entered text is required to be unique but is already used for another object, use notUnique as error type.","title":"Naming Conventions"},{"location":"view/languages-naming-conventions/#confirmation-messages","text":"If the language item for an action is foo.bar.action , the language item for the confirmation message has to be foo.bar.action.confirmMessage instead of foo.bar.action.sure which is still used by some older language items.","title":"Confirmation messages"},{"location":"view/languages-naming-conventions/#type-specific-deletion-confirmation-message","text":"","title":"Type-Specific Deletion Confirmation Message"},{"location":"view/languages-naming-conventions/#german","text":"1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} {element type} wirklich l\u00f6schen? Example: 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} das Icon wirklich l\u00f6schen?","title":"German"},{"location":"view/languages-naming-conventions/#english","text":"1 Do you really want delete the {element type}? Example: 1 Do you really want delete the icon?","title":"English"},{"location":"view/languages-naming-conventions/#object-specific-deletion-confirmation-message","text":"","title":"Object-Specific Deletion Confirmation Message"},{"location":"view/languages-naming-conventions/#german_1","text":"1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} {element type} <span class=\"confirmationObject\">{object name}</span> wirklich l\u00f6schen? Example: 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} den Artikel <span class=\"confirmationObject\">{$article->getTitle()}</span> wirklich l\u00f6schen?","title":"German"},{"location":"view/languages-naming-conventions/#english_1","text":"1 Do you really want to delete the {element type} <span class=\"confirmationObject\">{object name}</span>? Example: 1 Do you really want to delete the article <span class=\"confirmationObject\">{$article->getTitle()}</span>?","title":"English"},{"location":"view/languages-naming-conventions/#user-group-options","text":"","title":"User Group Options"},{"location":"view/languages-naming-conventions/#comments","text":"","title":"Comments"},{"location":"view/languages-naming-conventions/#german_2","text":"group type action example permission name language item user adding user.foo.canAddComment Kann Kommentare erstellen user deleting user.foo.canDeleteComment Kann eigene Kommentare l\u00f6schen user editing user.foo.canEditComment Kann eigene Kommentare bearbeiten moderator deleting mod.foo.canDeleteComment Kann Kommentare l\u00f6schen moderator editing mod.foo.canEditComment Kann Kommentare bearbeiten moderator moderating mod.foo.canModerateComment Kann Kommentare moderieren","title":"German"},{"location":"view/languages-naming-conventions/#english_2","text":"group type action example permission name language item user adding user.foo.canAddComment Can create comments user deleting user.foo.canDeleteComment Can delete their comments user editing user.foo.canEditComment Can edit their comments moderator deleting mod.foo.canDeleteComment Can delete comments moderator editing mod.foo.canEditComment Can edit comments moderator moderating mod.foo.canModerateComment Can moderate comments","title":"English"},{"location":"view/languages/","text":"Languages # WoltLab Suite offers full i18n support with its integrated language system, including but not limited to dynamic phrases using template scripting and the built-in support for right-to-left languages. Phrases are deployed using the language package installation plugin, please also read the naming conventions for language items . Special Phrases # wcf.date.dateFormat # Many characters in the format have a special meaning and will be replaced with date fragments. If you want to include a literal character, you'll have to use the backslash \\ as an escape sequence to indicate that the character should be output as-is rather than being replaced. For example, Y-m-d will be output as 2018-03-30 , but \\Y-m-d will result in Y-03-30 . Defaults to M jS Y . The date format without time using PHP's format characters for the date() function. This value is also used inside the JavaScript implementation, where the characters are mapped to an equivalent representation. wcf.date.timeFormat # Defaults to g:i a . The date format that is used to represent a time, but not a date. Please see the explanation on wcf.date.dateFormat to learn more about the format characters. wcf.date.firstDayOfTheWeek # Defaults to 0 . Sets the first day of the week: * 0 - Sunday * 1 - Monday wcf.global.pageDirection - RTL support # Defaults to ltr . Changing this value to rtl will reverse the page direction and enable the right-to-left support for phrases. Additionally, a special version of the stylesheet is loaded that contains all necessary adjustments for the reverse direction.","title":"Languages"},{"location":"view/languages/#languages","text":"WoltLab Suite offers full i18n support with its integrated language system, including but not limited to dynamic phrases using template scripting and the built-in support for right-to-left languages. Phrases are deployed using the language package installation plugin, please also read the naming conventions for language items .","title":"Languages"},{"location":"view/languages/#special-phrases","text":"","title":"Special Phrases"},{"location":"view/languages/#wcfdatedateformat","text":"Many characters in the format have a special meaning and will be replaced with date fragments. If you want to include a literal character, you'll have to use the backslash \\ as an escape sequence to indicate that the character should be output as-is rather than being replaced. For example, Y-m-d will be output as 2018-03-30 , but \\Y-m-d will result in Y-03-30 . Defaults to M jS Y . The date format without time using PHP's format characters for the date() function. This value is also used inside the JavaScript implementation, where the characters are mapped to an equivalent representation.","title":"wcf.date.dateFormat"},{"location":"view/languages/#wcfdatetimeformat","text":"Defaults to g:i a . The date format that is used to represent a time, but not a date. Please see the explanation on wcf.date.dateFormat to learn more about the format characters.","title":"wcf.date.timeFormat"},{"location":"view/languages/#wcfdatefirstdayoftheweek","text":"Defaults to 0 . Sets the first day of the week: * 0 - Sunday * 1 - Monday","title":"wcf.date.firstDayOfTheWeek"},{"location":"view/languages/#wcfglobalpagedirection-rtl-support","text":"Defaults to ltr . Changing this value to rtl will reverse the page direction and enable the right-to-left support for phrases. Additionally, a special version of the stylesheet is loaded that contains all necessary adjustments for the reverse direction.","title":"wcf.global.pageDirection - RTL support"},{"location":"view/template-plugins/","text":"Template Plugins # 5.3+ anchor # The anchor template plugin creates a HTML elements. The easiest way to use the template plugin is to pass it an instance of ITitledLinkObject : 1 { anchor object = $object } generates the same output as 1 <a href=\" { $object -> getLink () } \"> { $object -> getTitle () } </a> Instead of an object parameter, a link and content parameter can be used: 1 { anchor link = $linkObject content = $content } where $linkObject implements ILinkableObject and $content is either an object implementing ITitledObject or having a __toString() method or $content is a string or a number. The last special attribute is append whose contents are appended to the href attribute of the generated anchor element. All of the other attributes matching ~^[a-z]+([A-z]+)+$~ , expect for href which is disallowed, are added as attributes to the anchor element. If an object attribute is present, the object also implements IPopoverObject and if the return value of IPopoverObject::getPopoverLinkClass() is included in the class attribute of the anchor tag, data-object-id is automatically added. This functionality makes it easy to generate links with popover support. Instead of 1 <a href=\" { $entry -> getLink () } \" class=\"blogEntryLink\" data-object-id=\" { @ $entry -> entryID } \"> { $entry -> subject } </a> using 1 { anchor object = $entry class = 'blogEntryLink' } is sufficient if Entry::getPopoverLinkClass() returns blogEntryLink . 5.3+ anchorAttributes # anchorAttributes compliments the StringUtil::getAnchorTagAttributes(string, bool): string method. It allows to easily generate the necessary attributes for an anchor tag based off the destination URL. 1 <a href=\"https://www.example.com\" { anchorAttributes url = 'https://www.example.com' appendHref = false appendClassname = true isUgc = true } > Attribute Description url destination URL appendHref whether the href attribute should be generated; true by default isUgc whether the rel=\"ugc\" attribute should be generated; false by default appendClassname whether the class=\"externalURL\" attribute should be generated; true by default append # If a string should be appended to the value of a variable, append can be used: 1 2 3 4 5 6 7 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } { append var = templateVariable value = '2' } { $templateVariable } { * now prints 'newValue2 * } If the variables does not exist yet, append creates a new one with the given value. If append is used on an array as the variable, the value is appended to all elements of the array. assign # New template variables can be declared and new values can be assigned to existing template variables using assign : 1 2 3 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } capture # In some situations, assign is not sufficient to assign values to variables in templates if the value is complex. Instead, capture can be used: 1 2 3 4 5 6 7 { capture var = templateVariable } { if $foo } <p> { $bar } </p> { else } <small> { $baz } </small> { /if } { /capture } concat # concat is a modifier used to concatenate multiple strings: 1 2 3 4 5 { assign var = foo value = 'foo' } { assign var = templateVariable value = 'bar' | concat : $foo } { $templateVariable } { * prints 'foobar * } counter # counter can be used to generate and optionally print a counter: 1 2 3 4 5 6 7 { counter name = fooCounter print = true } { * prints '1' * } { counter name = fooCounter print = true } { * prints '2' now * } { counter name = fooCounter } { * prints nothing, but counter value is '3' now internally * } { counter name = fooCounter print = true } { * prints '4' * } Counter supports the following attributes: Attribute Description assign optional name of the template variable the current counter value is assigned to direction counting direction, either up or down ; up by default name name of the counter, relevant if multiple counters are used simultaneously print if true , the current counter value is printed; false by default skip positive counting increment; 1 by default start start counter value; 1 by default 5.4+ csrfToken # {csrfToken} prints out the session's CSRF token (\u201cSecurity Token\u201d). 1 2 3 4 5 <form action=\" { link controller = \"Foo\" }{ /link } \" method=\"post\"> { * snip * } { csrfToken } </form> The {csrfToken} template plugin supports a type parameter. Specifying this parameter might be required in rare situations. Please check the implementation for details. currency # currency is a modifier used to format currency values with two decimals using language dependent thousands separators and decimal point: 1 2 3 { assign var = currencyValue value = 12.345 } { $currencyValue | currency } { * prints '12.34' * } cycle # cycle can be used to cycle between different values: 1 2 3 4 5 6 7 { cycle name = fooCycle values = 'bar,baz' } { * prints 'bar' * } { cycle name = fooCycle } { * prints 'baz' * } { cycle name = fooCycle advance = false } { * prints 'baz' again * } { cycle name = fooCycle } { * prints 'bar' * } The values attribute only has to be present for the first call. If cycle is used in a loop, the presence of the same values in consecutive calls has no effect. Only once the values change, the cycle is reset. Attribute Description advance if true , the current cycle value is advanced to the next value; true by default assign optional name of the template variable the current cycle value is assigned to; if used, print is set to false delimiter delimiter between the different cycle values; , by default name name of the cycle, relevant if multiple cycles are used simultaneously print if true , the current cycle value is printed, false by default reset if true , the current cycle value is set to the first value, false by default values string containing the different cycles values, also see delimiter date # date generated a formatted date using wcf\\util\\DateUtil::format() with DateUtil::DATE_FORMAT internally. 1 { $timestamp | date } 3.1+ dateInterval # dateInterval calculates the difference between two unix timestamps and generated a textual date interval. 1 { dateInterval start = $startTimestamp end = $endTimestamp full = true format = 'sentence' } Attribute Description end end of the time interval; current timestamp by default (though either start or end has to be set) format output format, either default , sentence , or plain ; defaults to default , see wcf\\util\\DateUtil::FORMAT_* constants full if true , full difference in minutes is shown; if false , only the longest time interval is shown; false by default start start of the time interval; current timestamp by default (though either start or end has to be set) encodeJS # encodeJS encodes a string to be used as a single-quoted string in JavaScript by replacing \\\\ with \\\\\\\\ , ' with \\' , linebreaks with \\n , and / with \\/ . 1 2 3 <script> var foo = ' { @ $foo | encodeJS } '; </script> escapeCDATA # escapeCDATA encodes a string to be used in a CDATA element by replacing ]]> with ]]]]><![CDATA[> . 1 <![CDATA[ { @ $foo | encodeCDATA } ]]> event # event provides extension points in templates that template listeners can use. 1 { event name = 'foo' } fetch # fetch fetches the contents of a file using file_get_contents . 1 2 3 { fetch file = 'foo.html' } { * prints the contents of `foo.html` * } { fetch file = 'bar.html' assign = bar } { * assigns the contents of `foo.html` to `$bar`; does not print the contents * } filesizeBinary # filesizeBinary formats the filesize using binary filesize (in bytes). 1 { $filesize | filesizeBinary } filesize # filesize formats the filesize using filesize (in bytes). 1 { $filesize | filesize } hascontent # In many cases, conditional statements can be used to determine if a certain section of a template is shown: 1 2 3 { if $foo === 'bar' } only shown if $foo is bar { /if } In some situations, however, such conditional statements are not sufficient. One prominent example is a template event: 1 2 3 4 5 6 7 8 9 { if $foo === 'bar' } <ul> { if $foo === 'bar' } <li>Bar</li> { /if } { event name = 'listItems' } </li> { /if } In this example, if $foo !== 'bar' , the list will not be shown, regardless of the additional template code provided by template listeners. In such a situation, hascontent has to be used: 1 2 3 4 5 6 7 8 9 10 11 { hascontent } <ul> { content } { if $foo === 'bar' } <li>Bar</li> { /if } { event name = 'listItems' } { /content } </ul> { /hascontent } If the part of the template wrapped in the content tags has any (trimmed) content, the part of the template wrapped by hascontent tags is shown (including the part wrapped by the content tags), otherwise nothing is shown. Thus, this construct avoids an empty list compared to the if solution above. Like foreach , hascontent also supports an else part: 1 2 3 4 5 6 7 8 9 { hascontent } <ul> { content } { * \u2026 * } { /content } </ul> { hascontentelse } no list { /hascontent } htmlCheckboxes # htmlCheckboxes generates a list of HTML checkboxes. 1 2 3 { htmlCheckboxes name = foo options = $fooOptions selected = $currentFoo } { htmlCheckboxes name = bar output = $barLabels values = $barValues selected = $currentBar } Attribute Description 5.2+ disabled if true , all checkboxes are disabled disableEncoding if true , the values are not passed through wcf\\util\\StringUtil::encodeHTML() ; false by default name name attribute of the input checkbox element output array used as keys and values for options if present; not present by default options array selectable options with the key used as value attribute and the value as the checkbox label selected current selected value(s) separator separator between the different checkboxes in the generated output; empty string by default values array with values used in combination with output , where output is only used as keys for options htmlOptions # htmlOptions generates an select HTML element. 1 2 3 4 5 6 { htmlOptions name = 'foo' options = $options selected = $selected } <select name=\"bar\"> <option value=\"\" { if ! $selected } selected { /if } > { lang } foo.bar.default { /lang } </option> { htmlOptions options = $options selected = $selected } { * no `name` attribute * } </select> Attribute Description disableEncoding if true , the values are not passed through wcf\\util\\StringUtil::encodeHTML() ; false by default object optional instance of wcf\\data\\DatabaseObjectList that provides the selectable options (overwrites options attribute internally) name name attribute of the select element; if not present, only the contents of the select element are printed output array used as keys and values for options if present; not present by default values array with values used in combination with output , where output is only used as keys for options options array selectable options with the key used as value attribute and the value as the option label; if a value is an array, an optgroup is generated with the array key as the optgroup label selected current selected value(s) All additional attributes are added as attributes of the select HTML element. implode # implodes transforms an array into a string and prints it. 1 { implode from = $array key = key item = item glue = \";\" }{ $key } : { $value }{ /implode } Attribute Description from array with the imploded values glue separator between the different array values; ', ' by default item template variable name where the current array value is stored during the iteration key optional template variable name where the current array key is stored during the iteration 5.2+ ipSearch # ipSearch generates a link to search for an IP address. 1 { \"127.0.0.1\" | ipSearch } js # js generates script tags based on whether ENABLE_DEBUG_MODE and VISITOR_USE_TINY_BUILD are enabled. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 { js application = 'wbb' file = 'WBB' } { * generates 'http://example.com/js/WBB.js' * } { js application = 'wcf' file = 'WCF.User' bundle = 'WCF.Combined' } { * generates 'http://example.com/wcf/js/WCF.User.js' if ENABLE_DEBUG_MODE=1 * } { * generates 'http://example.com/wcf/js/WCF.Combined.min.js' if ENABLE_DEBUG_MODE=0 * } { js application = 'wcf' lib = 'jquery' } { * generates 'http://example.com/wcf/js/3rdParty/jquery.js' * } { js application = 'wcf' lib = 'jquery-ui' file = 'awesomeWidget' } { * generates 'http://example.com/wcf/js/3rdParty/jquery-ui/awesomeWidget.js' * } { js application = 'wcf' file = 'WCF.User' bundle = 'WCF.Combined' hasTiny = true } { * generates 'http://example.com/wcf/js/WCF.User.js' if ENABLE_DEBUG_MODE=1 * } { * generates 'http://example.com/wcf/js/WCF.Combined.min.js' (ENABLE_DEBUG_MODE=0 * } { * generates 'http://example.com/wcf/js/WCF.Combined.tiny.min.js' if ENABLE_DEBUG_MODE=0 and VISITOR_USE_TINY_BUILD=1 * } 5.3+ jslang # jslang works like lang with the difference that the resulting string is automatically passed through encodeJS . 1 2 3 4 5 6 7 require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' , } ); // \u2026 } ); 5.5+ json # json JSON-encodes the given value. 1 2 3 <script> let data = { \"title\" : { @ $foo -> getTitle ()| json } } ; </script> lang # lang replaces a language items with its value. 1 2 3 4 5 6 7 { lang } foo.bar.baz { /lang } { lang __literal = true } foo.bar.baz { /lang } { lang foo = 'baz' } foo.bar.baz { /lang } { lang } foo.bar.baz. { $action }{ /lang } Attribute Description __encode if true , the output will be passed through StringUtil::encodeHTML() __literal if true , template variables will not resolved but printed as they are in the language item; false by default __optional if true and the language item does not exist, an empty string is printed; false by default All additional attributes are available when parsing the language item. language # language replaces a language items with its value. If the template variable __language exists, this language object will be used instead of WCF::getLanguage() . This modifier is useful when assigning the value directly to a variable. Note that template scripting is applied to the output of the variable, which can lead to unwanted side effects. Use phrase instead if you don't want to use template scripting. 1 2 3 { $languageItem | language } { assign var = foo value = $languageItem | language } link # link generates internal links using LinkHandler . 1 <a href=\" { link controller = 'FooList' application = 'bar' } param1=2¶m2=A { /link } \">Foo</a> Attribute Description application abbreviation of the application the controller belongs to; wcf by default controller name of the controller; if not present, the landing page is linked in the frontend and the index page in the ACP encode if true , the generated link is passed through wcf\\util\\StringUtil::encodeHTML() ; true by default isEmail sets encode=false and forces links to link to the frontend Additional attributes are passed to LinkHandler::getLink() . newlineToBreak # newlineToBreak transforms newlines into HTML <br> elements after encoding the content via wcf\\util\\StringUtil::encodeHTML() . 1 { $foo | newlineToBreak } 5.4+ objectAction # objectAction generates action buttons to be used in combination with the WoltLabSuite/Core/Ui/Object/Action API . For detailed information on its usage, we refer to the extensive documentation in the ObjectActionFunctionTemplatePlugin class itself. page # page generates an internal link to a CMS page. 1 2 3 4 5 6 7 { page } com.woltlab.wcf.CookiePolicy { /page } { page pageID = 1 }{ /page } { page language = 'de' } com.woltlab.wcf.CookiePolicy { /page } { page languageID = 2 } com.woltlab.wcf.CookiePolicy { /page } Attribute Description pageID unique id of the page (cannot be used together with a page identifier as value) languageID id of the page language (cannot be used together with language ) language language code of the page language (cannot be used together with languageID ) pages # pages generates a pagination. 1 2 3 { pages controller = 'FooList' link = \"pageNo=%d\" print = true assign = pagesLinks } { * prints pagination * } { @ $pagesLinks } { * prints same pagination again * } Attribute Description assign optional name of the template variable the pagination is assigned to controller controller name of the generated links link additional link parameter where %d will be replaced with the relevant page number pages maximum number of of pages; by default, the template variable $pages is used print if false and assign=true , the pagination is not printed application , id , object , title additional parameters passed to LinkHandler::getLink() to generate page links 5.5+ phrase # phrase replaces a language items with its value. If the template variable __language exists, this language object will be used instead of WCF::getLanguage() . This modifier is useful when assigning the value directly to a variable. phrase should be used instead of language unless you want to explicitly allow template scripting on a variable's output. 1 2 3 { $languageItem | phrase } { assign var = foo value = $languageItem | phrase } plainTime # plainTime formats a timestamp to include year, month, day, hour, and minutes. The exact formatting depends on the current language (via the language items wcf.date.dateTimeFormat , wcf.date.dateFormat , and wcf.date.timeFormat ). 1 { $timestamp | plainTime } 5.3+ plural # plural allows to easily select the correct plural form of a phrase based on a given value . The pluralization logic follows the Unicode Language Plural Rules for cardinal numbers. The # placeholder within the resulting phrase is replaced by the value . It is automatically formatted using StringUtil::formatNumeric . English: Note the use of 1 if the number ( # ) is not used within the phrase and the use of one otherwise. They are equivalent for English, but following this rule generalizes better to other languages, helping the translator. 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Hello { plural value = $numberOfWorlds 1 = 'World' other = 'Worlds' } !</h1> <p>There { plural value = $numberOfWorlds 1 = 'is one world' other = 'are # worlds' } !</p> <p>There { plural value = $numberOfWorlds one = 'is # world' other = 'are # worlds' } !</p> German: 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Hallo { plural value = $numberOfWorlds 1 = 'Welt' other = 'Welten' } !</h1> <p>Es gibt { plural value = $numberOfWorlds 1 = 'eine Welt' other = '# Welten' } !</p> <p>Es gibt { plural value = $numberOfWorlds one = '# Welt' other = '# Welten' } !</p> Romanian: Note the additional use of few which is not required in English or German. 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Salut { plural value = $numberOfWorlds 1 = 'lume' other = 'lumi' } !</h1> <p>Exist\u0103 { plural value = $numberOfWorlds 1 = 'o lume' few = '# lumi' other = '# de lumi' } !</p> <p>Exist\u0103 { plural value = $numberOfWorlds one = '# lume' few = '# lumi' other = '# de lumi' } !</p> Russian: Note the difference between 1 (exactly 1 ) and one (ending in 1 , except ending in 11 ). 1 2 3 { assign var = numberOfWorlds value = 2 } <h1>\u041f\u0440\u0438\u0432\u0435\u0442 { plural value = $numberOfWorld 1 = '\u043c\u0438\u0440' other = '\u043c\u0438\u0440\u044b' } !</h1> <p>\u0415\u0441\u0442\u044c { plural value = $numberOfWorlds 1 = '\u043c\u0438\u0440' one = '# \u043c\u0438\u0440' few = '# \u043c\u0438\u0440\u0430' many = '# \u043c\u0438\u0440\u043e\u0432' other = '# \u043c\u0438\u0440\u043e\u0432' } !</p> Attribute Description value The value that is used to select the proper phrase. other The phrase that is used when no other selector matches. Any Category Name The phrase that is used when value belongs to the named category. Available categories depend on the language. Any Integer The phrase that is used when value is that exact integer. prepend # If a string should be prepended to the value of a variable, prepend can be used: 1 2 3 4 5 6 7 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } { prepend var = templateVariable value = '2' } { $templateVariable } { * now prints '2newValue' * } If the variables does not exist yet, prepend creates a new one with the given value. If prepend is used on an array as the variable, the value is prepended to all elements of the array. shortUnit # shortUnit shortens numbers larger than 1000 by using unit suffixes: 1 2 { 10000 | shortUnit } { * prints 10k * } { 5400000 | shortUnit } { * prints 5.4M * } smallpages # smallpages generates a smaller version of pages by using adding the small CSS class to the generated <nav> element and only showing 7 instead of 9 links. tableWordwrap # tableWordwrap inserts zero width spaces every 30 characters in words longer than 30 characters. 1 { $foo | tableWordwrap } time # time generates an HTML time elements based on a timestamp that shows a relative time or the absolute time if the timestamp more than six days ago. 1 { $timestamp | time } { * prints a '<time>' element * } truncate # truncate truncates a long string into a shorter one: 1 2 3 { $foo | truncate : 35 } { $foo | truncate : 35 : '_' : true } Parameter Number Description 0 truncated string 1 truncated length; 80 by default 2 ellipsis symbol; wcf\\util\\StringUtil::HELLIP by default 3 if true , words can be broken up in the middle; false by default 5.3+ user # user generates links to user profiles. The mandatory object parameter requires an instances of UserProfile . The optional type parameter is responsible for what the generated link contains: type='default' (also applies if no type is given) outputs the formatted username relying on the \u201cUser Marking\u201d setting of the relevant user group. Additionally, the user popover card will be shown when hovering over the generated link. type='plain' outputs the username without additional formatting. type='avatar(\\d+)' outputs the user\u2019s avatar in the specified size, i.e., avatar48 outputs the avatar with a width and height of 48 pixels. The last special attribute is append whose contents are appended to the href attribute of the generated anchor element. All of the other attributes matching ~^[a-z]+([A-z]+)+$~ , except for href which may not be added, are added as attributes to the anchor element. Examples: 1 { user object = $user } generates 1 <a href=\" { $user -> getLink () } \" data-object-id=\" { $user -> userID } \" class=\"userLink\"> { @ $user -> getFormattedUsername () } </a> and 1 { user object = $user type = 'avatar48' foo = 'bar' } generates 1 <a href=\" { $user -> getLink () } \" foo=\"bar\"> { @ $object -> getAvatar ()-> getImageTag ( 48 ) } </a>","title":"Template Plugins"},{"location":"view/template-plugins/#template-plugins","text":"","title":"Template Plugins"},{"location":"view/template-plugins/#53-anchor","text":"The anchor template plugin creates a HTML elements. The easiest way to use the template plugin is to pass it an instance of ITitledLinkObject : 1 { anchor object = $object } generates the same output as 1 <a href=\" { $object -> getLink () } \"> { $object -> getTitle () } </a> Instead of an object parameter, a link and content parameter can be used: 1 { anchor link = $linkObject content = $content } where $linkObject implements ILinkableObject and $content is either an object implementing ITitledObject or having a __toString() method or $content is a string or a number. The last special attribute is append whose contents are appended to the href attribute of the generated anchor element. All of the other attributes matching ~^[a-z]+([A-z]+)+$~ , expect for href which is disallowed, are added as attributes to the anchor element. If an object attribute is present, the object also implements IPopoverObject and if the return value of IPopoverObject::getPopoverLinkClass() is included in the class attribute of the anchor tag, data-object-id is automatically added. This functionality makes it easy to generate links with popover support. Instead of 1 <a href=\" { $entry -> getLink () } \" class=\"blogEntryLink\" data-object-id=\" { @ $entry -> entryID } \"> { $entry -> subject } </a> using 1 { anchor object = $entry class = 'blogEntryLink' } is sufficient if Entry::getPopoverLinkClass() returns blogEntryLink .","title":"5.3+ anchor"},{"location":"view/template-plugins/#53-anchorattributes","text":"anchorAttributes compliments the StringUtil::getAnchorTagAttributes(string, bool): string method. It allows to easily generate the necessary attributes for an anchor tag based off the destination URL. 1 <a href=\"https://www.example.com\" { anchorAttributes url = 'https://www.example.com' appendHref = false appendClassname = true isUgc = true } > Attribute Description url destination URL appendHref whether the href attribute should be generated; true by default isUgc whether the rel=\"ugc\" attribute should be generated; false by default appendClassname whether the class=\"externalURL\" attribute should be generated; true by default","title":"5.3+ anchorAttributes"},{"location":"view/template-plugins/#append","text":"If a string should be appended to the value of a variable, append can be used: 1 2 3 4 5 6 7 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } { append var = templateVariable value = '2' } { $templateVariable } { * now prints 'newValue2 * } If the variables does not exist yet, append creates a new one with the given value. If append is used on an array as the variable, the value is appended to all elements of the array.","title":"append"},{"location":"view/template-plugins/#assign","text":"New template variables can be declared and new values can be assigned to existing template variables using assign : 1 2 3 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * }","title":"assign"},{"location":"view/template-plugins/#capture","text":"In some situations, assign is not sufficient to assign values to variables in templates if the value is complex. Instead, capture can be used: 1 2 3 4 5 6 7 { capture var = templateVariable } { if $foo } <p> { $bar } </p> { else } <small> { $baz } </small> { /if } { /capture }","title":"capture"},{"location":"view/template-plugins/#concat","text":"concat is a modifier used to concatenate multiple strings: 1 2 3 4 5 { assign var = foo value = 'foo' } { assign var = templateVariable value = 'bar' | concat : $foo } { $templateVariable } { * prints 'foobar * }","title":"concat"},{"location":"view/template-plugins/#counter","text":"counter can be used to generate and optionally print a counter: 1 2 3 4 5 6 7 { counter name = fooCounter print = true } { * prints '1' * } { counter name = fooCounter print = true } { * prints '2' now * } { counter name = fooCounter } { * prints nothing, but counter value is '3' now internally * } { counter name = fooCounter print = true } { * prints '4' * } Counter supports the following attributes: Attribute Description assign optional name of the template variable the current counter value is assigned to direction counting direction, either up or down ; up by default name name of the counter, relevant if multiple counters are used simultaneously print if true , the current counter value is printed; false by default skip positive counting increment; 1 by default start start counter value; 1 by default","title":"counter"},{"location":"view/template-plugins/#54-csrftoken","text":"{csrfToken} prints out the session's CSRF token (\u201cSecurity Token\u201d). 1 2 3 4 5 <form action=\" { link controller = \"Foo\" }{ /link } \" method=\"post\"> { * snip * } { csrfToken } </form> The {csrfToken} template plugin supports a type parameter. Specifying this parameter might be required in rare situations. Please check the implementation for details.","title":"5.4+ csrfToken"},{"location":"view/template-plugins/#currency","text":"currency is a modifier used to format currency values with two decimals using language dependent thousands separators and decimal point: 1 2 3 { assign var = currencyValue value = 12.345 } { $currencyValue | currency } { * prints '12.34' * }","title":"currency"},{"location":"view/template-plugins/#cycle","text":"cycle can be used to cycle between different values: 1 2 3 4 5 6 7 { cycle name = fooCycle values = 'bar,baz' } { * prints 'bar' * } { cycle name = fooCycle } { * prints 'baz' * } { cycle name = fooCycle advance = false } { * prints 'baz' again * } { cycle name = fooCycle } { * prints 'bar' * } The values attribute only has to be present for the first call. If cycle is used in a loop, the presence of the same values in consecutive calls has no effect. Only once the values change, the cycle is reset. Attribute Description advance if true , the current cycle value is advanced to the next value; true by default assign optional name of the template variable the current cycle value is assigned to; if used, print is set to false delimiter delimiter between the different cycle values; , by default name name of the cycle, relevant if multiple cycles are used simultaneously print if true , the current cycle value is printed, false by default reset if true , the current cycle value is set to the first value, false by default values string containing the different cycles values, also see delimiter","title":"cycle"},{"location":"view/template-plugins/#date","text":"date generated a formatted date using wcf\\util\\DateUtil::format() with DateUtil::DATE_FORMAT internally. 1 { $timestamp | date }","title":"date"},{"location":"view/template-plugins/#31-dateinterval","text":"dateInterval calculates the difference between two unix timestamps and generated a textual date interval. 1 { dateInterval start = $startTimestamp end = $endTimestamp full = true format = 'sentence' } Attribute Description end end of the time interval; current timestamp by default (though either start or end has to be set) format output format, either default , sentence , or plain ; defaults to default , see wcf\\util\\DateUtil::FORMAT_* constants full if true , full difference in minutes is shown; if false , only the longest time interval is shown; false by default start start of the time interval; current timestamp by default (though either start or end has to be set)","title":"3.1+ dateInterval"},{"location":"view/template-plugins/#encodejs","text":"encodeJS encodes a string to be used as a single-quoted string in JavaScript by replacing \\\\ with \\\\\\\\ , ' with \\' , linebreaks with \\n , and / with \\/ . 1 2 3 <script> var foo = ' { @ $foo | encodeJS } '; </script>","title":"encodeJS"},{"location":"view/template-plugins/#escapecdata","text":"escapeCDATA encodes a string to be used in a CDATA element by replacing ]]> with ]]]]><![CDATA[> . 1 <![CDATA[ { @ $foo | encodeCDATA } ]]>","title":"escapeCDATA"},{"location":"view/template-plugins/#event","text":"event provides extension points in templates that template listeners can use. 1 { event name = 'foo' }","title":"event"},{"location":"view/template-plugins/#fetch","text":"fetch fetches the contents of a file using file_get_contents . 1 2 3 { fetch file = 'foo.html' } { * prints the contents of `foo.html` * } { fetch file = 'bar.html' assign = bar } { * assigns the contents of `foo.html` to `$bar`; does not print the contents * }","title":"fetch"},{"location":"view/template-plugins/#filesizebinary","text":"filesizeBinary formats the filesize using binary filesize (in bytes). 1 { $filesize | filesizeBinary }","title":"filesizeBinary"},{"location":"view/template-plugins/#filesize","text":"filesize formats the filesize using filesize (in bytes). 1 { $filesize | filesize }","title":"filesize"},{"location":"view/template-plugins/#hascontent","text":"In many cases, conditional statements can be used to determine if a certain section of a template is shown: 1 2 3 { if $foo === 'bar' } only shown if $foo is bar { /if } In some situations, however, such conditional statements are not sufficient. One prominent example is a template event: 1 2 3 4 5 6 7 8 9 { if $foo === 'bar' } <ul> { if $foo === 'bar' } <li>Bar</li> { /if } { event name = 'listItems' } </li> { /if } In this example, if $foo !== 'bar' , the list will not be shown, regardless of the additional template code provided by template listeners. In such a situation, hascontent has to be used: 1 2 3 4 5 6 7 8 9 10 11 { hascontent } <ul> { content } { if $foo === 'bar' } <li>Bar</li> { /if } { event name = 'listItems' } { /content } </ul> { /hascontent } If the part of the template wrapped in the content tags has any (trimmed) content, the part of the template wrapped by hascontent tags is shown (including the part wrapped by the content tags), otherwise nothing is shown. Thus, this construct avoids an empty list compared to the if solution above. Like foreach , hascontent also supports an else part: 1 2 3 4 5 6 7 8 9 { hascontent } <ul> { content } { * \u2026 * } { /content } </ul> { hascontentelse } no list { /hascontent }","title":"hascontent"},{"location":"view/template-plugins/#htmlcheckboxes","text":"htmlCheckboxes generates a list of HTML checkboxes. 1 2 3 { htmlCheckboxes name = foo options = $fooOptions selected = $currentFoo } { htmlCheckboxes name = bar output = $barLabels values = $barValues selected = $currentBar } Attribute Description 5.2+ disabled if true , all checkboxes are disabled disableEncoding if true , the values are not passed through wcf\\util\\StringUtil::encodeHTML() ; false by default name name attribute of the input checkbox element output array used as keys and values for options if present; not present by default options array selectable options with the key used as value attribute and the value as the checkbox label selected current selected value(s) separator separator between the different checkboxes in the generated output; empty string by default values array with values used in combination with output , where output is only used as keys for options","title":"htmlCheckboxes"},{"location":"view/template-plugins/#htmloptions","text":"htmlOptions generates an select HTML element. 1 2 3 4 5 6 { htmlOptions name = 'foo' options = $options selected = $selected } <select name=\"bar\"> <option value=\"\" { if ! $selected } selected { /if } > { lang } foo.bar.default { /lang } </option> { htmlOptions options = $options selected = $selected } { * no `name` attribute * } </select> Attribute Description disableEncoding if true , the values are not passed through wcf\\util\\StringUtil::encodeHTML() ; false by default object optional instance of wcf\\data\\DatabaseObjectList that provides the selectable options (overwrites options attribute internally) name name attribute of the select element; if not present, only the contents of the select element are printed output array used as keys and values for options if present; not present by default values array with values used in combination with output , where output is only used as keys for options options array selectable options with the key used as value attribute and the value as the option label; if a value is an array, an optgroup is generated with the array key as the optgroup label selected current selected value(s) All additional attributes are added as attributes of the select HTML element.","title":"htmlOptions"},{"location":"view/template-plugins/#implode","text":"implodes transforms an array into a string and prints it. 1 { implode from = $array key = key item = item glue = \";\" }{ $key } : { $value }{ /implode } Attribute Description from array with the imploded values glue separator between the different array values; ', ' by default item template variable name where the current array value is stored during the iteration key optional template variable name where the current array key is stored during the iteration","title":"implode"},{"location":"view/template-plugins/#52-ipsearch","text":"ipSearch generates a link to search for an IP address. 1 { \"127.0.0.1\" | ipSearch }","title":"5.2+ ipSearch"},{"location":"view/template-plugins/#js","text":"js generates script tags based on whether ENABLE_DEBUG_MODE and VISITOR_USE_TINY_BUILD are enabled. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 { js application = 'wbb' file = 'WBB' } { * generates 'http://example.com/js/WBB.js' * } { js application = 'wcf' file = 'WCF.User' bundle = 'WCF.Combined' } { * generates 'http://example.com/wcf/js/WCF.User.js' if ENABLE_DEBUG_MODE=1 * } { * generates 'http://example.com/wcf/js/WCF.Combined.min.js' if ENABLE_DEBUG_MODE=0 * } { js application = 'wcf' lib = 'jquery' } { * generates 'http://example.com/wcf/js/3rdParty/jquery.js' * } { js application = 'wcf' lib = 'jquery-ui' file = 'awesomeWidget' } { * generates 'http://example.com/wcf/js/3rdParty/jquery-ui/awesomeWidget.js' * } { js application = 'wcf' file = 'WCF.User' bundle = 'WCF.Combined' hasTiny = true } { * generates 'http://example.com/wcf/js/WCF.User.js' if ENABLE_DEBUG_MODE=1 * } { * generates 'http://example.com/wcf/js/WCF.Combined.min.js' (ENABLE_DEBUG_MODE=0 * } { * generates 'http://example.com/wcf/js/WCF.Combined.tiny.min.js' if ENABLE_DEBUG_MODE=0 and VISITOR_USE_TINY_BUILD=1 * }","title":"js"},{"location":"view/template-plugins/#53-jslang","text":"jslang works like lang with the difference that the resulting string is automatically passed through encodeJS . 1 2 3 4 5 6 7 require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' , } ); // \u2026 } );","title":"5.3+ jslang"},{"location":"view/template-plugins/#55-json","text":"json JSON-encodes the given value. 1 2 3 <script> let data = { \"title\" : { @ $foo -> getTitle ()| json } } ; </script>","title":"5.5+ json"},{"location":"view/template-plugins/#lang","text":"lang replaces a language items with its value. 1 2 3 4 5 6 7 { lang } foo.bar.baz { /lang } { lang __literal = true } foo.bar.baz { /lang } { lang foo = 'baz' } foo.bar.baz { /lang } { lang } foo.bar.baz. { $action }{ /lang } Attribute Description __encode if true , the output will be passed through StringUtil::encodeHTML() __literal if true , template variables will not resolved but printed as they are in the language item; false by default __optional if true and the language item does not exist, an empty string is printed; false by default All additional attributes are available when parsing the language item.","title":"lang"},{"location":"view/template-plugins/#language","text":"language replaces a language items with its value. If the template variable __language exists, this language object will be used instead of WCF::getLanguage() . This modifier is useful when assigning the value directly to a variable. Note that template scripting is applied to the output of the variable, which can lead to unwanted side effects. Use phrase instead if you don't want to use template scripting. 1 2 3 { $languageItem | language } { assign var = foo value = $languageItem | language }","title":"language"},{"location":"view/template-plugins/#link","text":"link generates internal links using LinkHandler . 1 <a href=\" { link controller = 'FooList' application = 'bar' } param1=2¶m2=A { /link } \">Foo</a> Attribute Description application abbreviation of the application the controller belongs to; wcf by default controller name of the controller; if not present, the landing page is linked in the frontend and the index page in the ACP encode if true , the generated link is passed through wcf\\util\\StringUtil::encodeHTML() ; true by default isEmail sets encode=false and forces links to link to the frontend Additional attributes are passed to LinkHandler::getLink() .","title":"link"},{"location":"view/template-plugins/#newlinetobreak","text":"newlineToBreak transforms newlines into HTML <br> elements after encoding the content via wcf\\util\\StringUtil::encodeHTML() . 1 { $foo | newlineToBreak }","title":"newlineToBreak"},{"location":"view/template-plugins/#54-objectaction","text":"objectAction generates action buttons to be used in combination with the WoltLabSuite/Core/Ui/Object/Action API . For detailed information on its usage, we refer to the extensive documentation in the ObjectActionFunctionTemplatePlugin class itself.","title":"5.4+ objectAction"},{"location":"view/template-plugins/#page","text":"page generates an internal link to a CMS page. 1 2 3 4 5 6 7 { page } com.woltlab.wcf.CookiePolicy { /page } { page pageID = 1 }{ /page } { page language = 'de' } com.woltlab.wcf.CookiePolicy { /page } { page languageID = 2 } com.woltlab.wcf.CookiePolicy { /page } Attribute Description pageID unique id of the page (cannot be used together with a page identifier as value) languageID id of the page language (cannot be used together with language ) language language code of the page language (cannot be used together with languageID )","title":"page"},{"location":"view/template-plugins/#pages","text":"pages generates a pagination. 1 2 3 { pages controller = 'FooList' link = \"pageNo=%d\" print = true assign = pagesLinks } { * prints pagination * } { @ $pagesLinks } { * prints same pagination again * } Attribute Description assign optional name of the template variable the pagination is assigned to controller controller name of the generated links link additional link parameter where %d will be replaced with the relevant page number pages maximum number of of pages; by default, the template variable $pages is used print if false and assign=true , the pagination is not printed application , id , object , title additional parameters passed to LinkHandler::getLink() to generate page links","title":"pages"},{"location":"view/template-plugins/#55-phrase","text":"phrase replaces a language items with its value. If the template variable __language exists, this language object will be used instead of WCF::getLanguage() . This modifier is useful when assigning the value directly to a variable. phrase should be used instead of language unless you want to explicitly allow template scripting on a variable's output. 1 2 3 { $languageItem | phrase } { assign var = foo value = $languageItem | phrase }","title":"5.5+ phrase"},{"location":"view/template-plugins/#plaintime","text":"plainTime formats a timestamp to include year, month, day, hour, and minutes. The exact formatting depends on the current language (via the language items wcf.date.dateTimeFormat , wcf.date.dateFormat , and wcf.date.timeFormat ). 1 { $timestamp | plainTime }","title":"plainTime"},{"location":"view/template-plugins/#53-plural","text":"plural allows to easily select the correct plural form of a phrase based on a given value . The pluralization logic follows the Unicode Language Plural Rules for cardinal numbers. The # placeholder within the resulting phrase is replaced by the value . It is automatically formatted using StringUtil::formatNumeric . English: Note the use of 1 if the number ( # ) is not used within the phrase and the use of one otherwise. They are equivalent for English, but following this rule generalizes better to other languages, helping the translator. 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Hello { plural value = $numberOfWorlds 1 = 'World' other = 'Worlds' } !</h1> <p>There { plural value = $numberOfWorlds 1 = 'is one world' other = 'are # worlds' } !</p> <p>There { plural value = $numberOfWorlds one = 'is # world' other = 'are # worlds' } !</p> German: 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Hallo { plural value = $numberOfWorlds 1 = 'Welt' other = 'Welten' } !</h1> <p>Es gibt { plural value = $numberOfWorlds 1 = 'eine Welt' other = '# Welten' } !</p> <p>Es gibt { plural value = $numberOfWorlds one = '# Welt' other = '# Welten' } !</p> Romanian: Note the additional use of few which is not required in English or German. 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Salut { plural value = $numberOfWorlds 1 = 'lume' other = 'lumi' } !</h1> <p>Exist\u0103 { plural value = $numberOfWorlds 1 = 'o lume' few = '# lumi' other = '# de lumi' } !</p> <p>Exist\u0103 { plural value = $numberOfWorlds one = '# lume' few = '# lumi' other = '# de lumi' } !</p> Russian: Note the difference between 1 (exactly 1 ) and one (ending in 1 , except ending in 11 ). 1 2 3 { assign var = numberOfWorlds value = 2 } <h1>\u041f\u0440\u0438\u0432\u0435\u0442 { plural value = $numberOfWorld 1 = '\u043c\u0438\u0440' other = '\u043c\u0438\u0440\u044b' } !</h1> <p>\u0415\u0441\u0442\u044c { plural value = $numberOfWorlds 1 = '\u043c\u0438\u0440' one = '# \u043c\u0438\u0440' few = '# \u043c\u0438\u0440\u0430' many = '# \u043c\u0438\u0440\u043e\u0432' other = '# \u043c\u0438\u0440\u043e\u0432' } !</p> Attribute Description value The value that is used to select the proper phrase. other The phrase that is used when no other selector matches. Any Category Name The phrase that is used when value belongs to the named category. Available categories depend on the language. Any Integer The phrase that is used when value is that exact integer.","title":"5.3+ plural"},{"location":"view/template-plugins/#prepend","text":"If a string should be prepended to the value of a variable, prepend can be used: 1 2 3 4 5 6 7 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } { prepend var = templateVariable value = '2' } { $templateVariable } { * now prints '2newValue' * } If the variables does not exist yet, prepend creates a new one with the given value. If prepend is used on an array as the variable, the value is prepended to all elements of the array.","title":"prepend"},{"location":"view/template-plugins/#shortunit","text":"shortUnit shortens numbers larger than 1000 by using unit suffixes: 1 2 { 10000 | shortUnit } { * prints 10k * } { 5400000 | shortUnit } { * prints 5.4M * }","title":"shortUnit"},{"location":"view/template-plugins/#smallpages","text":"smallpages generates a smaller version of pages by using adding the small CSS class to the generated <nav> element and only showing 7 instead of 9 links.","title":"smallpages"},{"location":"view/template-plugins/#tablewordwrap","text":"tableWordwrap inserts zero width spaces every 30 characters in words longer than 30 characters. 1 { $foo | tableWordwrap }","title":"tableWordwrap"},{"location":"view/template-plugins/#time","text":"time generates an HTML time elements based on a timestamp that shows a relative time or the absolute time if the timestamp more than six days ago. 1 { $timestamp | time } { * prints a '<time>' element * }","title":"time"},{"location":"view/template-plugins/#truncate","text":"truncate truncates a long string into a shorter one: 1 2 3 { $foo | truncate : 35 } { $foo | truncate : 35 : '_' : true } Parameter Number Description 0 truncated string 1 truncated length; 80 by default 2 ellipsis symbol; wcf\\util\\StringUtil::HELLIP by default 3 if true , words can be broken up in the middle; false by default","title":"truncate"},{"location":"view/template-plugins/#53-user","text":"user generates links to user profiles. The mandatory object parameter requires an instances of UserProfile . The optional type parameter is responsible for what the generated link contains: type='default' (also applies if no type is given) outputs the formatted username relying on the \u201cUser Marking\u201d setting of the relevant user group. Additionally, the user popover card will be shown when hovering over the generated link. type='plain' outputs the username without additional formatting. type='avatar(\\d+)' outputs the user\u2019s avatar in the specified size, i.e., avatar48 outputs the avatar with a width and height of 48 pixels. The last special attribute is append whose contents are appended to the href attribute of the generated anchor element. All of the other attributes matching ~^[a-z]+([A-z]+)+$~ , except for href which may not be added, are added as attributes to the anchor element. Examples: 1 { user object = $user } generates 1 <a href=\" { $user -> getLink () } \" data-object-id=\" { $user -> userID } \" class=\"userLink\"> { @ $user -> getFormattedUsername () } </a> and 1 { user object = $user type = 'avatar48' foo = 'bar' } generates 1 <a href=\" { $user -> getLink () } \" foo=\"bar\"> { @ $object -> getAvatar ()-> getImageTag ( 48 ) } </a>","title":"5.3+ user"},{"location":"view/templates/","text":"Templates # Templates are responsible for the output a user sees when requesting a page (while the PHP code is responsible for providing the data that will be shown). Templates are text files with .tpl as the file extension. WoltLab Suite Core compiles the template files once into a PHP file that is executed when a user requests the page. In subsequent request, as the PHP file containing the compiled template already exists, compiling the template is not necessary anymore. Template Types and Conventions # WoltLab Suite Core supports two types of templates: frontend templates (or simply templates ) and backend templates ( ACP templates ). Each type of template is only available in its respective domain, thus frontend templates cannot be included or used in the ACP and vice versa. For pages and forms, the name of the template matches the unqualified name of the PHP class except for the Page or Form suffix: RegisterForm.class.php \u2192 register.tpl UserPage.class.php \u2192 user.tpl If you follow this convention, WoltLab Suite Core will automatically determine the template name so that you do not have to explicitly set it. For forms that handle creating and editing objects, in general, there are two form classes: FooAddForm and FooEditForm . WoltLab Suite Core, however, generally only uses one template fooAdd.tpl and the template variable $action to distinguish between creating a new object ( $action = 'add' ) and editing an existing object ( $action = 'edit' ) as the differences between templates for adding and editing an object are minimal. Installing Templates # Templates and ACP templates are installed by two different package installation plugins: the template PIP and the ACP template PIP . More information about installing templates can be found on those pages. Base Templates # Frontend # 1 2 3 4 5 { include file = 'header' } { * content * } { include file = 'footer' } Backend # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'foo.bar.baz' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\">Title</h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> { * your default content header navigation buttons * } { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { * content * } { include file = 'footer' } foo.bar.baz is the language item that contains the title of the page. Common Template Components # Forms # For new forms, use the new form builder API introduced with WoltLab Suite 5.2. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <form method=\"post\" action=\" { link controller = 'FooBar' }{ /link } \"> <div class=\"section\"> <dl { if $errorField == 'baz' } class=\"formError\" { /if } > <dt><label for=\"baz\"> { lang } foo.bar.baz { /lang } </label></dt> <dd> <input type=\"text\" id=\"baz\" name=\"baz\" value=\" { $baz } \" class=\"long\" required autofocus> { if $errorField == 'baz' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } foo.bar.baz.error. { @ $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> <dl> <dt><label for=\"bar\"> { lang } foo.bar.bar { /lang } </label></dt> <dd> <textarea name=\"bar\" id=\"bar\" cols=\"40\" rows=\"10\"> { $bar } </textarea> { if $errorField == 'bar' } <small class=\"innerError\"> { lang } foo.bar.bar.error. { @ $errorType }{ /lang } </small> { /if } </dd> </dl> { * other fields * } { event name = 'dataFields' } </div> { * other sections * } { event name = 'sections' } <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> { csrfToken } </div> </form> Tab Menus # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <div class=\"section tabMenuContainer\"> <nav class=\"tabMenu\"> <ul> <li><a href=\"#tab1\">Tab 1</a></li> <li><a href=\"#tab2\">Tab 2</a></li> { event name = 'tabMenuTabs' } </ul> </nav> <div id=\"tab1\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of first tab * } </div> </div> <div id=\"tab2\" class=\"tabMenuContainer tabMenuContent\"> <nav class=\"menu\"> <ul> <li><a href=\"#tab2A\">Tab 2A</a></li> <li><a href=\"#tab2B\">Tab 2B</a></li> { event name = 'tabMenuTab2Subtabs' } </ul> </nav> <div id=\"tab2A\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of first subtab for second tab * } </div> </div> <div id=\"tab2B\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of second subtab for second tab * } </div> </div> { event name = 'tabMenuTab2Contents' } </div> { event name = 'tabMenuContents' } </div> Template Scripting # Template Variables # Template variables can be assigned via WCF::getTPL()->assign('foo', 'bar') and accessed in templates via $foo : {$foo} will result in the contents of $foo to be passed to StringUtil::encodeHTML() before being printed. {#$foo} will result in the contents of $foo to be passed to StringUtil::formatNumeric() before being printed. Thus, this method is relevant when printing numbers and having them formatted correctly according the the user\u2019s language. {@$foo} will result in the contents of $foo to be printed directly. In general, this method should not be used for user-generated input. Multiple template variables can be assigned by passing an array: 1 2 3 4 WCF :: getTPL () -> assign ([ 'foo' => 'bar' , 'baz' => false ]); Modifiers # If you want to call a function on a variable, you can use the modifier syntax: {@$foo|trim} , for example, results in the trimmed contents of $foo to be printed. System Template Variable # The template variable $tpl is automatically assigned and is an array containing different data: $tpl[get] contains $_GET . $tpl[post] contains $_POST . $tpl[cookie] contains $_COOKIE . $tpl[server] contains $_SERVER . $tpl[env] contains $_ENV . $tpl[now] contains TIME_NOW (current timestamp). Furthermore, the following template variables are also automatically assigned: $__wcf contains the WCF object (or WCFACP object in the backend). Comments # Comments are wrapped in {* and *} and can span multiple lines: 1 2 { * some comment * } The template compiler discards the comments, so that they not included in the compiled template. Conditions # Conditions follow a similar syntax to PHP code: 1 2 3 4 5 6 7 { if $foo === 'bar' } foo is bar { elseif $foo === 'baz' } foo is baz { else } foo is neither bar nor baz { /if } The supported operators in conditions are === , !== , == , != , <= , < , >= , > , || , && , ! , and = . More examples: 1 2 3 { if $bar | isset } \u2026 { /if } { if $bar | count > 3 && $bar | count < 100 } \u2026 { /if } Foreach Loops # Foreach loops allow to iterate over arrays or iterable objects: 1 2 3 4 5 <ul> { foreach from = $array key = key item = value } <li> { $key } : { $value } </li> { /foreach } </ul> While the from attribute containing the iterated structure and the item attribute containg the current value are mandatory, the key attribute is optional. If the foreach loop has a name assigned to it via the name attribute, the $tpl template variable provides additional data about the loop: 1 2 3 4 5 6 7 8 9 10 11 <ul> { foreach from = $array key = key item = value name = foo } { if $tpl [ foreach ][ foo ][ first ] } something special for the first iteration { elseif $tpl [ foreach ][ foo ][ last ] } something special for the last iteration { /if } <li>iteration { # $tpl [ foreach ][ foo ][ iteration ]+ 1 } out of { # $tpl [ foreach ][ foo ][ total ] } { $key } : { $value } </li> { /foreach } </ul> In contrast to PHP\u2019s foreach loop, templates also support foreachelse : 1 2 3 4 5 { foreach from = $array item = value } \u2026 { foreachelse } there is nothing to iterate over { /foreach } Including Other Templates # To include template named foo from the same domain (frontend/backend), you can use 1 { include file = 'foo' } If the template belongs to an application, you have to specify that application using the application attribute: 1 { include file = 'foo' application = 'app' } Additional template variables can be passed to the included template as additional attributes: 1 { include file = 'foo' application = 'app' var1 = 'foo1' var2 = 'foo2' } Template Plugins # An overview of all available template plugins can be found here .","title":"Templates"},{"location":"view/templates/#templates","text":"Templates are responsible for the output a user sees when requesting a page (while the PHP code is responsible for providing the data that will be shown). Templates are text files with .tpl as the file extension. WoltLab Suite Core compiles the template files once into a PHP file that is executed when a user requests the page. In subsequent request, as the PHP file containing the compiled template already exists, compiling the template is not necessary anymore.","title":"Templates"},{"location":"view/templates/#template-types-and-conventions","text":"WoltLab Suite Core supports two types of templates: frontend templates (or simply templates ) and backend templates ( ACP templates ). Each type of template is only available in its respective domain, thus frontend templates cannot be included or used in the ACP and vice versa. For pages and forms, the name of the template matches the unqualified name of the PHP class except for the Page or Form suffix: RegisterForm.class.php \u2192 register.tpl UserPage.class.php \u2192 user.tpl If you follow this convention, WoltLab Suite Core will automatically determine the template name so that you do not have to explicitly set it. For forms that handle creating and editing objects, in general, there are two form classes: FooAddForm and FooEditForm . WoltLab Suite Core, however, generally only uses one template fooAdd.tpl and the template variable $action to distinguish between creating a new object ( $action = 'add' ) and editing an existing object ( $action = 'edit' ) as the differences between templates for adding and editing an object are minimal.","title":"Template Types and Conventions"},{"location":"view/templates/#installing-templates","text":"Templates and ACP templates are installed by two different package installation plugins: the template PIP and the ACP template PIP . More information about installing templates can be found on those pages.","title":"Installing Templates"},{"location":"view/templates/#base-templates","text":"","title":"Base Templates"},{"location":"view/templates/#frontend","text":"1 2 3 4 5 { include file = 'header' } { * content * } { include file = 'footer' }","title":"Frontend"},{"location":"view/templates/#backend","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'foo.bar.baz' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\">Title</h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> { * your default content header navigation buttons * } { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { * content * } { include file = 'footer' } foo.bar.baz is the language item that contains the title of the page.","title":"Backend"},{"location":"view/templates/#common-template-components","text":"","title":"Common Template Components"},{"location":"view/templates/#forms","text":"For new forms, use the new form builder API introduced with WoltLab Suite 5.2. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <form method=\"post\" action=\" { link controller = 'FooBar' }{ /link } \"> <div class=\"section\"> <dl { if $errorField == 'baz' } class=\"formError\" { /if } > <dt><label for=\"baz\"> { lang } foo.bar.baz { /lang } </label></dt> <dd> <input type=\"text\" id=\"baz\" name=\"baz\" value=\" { $baz } \" class=\"long\" required autofocus> { if $errorField == 'baz' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } foo.bar.baz.error. { @ $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> <dl> <dt><label for=\"bar\"> { lang } foo.bar.bar { /lang } </label></dt> <dd> <textarea name=\"bar\" id=\"bar\" cols=\"40\" rows=\"10\"> { $bar } </textarea> { if $errorField == 'bar' } <small class=\"innerError\"> { lang } foo.bar.bar.error. { @ $errorType }{ /lang } </small> { /if } </dd> </dl> { * other fields * } { event name = 'dataFields' } </div> { * other sections * } { event name = 'sections' } <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> { csrfToken } </div> </form>","title":"Forms"},{"location":"view/templates/#tab-menus","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <div class=\"section tabMenuContainer\"> <nav class=\"tabMenu\"> <ul> <li><a href=\"#tab1\">Tab 1</a></li> <li><a href=\"#tab2\">Tab 2</a></li> { event name = 'tabMenuTabs' } </ul> </nav> <div id=\"tab1\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of first tab * } </div> </div> <div id=\"tab2\" class=\"tabMenuContainer tabMenuContent\"> <nav class=\"menu\"> <ul> <li><a href=\"#tab2A\">Tab 2A</a></li> <li><a href=\"#tab2B\">Tab 2B</a></li> { event name = 'tabMenuTab2Subtabs' } </ul> </nav> <div id=\"tab2A\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of first subtab for second tab * } </div> </div> <div id=\"tab2B\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of second subtab for second tab * } </div> </div> { event name = 'tabMenuTab2Contents' } </div> { event name = 'tabMenuContents' } </div>","title":"Tab Menus"},{"location":"view/templates/#template-scripting","text":"","title":"Template Scripting"},{"location":"view/templates/#template-variables","text":"Template variables can be assigned via WCF::getTPL()->assign('foo', 'bar') and accessed in templates via $foo : {$foo} will result in the contents of $foo to be passed to StringUtil::encodeHTML() before being printed. {#$foo} will result in the contents of $foo to be passed to StringUtil::formatNumeric() before being printed. Thus, this method is relevant when printing numbers and having them formatted correctly according the the user\u2019s language. {@$foo} will result in the contents of $foo to be printed directly. In general, this method should not be used for user-generated input. Multiple template variables can be assigned by passing an array: 1 2 3 4 WCF :: getTPL () -> assign ([ 'foo' => 'bar' , 'baz' => false ]);","title":"Template Variables"},{"location":"view/templates/#modifiers","text":"If you want to call a function on a variable, you can use the modifier syntax: {@$foo|trim} , for example, results in the trimmed contents of $foo to be printed.","title":"Modifiers"},{"location":"view/templates/#system-template-variable","text":"The template variable $tpl is automatically assigned and is an array containing different data: $tpl[get] contains $_GET . $tpl[post] contains $_POST . $tpl[cookie] contains $_COOKIE . $tpl[server] contains $_SERVER . $tpl[env] contains $_ENV . $tpl[now] contains TIME_NOW (current timestamp). Furthermore, the following template variables are also automatically assigned: $__wcf contains the WCF object (or WCFACP object in the backend).","title":"System Template Variable"},{"location":"view/templates/#comments","text":"Comments are wrapped in {* and *} and can span multiple lines: 1 2 { * some comment * } The template compiler discards the comments, so that they not included in the compiled template.","title":"Comments"},{"location":"view/templates/#conditions","text":"Conditions follow a similar syntax to PHP code: 1 2 3 4 5 6 7 { if $foo === 'bar' } foo is bar { elseif $foo === 'baz' } foo is baz { else } foo is neither bar nor baz { /if } The supported operators in conditions are === , !== , == , != , <= , < , >= , > , || , && , ! , and = . More examples: 1 2 3 { if $bar | isset } \u2026 { /if } { if $bar | count > 3 && $bar | count < 100 } \u2026 { /if }","title":"Conditions"},{"location":"view/templates/#foreach-loops","text":"Foreach loops allow to iterate over arrays or iterable objects: 1 2 3 4 5 <ul> { foreach from = $array key = key item = value } <li> { $key } : { $value } </li> { /foreach } </ul> While the from attribute containing the iterated structure and the item attribute containg the current value are mandatory, the key attribute is optional. If the foreach loop has a name assigned to it via the name attribute, the $tpl template variable provides additional data about the loop: 1 2 3 4 5 6 7 8 9 10 11 <ul> { foreach from = $array key = key item = value name = foo } { if $tpl [ foreach ][ foo ][ first ] } something special for the first iteration { elseif $tpl [ foreach ][ foo ][ last ] } something special for the last iteration { /if } <li>iteration { # $tpl [ foreach ][ foo ][ iteration ]+ 1 } out of { # $tpl [ foreach ][ foo ][ total ] } { $key } : { $value } </li> { /foreach } </ul> In contrast to PHP\u2019s foreach loop, templates also support foreachelse : 1 2 3 4 5 { foreach from = $array item = value } \u2026 { foreachelse } there is nothing to iterate over { /foreach }","title":"Foreach Loops"},{"location":"view/templates/#including-other-templates","text":"To include template named foo from the same domain (frontend/backend), you can use 1 { include file = 'foo' } If the template belongs to an application, you have to specify that application using the application attribute: 1 { include file = 'foo' application = 'app' } Additional template variables can be passed to the included template as additional attributes: 1 { include file = 'foo' application = 'app' var1 = 'foo1' var2 = 'foo2' }","title":"Including Other Templates"},{"location":"view/templates/#template-plugins","text":"An overview of all available template plugins can be found here .","title":"Template Plugins"}]}
\ No newline at end of file
+{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"WoltLab Suite 5.5 Documentation # Introduction # This documentation explains the basic API functionality and the creation of own packages. It is expected that you are somewhat experienced with PHP , object-oriented programming and MySQL . Head over to the quick start tutorial to learn more. About WoltLab Suite # WoltLab Suite Core as well as most of the other packages are available on GitHub and are licensed under the terms of the GNU Lesser General Public License 2.1 .","title":"WoltLab Suite 5.5 Documentation"},{"location":"#woltlab-suite-55-documentation","text":"","title":"WoltLab Suite 5.5 Documentation"},{"location":"#introduction","text":"This documentation explains the basic API functionality and the creation of own packages. It is expected that you are somewhat experienced with PHP , object-oriented programming and MySQL . Head over to the quick start tutorial to learn more.","title":"Introduction"},{"location":"#about-woltlab-suite","text":"WoltLab Suite Core as well as most of the other packages are available on GitHub and are licensed under the terms of the GNU Lesser General Public License 2.1 .","title":"About WoltLab Suite"},{"location":"getting-started/","text":"Creating a simple package # Setup and Requirements # This guide will help you to create a simple package that provides a simple test page. It is nothing too fancy, but you can use it as the foundation for your next project. There are some requirements you should met before starting: Text editor with syntax highlighting for PHP, Notepad++ is a solid pick *.php and *.tpl should be encoded with ANSI/ASCII *.xml are always encoded with UTF-8, but omit the BOM (byte-order-mark) Use tabs instead of spaces to indent lines It is recommended to set the tab width to 8 spaces, this is used in the entire software and will ease reading the source files An active installation of WoltLab Suite An application to create *.tar archives, e.g. 7-Zip on Windows The package.xml File # We want to create a simple page that will display the sentence \"Hello World\" embedded into the application frame. Create an empty directory in the workspace of your choice to start with. Create a new file called package.xml and insert the code below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/package.xsd\" name= \"com.example.test\" > <packageinformation> <!-- com.example.test --> <packagename> Simple Package </packagename> <packagedescription> A simple package to demonstrate the package system of WoltLab Suite Core </packagedescription> <version> 1.0.0 </version> <date> 2019-04-28 </date> </packageinformation> <authorinformation> <author> Your Name </author> <authorurl> http://www.example.com </authorurl> </authorinformation> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"template\" /> <instruction type= \"page\" /> </instructions> </package> There is an entire chapter on the package system that explains what the code above does and how you can adjust it to fit your needs. For now we'll keep it as it is. The PHP Class # The next step is to create the PHP class which will serve our page: Create the directory files in the same directory where package.xml is located Open files and create the directory lib Open lib and create the directory page Within the directory page , please create the file TestPage.class.php Copy and paste the following code into the TestPage.class.php : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <? php namespace wcf\\page ; use wcf\\system\\WCF ; /** * A simple test page for demonstration purposes. * * @author YOUR NAME * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> */ class TestPage extends AbstractPage { /** * @var string */ protected $greet = '' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_GET [ 'greet' ])) $this -> greet = $_GET [ 'greet' ]; } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( empty ( $this -> greet )) { $this -> greet = 'World' ; } } /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'greet' => $this -> greet ]); } } The class inherits from wcf\\page\\AbstractPage , the default implementation of pages without form controls. It defines quite a few methods that will be automatically invoked in a specific order, for example readParameters() before readData() and finally assignVariables() to pass arbitrary values to the template. The property $greet is defined as World , but can optionally be populated through a GET variable ( index.php?test/&greet=You would output Hello You! ). This extra code illustrates the separation of data processing that takes place within all sort of pages, where all user-supplied data is read from within a single method. It helps organizing the code, but most of all it enforces a clean class logic that does not start reading user input at random places, including the risk to only escape the input of variable $_GET['foo'] 4 out of 5 times. Reading and processing the data is only half the story, now we need a template to display the actual content for our page. You don't need to specify it yourself, it will be automatically guessed based on your namespace and class name, you can read more about it later . Last but not least, you must not include the closing PHP tag ?> at the end, it can cause PHP to break on whitespaces and is not required at all. The Template # Navigate back to the root directory of your package until you see both the files directory and the package.xml . Now create a directory called templates , open it and create the file test.tpl . 1 2 3 4 5 6 7 { include file = 'header' } <div class=\"section\"> Hello { $greet } ! </div> { include file = 'footer' } Templates are a mixture of HTML and Smarty-like template scripting to overcome the static nature of raw HTML. The above code will display the phrase Hello World! in the application frame, just as any other page would render. The included templates header and footer are responsible for the majority of the overall page functionality, but offer a whole lot of customization abilities to influence their behavior and appearance. The Page Definition # The package now contains the PHP class and the matching template, but it is still missing the page definition. Please create the file page.xml in your project's root directory, thus on the same level as the package.xml . 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/page.xsd\" > <import> <page identifier= \"com.example.test.Test\" > <controller> wcf\\page\\TestPage </controller> <name language= \"en\" > Test Page </name> <pageType> system </pageType> </page> </import> </data> You can provide a lot more data for a page, including logical nesting and dedicated handler classes for display in menus. Building the Package # If you have followed the above guidelines carefully, your package directory should now look like this: 1 2 3 4 5 6 7 8 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 TestPage.class.php \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u2514\u2500\u2500 templates \u2514\u2500\u2500 test.tpl Both files and templates are archive-based package components, that deploy their payload using tar archives rather than adding the raw files to the package file. Please create the archive files.tar and add the contents of the files/* directory, but not the directory files/ itself. Repeat the same process for the templates directory, but this time with the file name templates.tar . Place both files in the root of your project. Last but not least, create the package archive com.example.test.tar and add all the files listed below. files.tar package.xml page.xml templates.tar The archive's filename can be anything you want, all though it is the general convention to use the package name itself for easier recognition. Installation # Open the Administration Control Panel and navigate to Configuration > Packages > Install Package , click on Upload Package and select the file com.example.test.tar from your disk. Follow the on-screen instructions until it has been successfully installed. Open a new browser tab and navigate to your newly created page. If WoltLab Suite is installed at https://example.com/wsc/ , then the URL should read https://example.com/wsc/index.php?test/ . Congratulations, you have just created your first package! Developer Tools # The developer tools provide an interface to synchronize the data of an installed package with a bare repository on the local disk. You can re-import most PIPs at any time and have the changes applied without crafting a manual update. This process simulates a regular package update with a single PIP only, and resets the cache after the import has been completed. Registering a Project # Projects require the absolute path to the package directory, that is, the directory where it can find the package.xml . It is not required to install an package to register it as a project, but you have to install it in order to work with it. It does not install the package by itself! There is a special button on the project list that allows for a mass-import of projects based on a search path. Each direct child directory of the provided path will be tested and projects created this way will use the identifier extracted from the package.xml . Synchronizing # The install instructions in the package.xml are ignored when offering the PIP imports, the detection works entirely based on the default filename for each PIP. On top of that, only PIPs that implement the interface wcf\\system\\devtools\\pip\\IIdempotentPackageInstallationPlugin are valid for import, as it indicates that importing the PIP multiple times will have no side-effects and that the result is deterministic regardless of the number of times it has been imported. Some built-in PIPs, such as sql or script , do not qualify for this step and remain unavailable at all times. However, you can still craft and perform an actual package update to have these PIPs executed. Appendix # Template Guessing # The class name including the namespace is used to automatically determine the path to the template and its name. The example above used the page class name wcf\\page\\TestPage that is then split into four distinct parts: wcf , the internal abbreviation of WoltLab Suite Core (previously known as WoltLab Community Framework) \\page\\ (ignored) Test , the actual name that is used for both the template and the URL Page (page type, ignored) The fragments 1. and 3. from above are used to construct the path to the template: <installDirOfWSC>/templates/test.tpl (the first letter of Test is being converted to lower-case).","title":"Getting Started"},{"location":"getting-started/#creating-a-simple-package","text":"","title":"Creating a simple package"},{"location":"getting-started/#setup-and-requirements","text":"This guide will help you to create a simple package that provides a simple test page. It is nothing too fancy, but you can use it as the foundation for your next project. There are some requirements you should met before starting: Text editor with syntax highlighting for PHP, Notepad++ is a solid pick *.php and *.tpl should be encoded with ANSI/ASCII *.xml are always encoded with UTF-8, but omit the BOM (byte-order-mark) Use tabs instead of spaces to indent lines It is recommended to set the tab width to 8 spaces, this is used in the entire software and will ease reading the source files An active installation of WoltLab Suite An application to create *.tar archives, e.g. 7-Zip on Windows","title":"Setup and Requirements"},{"location":"getting-started/#the-packagexml-file","text":"We want to create a simple page that will display the sentence \"Hello World\" embedded into the application frame. Create an empty directory in the workspace of your choice to start with. Create a new file called package.xml and insert the code below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/package.xsd\" name= \"com.example.test\" > <packageinformation> <!-- com.example.test --> <packagename> Simple Package </packagename> <packagedescription> A simple package to demonstrate the package system of WoltLab Suite Core </packagedescription> <version> 1.0.0 </version> <date> 2019-04-28 </date> </packageinformation> <authorinformation> <author> Your Name </author> <authorurl> http://www.example.com </authorurl> </authorinformation> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"template\" /> <instruction type= \"page\" /> </instructions> </package> There is an entire chapter on the package system that explains what the code above does and how you can adjust it to fit your needs. For now we'll keep it as it is.","title":"The package.xml File"},{"location":"getting-started/#the-php-class","text":"The next step is to create the PHP class which will serve our page: Create the directory files in the same directory where package.xml is located Open files and create the directory lib Open lib and create the directory page Within the directory page , please create the file TestPage.class.php Copy and paste the following code into the TestPage.class.php : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <? php namespace wcf\\page ; use wcf\\system\\WCF ; /** * A simple test page for demonstration purposes. * * @author YOUR NAME * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> */ class TestPage extends AbstractPage { /** * @var string */ protected $greet = '' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_GET [ 'greet' ])) $this -> greet = $_GET [ 'greet' ]; } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( empty ( $this -> greet )) { $this -> greet = 'World' ; } } /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'greet' => $this -> greet ]); } } The class inherits from wcf\\page\\AbstractPage , the default implementation of pages without form controls. It defines quite a few methods that will be automatically invoked in a specific order, for example readParameters() before readData() and finally assignVariables() to pass arbitrary values to the template. The property $greet is defined as World , but can optionally be populated through a GET variable ( index.php?test/&greet=You would output Hello You! ). This extra code illustrates the separation of data processing that takes place within all sort of pages, where all user-supplied data is read from within a single method. It helps organizing the code, but most of all it enforces a clean class logic that does not start reading user input at random places, including the risk to only escape the input of variable $_GET['foo'] 4 out of 5 times. Reading and processing the data is only half the story, now we need a template to display the actual content for our page. You don't need to specify it yourself, it will be automatically guessed based on your namespace and class name, you can read more about it later . Last but not least, you must not include the closing PHP tag ?> at the end, it can cause PHP to break on whitespaces and is not required at all.","title":"The PHP Class"},{"location":"getting-started/#the-template","text":"Navigate back to the root directory of your package until you see both the files directory and the package.xml . Now create a directory called templates , open it and create the file test.tpl . 1 2 3 4 5 6 7 { include file = 'header' } <div class=\"section\"> Hello { $greet } ! </div> { include file = 'footer' } Templates are a mixture of HTML and Smarty-like template scripting to overcome the static nature of raw HTML. The above code will display the phrase Hello World! in the application frame, just as any other page would render. The included templates header and footer are responsible for the majority of the overall page functionality, but offer a whole lot of customization abilities to influence their behavior and appearance.","title":"The Template"},{"location":"getting-started/#the-page-definition","text":"The package now contains the PHP class and the matching template, but it is still missing the page definition. Please create the file page.xml in your project's root directory, thus on the same level as the package.xml . 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/page.xsd\" > <import> <page identifier= \"com.example.test.Test\" > <controller> wcf\\page\\TestPage </controller> <name language= \"en\" > Test Page </name> <pageType> system </pageType> </page> </import> </data> You can provide a lot more data for a page, including logical nesting and dedicated handler classes for display in menus.","title":"The Page Definition"},{"location":"getting-started/#building-the-package","text":"If you have followed the above guidelines carefully, your package directory should now look like this: 1 2 3 4 5 6 7 8 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 TestPage.class.php \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u2514\u2500\u2500 templates \u2514\u2500\u2500 test.tpl Both files and templates are archive-based package components, that deploy their payload using tar archives rather than adding the raw files to the package file. Please create the archive files.tar and add the contents of the files/* directory, but not the directory files/ itself. Repeat the same process for the templates directory, but this time with the file name templates.tar . Place both files in the root of your project. Last but not least, create the package archive com.example.test.tar and add all the files listed below. files.tar package.xml page.xml templates.tar The archive's filename can be anything you want, all though it is the general convention to use the package name itself for easier recognition.","title":"Building the Package"},{"location":"getting-started/#installation","text":"Open the Administration Control Panel and navigate to Configuration > Packages > Install Package , click on Upload Package and select the file com.example.test.tar from your disk. Follow the on-screen instructions until it has been successfully installed. Open a new browser tab and navigate to your newly created page. If WoltLab Suite is installed at https://example.com/wsc/ , then the URL should read https://example.com/wsc/index.php?test/ . Congratulations, you have just created your first package!","title":"Installation"},{"location":"getting-started/#developer-tools","text":"The developer tools provide an interface to synchronize the data of an installed package with a bare repository on the local disk. You can re-import most PIPs at any time and have the changes applied without crafting a manual update. This process simulates a regular package update with a single PIP only, and resets the cache after the import has been completed.","title":"Developer Tools"},{"location":"getting-started/#registering-a-project","text":"Projects require the absolute path to the package directory, that is, the directory where it can find the package.xml . It is not required to install an package to register it as a project, but you have to install it in order to work with it. It does not install the package by itself! There is a special button on the project list that allows for a mass-import of projects based on a search path. Each direct child directory of the provided path will be tested and projects created this way will use the identifier extracted from the package.xml .","title":"Registering a Project"},{"location":"getting-started/#synchronizing","text":"The install instructions in the package.xml are ignored when offering the PIP imports, the detection works entirely based on the default filename for each PIP. On top of that, only PIPs that implement the interface wcf\\system\\devtools\\pip\\IIdempotentPackageInstallationPlugin are valid for import, as it indicates that importing the PIP multiple times will have no side-effects and that the result is deterministic regardless of the number of times it has been imported. Some built-in PIPs, such as sql or script , do not qualify for this step and remain unavailable at all times. However, you can still craft and perform an actual package update to have these PIPs executed.","title":"Synchronizing"},{"location":"getting-started/#appendix","text":"","title":"Appendix"},{"location":"getting-started/#template-guessing","text":"The class name including the namespace is used to automatically determine the path to the template and its name. The example above used the page class name wcf\\page\\TestPage that is then split into four distinct parts: wcf , the internal abbreviation of WoltLab Suite Core (previously known as WoltLab Community Framework) \\page\\ (ignored) Test , the actual name that is used for both the template and the URL Page (page type, ignored) The fragments 1. and 3. from above are used to construct the path to the template: <installDirOfWSC>/templates/test.tpl (the first letter of Test is being converted to lower-case).","title":"Template Guessing"},{"location":"javascript/code-snippets/","text":"Code Snippets - JavaScript API # This is a list of code snippets that do not fit into any of the other articles and merely describe how to achieve something very specific, rather than explaining the inner workings of a function. ImageViewer # The ImageViewer is available on all frontend pages by default, you can easily add images to the viewer by wrapping the thumbnails with a link with the CSS class jsImageViewer that points to the full version. 1 2 3 < a href = \"http://example.com/full.jpg\" class = \"jsImageViewer\" > < img src = \"http://example.com/thumbnail.jpg\" > </ a >","title":"Code Snippets"},{"location":"javascript/code-snippets/#code-snippets-javascript-api","text":"This is a list of code snippets that do not fit into any of the other articles and merely describe how to achieve something very specific, rather than explaining the inner workings of a function.","title":"Code Snippets - JavaScript API"},{"location":"javascript/code-snippets/#imageviewer","text":"The ImageViewer is available on all frontend pages by default, you can easily add images to the viewer by wrapping the thumbnails with a link with the CSS class jsImageViewer that points to the full version. 1 2 3 < a href = \"http://example.com/full.jpg\" class = \"jsImageViewer\" > < img src = \"http://example.com/thumbnail.jpg\" > </ a >","title":"ImageViewer"},{"location":"javascript/general-usage/","text":"General JavaScript Usage # WoltLab Suite 5.4 introduced support for TypeScript, migrating all existing modules to TypeScript. The JavaScript section of the documentation is not yet updated to account for the changes, possibly explaining concepts that cannot be applied as-is when writing TypeScript. You can learn about basic TypeScript use in WoltLab Suite, such as consuming WoltLab Suite\u2019s types in own packages, within in the TypeScript section . The History of the Legacy API # The WoltLab Suite 3.0 introduced a new API based on AMD-Modules with ES5-JavaScript that was designed with high performance and visible dependencies in mind. This was a fundamental change in comparison to the legacy API that was build many years before while jQuery was still a thing and we had to deal with ancient browsers such as Internet Explorer 9 that felt short in both CSS and JavaScript capabilities. Fast forward a few years, the old API is still around and most important, it is actively being used by some components that have not been rewritten yet. This has been done to preserve the backwards-compatibility and to avoid the significant amount of work that it requires to rewrite a component. The components invoked on page initialization have all been rewritten to use the modern API, but some deferred objects that are invoked later during the page runtime may still use the old API. However, the legacy API is deprecated and you should not rely on it for new components at all. It slowly but steadily gets replaced up until a point where its last bits are finally removed from the code base. Embedding JavaScript inside Templates # The <script> -tags are extracted and moved during template processing, eventually placing them at the very end of the body element while preserving their order of appearance. This behavior is controlled through the data-relocate=\"true\" attribute on the <script> which is mandatory for almost all scripts, mostly because their dependencies (such as jQuery) are moved to the bottom anyway. 1 2 3 4 5 6 7 8 9 10 11 12 13 < script data-relocate = \"true\" > $ ( function () { // Code that uses jQuery (Legacy API) }); </ script > <!-- or --> < script data-relocate = \"true\" > require ([ \"Some\" , \"Dependencies\" ], function ( Some , Dependencies ) { // Modern API }); </ script > Including External JavaScript Files # The AMD-Modules used in the new API are automatically recognized and lazy-loaded on demand, so unless you have a rather large and pre-compiled code-base, there is nothing else to worry about. Debug-Variants and Cache-Buster # Your JavaScript files may change over time and you would want the users' browsers to always load and use the latest version of your files. This can be achieved by appending the special LAST_UPDATE_TIME constant to your file path. It contains the unix timestamp of the last time any package was installed, updated or removed and thus avoid outdated caches by relying on a unique value, without invalidating the cache more often that it needs to be. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App.js?t={@LAST_UPDATE_TIME}\" ></ script > For small scripts you can simply serve the full, non-minified version to the user at all times, the differences in size and execution speed are insignificant and are very unlikely to offer any benefits. They might even yield a worse performance, because you'll have to include them statically in the template, even if the code is never called. However, if you're including a minified build in your app or plugin, you should include a switch to load the uncompressed version in the debug mode, while serving the minified and optimized file to the average visitor. You should use the ENABLE_DEBUG_MODE constant to decide which version should be loaded. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App{if !ENABLE_DEBUG_MODE}.min{/if}.js?t={@LAST_UPDATE_TIME}\" ></ script > The Accelerated Guest View (\"Tiny Builds\") # You can learn more on the Accelerated Guest View in the migration docs. The \u201cAccelerated Guest View\u201d aims to decrease page size and to improve responsiveness by enabling a read-only mode for visitors. If you are providing a separate compiled build for this mode, you'll need to include yet another switch to serve the right version to the visitor. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App{if !ENABLE_DEBUG_MODE}{if VISITOR_USE_TINY_BUILD}.tiny{/if}.min{/if}.js?t={@LAST_UPDATE_TIME}\" ></ script > The {js} Template Plugin # The {js} template plugin exists solely to provide a much easier and less error-prone method to include external JavaScript files. 1 {js application='app' file='App' hasTiny=true} The hasTiny attribute is optional, you can set it to false or just omit it entirely if you do not provide a tiny build for your file.","title":"General Usage"},{"location":"javascript/general-usage/#general-javascript-usage","text":"WoltLab Suite 5.4 introduced support for TypeScript, migrating all existing modules to TypeScript. The JavaScript section of the documentation is not yet updated to account for the changes, possibly explaining concepts that cannot be applied as-is when writing TypeScript. You can learn about basic TypeScript use in WoltLab Suite, such as consuming WoltLab Suite\u2019s types in own packages, within in the TypeScript section .","title":"General JavaScript Usage"},{"location":"javascript/general-usage/#the-history-of-the-legacy-api","text":"The WoltLab Suite 3.0 introduced a new API based on AMD-Modules with ES5-JavaScript that was designed with high performance and visible dependencies in mind. This was a fundamental change in comparison to the legacy API that was build many years before while jQuery was still a thing and we had to deal with ancient browsers such as Internet Explorer 9 that felt short in both CSS and JavaScript capabilities. Fast forward a few years, the old API is still around and most important, it is actively being used by some components that have not been rewritten yet. This has been done to preserve the backwards-compatibility and to avoid the significant amount of work that it requires to rewrite a component. The components invoked on page initialization have all been rewritten to use the modern API, but some deferred objects that are invoked later during the page runtime may still use the old API. However, the legacy API is deprecated and you should not rely on it for new components at all. It slowly but steadily gets replaced up until a point where its last bits are finally removed from the code base.","title":"The History of the Legacy API"},{"location":"javascript/general-usage/#embedding-javascript-inside-templates","text":"The <script> -tags are extracted and moved during template processing, eventually placing them at the very end of the body element while preserving their order of appearance. This behavior is controlled through the data-relocate=\"true\" attribute on the <script> which is mandatory for almost all scripts, mostly because their dependencies (such as jQuery) are moved to the bottom anyway. 1 2 3 4 5 6 7 8 9 10 11 12 13 < script data-relocate = \"true\" > $ ( function () { // Code that uses jQuery (Legacy API) }); </ script > <!-- or --> < script data-relocate = \"true\" > require ([ \"Some\" , \"Dependencies\" ], function ( Some , Dependencies ) { // Modern API }); </ script >","title":"Embedding JavaScript inside Templates"},{"location":"javascript/general-usage/#including-external-javascript-files","text":"The AMD-Modules used in the new API are automatically recognized and lazy-loaded on demand, so unless you have a rather large and pre-compiled code-base, there is nothing else to worry about.","title":"Including External JavaScript Files"},{"location":"javascript/general-usage/#debug-variants-and-cache-buster","text":"Your JavaScript files may change over time and you would want the users' browsers to always load and use the latest version of your files. This can be achieved by appending the special LAST_UPDATE_TIME constant to your file path. It contains the unix timestamp of the last time any package was installed, updated or removed and thus avoid outdated caches by relying on a unique value, without invalidating the cache more often that it needs to be. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App.js?t={@LAST_UPDATE_TIME}\" ></ script > For small scripts you can simply serve the full, non-minified version to the user at all times, the differences in size and execution speed are insignificant and are very unlikely to offer any benefits. They might even yield a worse performance, because you'll have to include them statically in the template, even if the code is never called. However, if you're including a minified build in your app or plugin, you should include a switch to load the uncompressed version in the debug mode, while serving the minified and optimized file to the average visitor. You should use the ENABLE_DEBUG_MODE constant to decide which version should be loaded. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App{if !ENABLE_DEBUG_MODE}.min{/if}.js?t={@LAST_UPDATE_TIME}\" ></ script >","title":"Debug-Variants and Cache-Buster"},{"location":"javascript/general-usage/#the-accelerated-guest-view-tiny-builds","text":"You can learn more on the Accelerated Guest View in the migration docs. The \u201cAccelerated Guest View\u201d aims to decrease page size and to improve responsiveness by enabling a read-only mode for visitors. If you are providing a separate compiled build for this mode, you'll need to include yet another switch to serve the right version to the visitor. 1 < script data-relocate = \"true\" src = \"{@$__wcf->getPath('app')}js/App{if !ENABLE_DEBUG_MODE}{if VISITOR_USE_TINY_BUILD}.tiny{/if}.min{/if}.js?t={@LAST_UPDATE_TIME}\" ></ script >","title":"The Accelerated Guest View (\"Tiny Builds\")"},{"location":"javascript/general-usage/#the-js-template-plugin","text":"The {js} template plugin exists solely to provide a much easier and less error-prone method to include external JavaScript files. 1 {js application='app' file='App' hasTiny=true} The hasTiny attribute is optional, you can set it to false or just omit it entirely if you do not provide a tiny build for your file.","title":"The {js} Template Plugin"},{"location":"javascript/helper-functions/","text":"JavaScript Helper Functions # These helper functions are deprecated since version 5.4. Refer to our migration guide on how to replace them. Introduction # Since version 3.0, WoltLab Suite ships with a set of global helper functions that are exposed on the window -object and thus are available regardless of the context. They are meant to reduce code repetition and to increase readability by moving potentially relevant parts to the front of an instruction. Elements # elCreate(tagName: string): Element # Creates a new element with the provided tag name. 1 2 3 var element = elCreate ( \"div\" ); // equals var element = document . createElement ( \"div\" ); elRemove(element: Element) # Removes an element from its parent without returning it. This function will throw an error if the element doesn't have a parent node. 1 2 3 elRemove ( element ); // equals element . parentNode . removeChild ( element ); elShow(element: Element) # Attempts to show an element by removing the display CSS-property, usually used in conjunction with the elHide() function. 1 2 3 elShow ( element ); // equals element . style . removeProperty ( \"display\" ); elHide(element: Element) # Attempts to hide an element by setting the display CSS-property to none , this is intended to be used with elShow() that relies on this behavior. 1 2 3 elHide ( element ); // equals element . style . setProperty ( \"display\" , \"none\" , \"\" ); elToggle(element: Element) # Attempts to toggle the visibility of an element by examining the value of the display CSS-property and calls either elShow() or elHide() . Attributes # elAttr(element: Element, attribute: string, value?: string): string # Sets or reads an attribute value, value are implicitly casted into strings and reading non-existing attributes will always yield an empty string. If you want to test for attribute existence, you'll have to fall-back to the native Element.hasAttribute() method. You should read and set native attributes directly, such as img.src rather than img.getAttribute(\"src\"); . 1 2 3 4 5 6 7 var value = elAttr ( element , \"some-attribute\" ); // equals var value = element . getAttribute ( \"some-attribute\" ); elAttr ( element , \"some-attribute\" , \"some value\" ); // equals element . setAttribute ( \"some-attribute\" , \"some value\" ); elAttrBool(element: Element, attribute: string): boolean # Reads an attribute and converts it value into a boolean value, the strings \"1\" and \"true\" will evaluate to true . All other values, including a missing attribute, will return false . 1 2 3 if ( elAttrBool ( element , \"some-attribute\" )) { // attribute is true-ish } elData(element: Element, attribute: string, value?: string): string # Short-hand function to read or set HTML5 data-* -attributes, it essentially prepends the data- prefix before forwarding the call to elAttr() . 1 2 3 4 5 6 7 var value = elData ( element , \"some-attribute\" ); // equals var value = elAttr ( element , \"data-some-attribute\" ); elData ( element , \"some-attribute\" , \"some value\" ); // equals elAttr ( element , \"data-some-attribute\" , \"some value\" ); elDataBool(element: Element, attribute: string): boolean # Short-hand function to convert a HTML5 data-* -attribute into a boolean value. It prepends the data- prefix before forwarding the call to elAttrBool() . 1 2 3 4 5 6 7 if ( elDataBool ( element , \"some-attribute\" )) { // attribute is true-ish } // equals if ( elAttrBool ( element , \"data-some-attribute\" )) { // attribute is true-ish } Selecting Elements # Unlike libraries like jQuery, these functions will return null if an element is not found. You are responsible to validate if the element exist and to branch accordingly, invoking methods on the return value without checking for null will yield an error. elById(id: string): Element | null # Selects an element by its id -attribute value. 1 2 3 var element = elById ( \"my-awesome-element\" ); // equals var element = document . getElementById ( \"my-awesome-element\" ); elBySel(selector: string, context?: Element): Element | null # The underlying querySelector() -method works on the entire DOM hierarchy and can yield results outside of your context element! Please read and understand the MDN article on Element.querySelector() to learn more about this. Select a single element based on a CSS selector, optionally limiting the results to be a direct or indirect children of the context element. 1 2 3 4 5 6 7 8 var element = elBySel ( \".some-element\" ); // equals var element = document . querySelector ( \".some-element\" ); // limiting the scope to a context element: var element = elBySel ( \".some-element\" , context ); // equals var element = context . querySelector ( \".some-element\" ); elBySelAll(selector: string, context?: Element, callback: (element: Element) => void): NodeList # The underlying querySelector() -method works on the entire DOM hierarchy and can yield results outside of your context element! Please read and understand the MDN article on Element.querySelector() to learn more about this. Finds and returns a NodeList containing all elements that match the provided CSS selector. Although NodeList is an array-like structure, it is not possible to iterate over it using array functions, including .forEach() which is not available in Internet Explorer 11. 1 2 3 4 5 6 7 8 var elements = elBySelAll ( \".some-element\" ); // equals var elements = document . querySelectorAll ( \".some-element\" ); // limiting the scope to a context element: var elements = elBySelAll ( \".some-element\" , context ); // equals var elements = context . querySelectorAll ( \".some-element\" ); Callback to Iterate Over Elements # elBySelAll() supports an optional third parameter that expects a callback function that is invoked for every element in the list. 1 2 3 4 5 6 7 8 9 // set the 2nd parameter to `undefined` or `null` to query the whole document elBySelAll ( \".some-element\" , undefined , function ( element ) { // is called for each element }); // limiting the scope to a context element: elBySelAll ( \".some-element\" , context , function ( element ) { // is called for each element }); elClosest(element: Element, selector: string): Element | null # Returns the first Element that matches the provided CSS selector, this will return the provided element itself if it matches the selector. 1 2 3 var element = elClosest ( context , \".some-element\" ); // equals var element = context . closest ( \".some-element\" ); Text Nodes # If the provided context is a Text -node, the function will move the context to the parent element before applying the CSS selector. If the Text has no parent, null is returned without evaluating the selector. elByClass(className: string, context?: Element): NodeList # Returns a live NodeList containing all elements that match the provided CSS class now and in the future! The collection is automatically updated whenever an element with that class is added or removed from the DOM, it will also include elements that get dynamically assigned or removed this CSS class. You absolutely need to understand that this collection is dynamic, that means that elements can and will be added and removed from the collection even while you iterate over it. There are only very few cases where you would need such a collection, almost always elBySelAll() is what you're looking for. 1 2 3 4 5 6 7 8 9 // no leading dot! var elements = elByClass ( \"some-element\" ); // equals var elements = document . getElementsByClassName ( \"some-element\" ); // limiting the scope to a context element: var elements = elByClass ( \"some-element\" , context ); // equals var elements = context . getElementsByClassName ( \".some-element\" ); elByTag(tagName: string, context?: Element): NodeList # Returns a live NodeList containing all elements with the provided tag name now and in the future! Please read the remarks on elByClass() above to understand the implications of this. 1 2 3 4 5 6 7 8 var elements = elByTag ( \"div\" ); // equals var elements = document . getElementsByTagName ( \"div\" ); // limiting the scope to a context element: var elements = elByTag ( \"div\" , context ); // equals var elements = context . getElementsByTagName ( \"div\" ); Utility Functions # elInnerError(element: Element, errorMessage?: string, isHtml?: boolean): Element | null # Unified function to display and remove inline error messages for input elements, please read the section in the migration docs to learn more about this function. String Extensions # hashCode(): string # Computes a numeric hash value of a string similar to Java's String.hashCode() method. 1 2 console . log ( \"Hello World\" . hashCode ()); // outputs: -862545276","title":"Helper Functions"},{"location":"javascript/helper-functions/#javascript-helper-functions","text":"These helper functions are deprecated since version 5.4. Refer to our migration guide on how to replace them.","title":"JavaScript Helper Functions"},{"location":"javascript/helper-functions/#introduction","text":"Since version 3.0, WoltLab Suite ships with a set of global helper functions that are exposed on the window -object and thus are available regardless of the context. They are meant to reduce code repetition and to increase readability by moving potentially relevant parts to the front of an instruction.","title":"Introduction"},{"location":"javascript/helper-functions/#elements","text":"","title":"Elements"},{"location":"javascript/helper-functions/#elcreatetagname-string-element","text":"Creates a new element with the provided tag name. 1 2 3 var element = elCreate ( \"div\" ); // equals var element = document . createElement ( \"div\" );","title":"elCreate(tagName: string): Element"},{"location":"javascript/helper-functions/#elremoveelement-element","text":"Removes an element from its parent without returning it. This function will throw an error if the element doesn't have a parent node. 1 2 3 elRemove ( element ); // equals element . parentNode . removeChild ( element );","title":"elRemove(element: Element)"},{"location":"javascript/helper-functions/#elshowelement-element","text":"Attempts to show an element by removing the display CSS-property, usually used in conjunction with the elHide() function. 1 2 3 elShow ( element ); // equals element . style . removeProperty ( \"display\" );","title":"elShow(element: Element)"},{"location":"javascript/helper-functions/#elhideelement-element","text":"Attempts to hide an element by setting the display CSS-property to none , this is intended to be used with elShow() that relies on this behavior. 1 2 3 elHide ( element ); // equals element . style . setProperty ( \"display\" , \"none\" , \"\" );","title":"elHide(element: Element)"},{"location":"javascript/helper-functions/#eltoggleelement-element","text":"Attempts to toggle the visibility of an element by examining the value of the display CSS-property and calls either elShow() or elHide() .","title":"elToggle(element: Element)"},{"location":"javascript/helper-functions/#attributes","text":"","title":"Attributes"},{"location":"javascript/helper-functions/#elattrelement-element-attribute-string-value-string-string","text":"Sets or reads an attribute value, value are implicitly casted into strings and reading non-existing attributes will always yield an empty string. If you want to test for attribute existence, you'll have to fall-back to the native Element.hasAttribute() method. You should read and set native attributes directly, such as img.src rather than img.getAttribute(\"src\"); . 1 2 3 4 5 6 7 var value = elAttr ( element , \"some-attribute\" ); // equals var value = element . getAttribute ( \"some-attribute\" ); elAttr ( element , \"some-attribute\" , \"some value\" ); // equals element . setAttribute ( \"some-attribute\" , \"some value\" );","title":"elAttr(element: Element, attribute: string, value?: string): string"},{"location":"javascript/helper-functions/#elattrboolelement-element-attribute-string-boolean","text":"Reads an attribute and converts it value into a boolean value, the strings \"1\" and \"true\" will evaluate to true . All other values, including a missing attribute, will return false . 1 2 3 if ( elAttrBool ( element , \"some-attribute\" )) { // attribute is true-ish }","title":"elAttrBool(element: Element, attribute: string): boolean"},{"location":"javascript/helper-functions/#eldataelement-element-attribute-string-value-string-string","text":"Short-hand function to read or set HTML5 data-* -attributes, it essentially prepends the data- prefix before forwarding the call to elAttr() . 1 2 3 4 5 6 7 var value = elData ( element , \"some-attribute\" ); // equals var value = elAttr ( element , \"data-some-attribute\" ); elData ( element , \"some-attribute\" , \"some value\" ); // equals elAttr ( element , \"data-some-attribute\" , \"some value\" );","title":"elData(element: Element, attribute: string, value?: string): string"},{"location":"javascript/helper-functions/#eldataboolelement-element-attribute-string-boolean","text":"Short-hand function to convert a HTML5 data-* -attribute into a boolean value. It prepends the data- prefix before forwarding the call to elAttrBool() . 1 2 3 4 5 6 7 if ( elDataBool ( element , \"some-attribute\" )) { // attribute is true-ish } // equals if ( elAttrBool ( element , \"data-some-attribute\" )) { // attribute is true-ish }","title":"elDataBool(element: Element, attribute: string): boolean"},{"location":"javascript/helper-functions/#selecting-elements","text":"Unlike libraries like jQuery, these functions will return null if an element is not found. You are responsible to validate if the element exist and to branch accordingly, invoking methods on the return value without checking for null will yield an error.","title":"Selecting Elements"},{"location":"javascript/helper-functions/#elbyidid-string-element-null","text":"Selects an element by its id -attribute value. 1 2 3 var element = elById ( \"my-awesome-element\" ); // equals var element = document . getElementById ( \"my-awesome-element\" );","title":"elById(id: string): Element | null"},{"location":"javascript/helper-functions/#elbyselselector-string-context-element-element-null","text":"The underlying querySelector() -method works on the entire DOM hierarchy and can yield results outside of your context element! Please read and understand the MDN article on Element.querySelector() to learn more about this. Select a single element based on a CSS selector, optionally limiting the results to be a direct or indirect children of the context element. 1 2 3 4 5 6 7 8 var element = elBySel ( \".some-element\" ); // equals var element = document . querySelector ( \".some-element\" ); // limiting the scope to a context element: var element = elBySel ( \".some-element\" , context ); // equals var element = context . querySelector ( \".some-element\" );","title":"elBySel(selector: string, context?: Element): Element | null"},{"location":"javascript/helper-functions/#elbyselallselector-string-context-element-callback-element-element-void-nodelist","text":"The underlying querySelector() -method works on the entire DOM hierarchy and can yield results outside of your context element! Please read and understand the MDN article on Element.querySelector() to learn more about this. Finds and returns a NodeList containing all elements that match the provided CSS selector. Although NodeList is an array-like structure, it is not possible to iterate over it using array functions, including .forEach() which is not available in Internet Explorer 11. 1 2 3 4 5 6 7 8 var elements = elBySelAll ( \".some-element\" ); // equals var elements = document . querySelectorAll ( \".some-element\" ); // limiting the scope to a context element: var elements = elBySelAll ( \".some-element\" , context ); // equals var elements = context . querySelectorAll ( \".some-element\" );","title":"elBySelAll(selector: string, context?: Element, callback: (element: Element) => void): NodeList"},{"location":"javascript/helper-functions/#callback-to-iterate-over-elements","text":"elBySelAll() supports an optional third parameter that expects a callback function that is invoked for every element in the list. 1 2 3 4 5 6 7 8 9 // set the 2nd parameter to `undefined` or `null` to query the whole document elBySelAll ( \".some-element\" , undefined , function ( element ) { // is called for each element }); // limiting the scope to a context element: elBySelAll ( \".some-element\" , context , function ( element ) { // is called for each element });","title":"Callback to Iterate Over Elements"},{"location":"javascript/helper-functions/#elclosestelement-element-selector-string-element-null","text":"Returns the first Element that matches the provided CSS selector, this will return the provided element itself if it matches the selector. 1 2 3 var element = elClosest ( context , \".some-element\" ); // equals var element = context . closest ( \".some-element\" );","title":"elClosest(element: Element, selector: string): Element | null"},{"location":"javascript/helper-functions/#text-nodes","text":"If the provided context is a Text -node, the function will move the context to the parent element before applying the CSS selector. If the Text has no parent, null is returned without evaluating the selector.","title":"Text Nodes"},{"location":"javascript/helper-functions/#elbyclassclassname-string-context-element-nodelist","text":"Returns a live NodeList containing all elements that match the provided CSS class now and in the future! The collection is automatically updated whenever an element with that class is added or removed from the DOM, it will also include elements that get dynamically assigned or removed this CSS class. You absolutely need to understand that this collection is dynamic, that means that elements can and will be added and removed from the collection even while you iterate over it. There are only very few cases where you would need such a collection, almost always elBySelAll() is what you're looking for. 1 2 3 4 5 6 7 8 9 // no leading dot! var elements = elByClass ( \"some-element\" ); // equals var elements = document . getElementsByClassName ( \"some-element\" ); // limiting the scope to a context element: var elements = elByClass ( \"some-element\" , context ); // equals var elements = context . getElementsByClassName ( \".some-element\" );","title":"elByClass(className: string, context?: Element): NodeList"},{"location":"javascript/helper-functions/#elbytagtagname-string-context-element-nodelist","text":"Returns a live NodeList containing all elements with the provided tag name now and in the future! Please read the remarks on elByClass() above to understand the implications of this. 1 2 3 4 5 6 7 8 var elements = elByTag ( \"div\" ); // equals var elements = document . getElementsByTagName ( \"div\" ); // limiting the scope to a context element: var elements = elByTag ( \"div\" , context ); // equals var elements = context . getElementsByTagName ( \"div\" );","title":"elByTag(tagName: string, context?: Element): NodeList"},{"location":"javascript/helper-functions/#utility-functions","text":"","title":"Utility Functions"},{"location":"javascript/helper-functions/#elinnererrorelement-element-errormessage-string-ishtml-boolean-element-null","text":"Unified function to display and remove inline error messages for input elements, please read the section in the migration docs to learn more about this function.","title":"elInnerError(element: Element, errorMessage?: string, isHtml?: boolean): Element | null"},{"location":"javascript/helper-functions/#string-extensions","text":"","title":"String Extensions"},{"location":"javascript/helper-functions/#hashcode-string","text":"Computes a numeric hash value of a string similar to Java's String.hashCode() method. 1 2 console . log ( \"Hello World\" . hashCode ()); // outputs: -862545276","title":"hashCode(): string"},{"location":"javascript/legacy-api/","text":"Legacy JavaScript API # Introduction # The legacy JavaScript API is the original code that was part of the 2.x series of WoltLab Suite, formerly known as WoltLab Community Framework. It has been superseded for the most part by the ES5/AMD-modules API introduced with WoltLab Suite 3.0. Some parts still exist to this day for backwards-compatibility and because some less important components have not been rewritten yet. The old API is still supported, but marked as deprecated and will continue to be replaced parts by part in future releases, up until their entire removal, including jQuery support. This guide does not provide any explanation on the usage of those legacy components, but instead serves as a cheat sheet to convert code to use the new API. Classes # Singletons # Singleton instances are designed to provide a unique \"instance\" of an object regardless of when its first instance was created. Due to the lack of a class construct in ES5, they are represented by mere objects that act as an instance. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // App.js window . App = {}; App . Foo = { bar : function () {} }; // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; return { bar : function () {} }; }); Regular Classes # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); Inheritance # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); App . Baz = App . Foo . extend ({ makeSnafucated : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); // App/Baz.js define ([ \"Core\" , \"./Foo\" ], function ( Core , Foo ) { \"use strict\" ; function Baz () {}; Core . inherit ( Baz , Foo , { makeSnafucated : function () {} }); return Baz ; }); Ajax Requests # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // App.js App . Foo = Class . extend ({ _proxy : null , init : function () { this . _proxy = new WCF . Action . Proxy ({ success : $ . proxy ( this . _success , this ) }); }, bar : function () { this . _proxy . setOption ( \"data\" , { actionName : \"baz\" , className : \"app\\\\foo\\\\FooAction\" , objectIDs : [ 1 , 2 , 3 ], parameters : { foo : \"bar\" , baz : true } }); this . _proxy . sendRequest (); }, _success : function ( data ) { // ajax request result } }); // --- NEW API --- // App/Foo.js define ([ \"Ajax\" ], function ( Ajax ) { \"use strict\" ; function Foo () {} Foo . prototype = { bar : function () { Ajax . api ( this , { objectIDs : [ 1 , 2 , 3 ], parameters : { foo : \"bar\" , baz : true } }); }, // magic method! _ajaxSuccess : function ( data ) { // ajax request result }, // magic method! _ajaxSetup : function () { return { actionName : \"baz\" , className : \"app\\\\foo\\\\FooAction\" } } } return Foo ; }); Phrases # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < script data-relocate = \"true\" > $ ( function () { WCF . Language . addObject ({ 'app.foo.bar' : '{lang}app.foo.bar{/lang}' }); console . log ( WCF . Language . get ( \"app.foo.bar\" )); }); </ script > <!-- NEW API --> < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . addObject ({ 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' }); console . log ( Language . get ( \"app.foo.bar\" )); }); </ script > Event-Listener # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < script data-relocate = \"true\" > $ ( function () { WCF . System . Event . addListener ( \"app.foo.bar\" , \"makeSnafucated\" , function ( data ) { console . log ( \"Event was invoked.\" ); }); WCF . System . Event . fireEvent ( \"app.foo.bar\" , \"makeSnafucated\" , { some : \"data\" }); }); </ script > <!-- NEW API --> < script data-relocate = \"true\" > require ([ \"EventHandler\" ], function ( EventHandler ) { EventHandler . add ( \"app.foo.bar\" , \"makeSnafucated\" , function ( data ) { console . log ( \"Event was invoked\" ); }); EventHandler . fire ( \"app.foo.bar\" , \"makeSnafucated\" , { some : \"data\" }); }); </ script >","title":"Legacy API"},{"location":"javascript/legacy-api/#legacy-javascript-api","text":"","title":"Legacy JavaScript API"},{"location":"javascript/legacy-api/#introduction","text":"The legacy JavaScript API is the original code that was part of the 2.x series of WoltLab Suite, formerly known as WoltLab Community Framework. It has been superseded for the most part by the ES5/AMD-modules API introduced with WoltLab Suite 3.0. Some parts still exist to this day for backwards-compatibility and because some less important components have not been rewritten yet. The old API is still supported, but marked as deprecated and will continue to be replaced parts by part in future releases, up until their entire removal, including jQuery support. This guide does not provide any explanation on the usage of those legacy components, but instead serves as a cheat sheet to convert code to use the new API.","title":"Introduction"},{"location":"javascript/legacy-api/#classes","text":"","title":"Classes"},{"location":"javascript/legacy-api/#singletons","text":"Singleton instances are designed to provide a unique \"instance\" of an object regardless of when its first instance was created. Due to the lack of a class construct in ES5, they are represented by mere objects that act as an instance. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // App.js window . App = {}; App . Foo = { bar : function () {} }; // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; return { bar : function () {} }; });","title":"Singletons"},{"location":"javascript/legacy-api/#regular-classes","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; });","title":"Regular Classes"},{"location":"javascript/legacy-api/#inheritance","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); App . Baz = App . Foo . extend ({ makeSnafucated : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); // App/Baz.js define ([ \"Core\" , \"./Foo\" ], function ( Core , Foo ) { \"use strict\" ; function Baz () {}; Core . inherit ( Baz , Foo , { makeSnafucated : function () {} }); return Baz ; });","title":"Inheritance"},{"location":"javascript/legacy-api/#ajax-requests","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // App.js App . Foo = Class . extend ({ _proxy : null , init : function () { this . _proxy = new WCF . Action . Proxy ({ success : $ . proxy ( this . _success , this ) }); }, bar : function () { this . _proxy . setOption ( \"data\" , { actionName : \"baz\" , className : \"app\\\\foo\\\\FooAction\" , objectIDs : [ 1 , 2 , 3 ], parameters : { foo : \"bar\" , baz : true } }); this . _proxy . sendRequest (); }, _success : function ( data ) { // ajax request result } }); // --- NEW API --- // App/Foo.js define ([ \"Ajax\" ], function ( Ajax ) { \"use strict\" ; function Foo () {} Foo . prototype = { bar : function () { Ajax . api ( this , { objectIDs : [ 1 , 2 , 3 ], parameters : { foo : \"bar\" , baz : true } }); }, // magic method! _ajaxSuccess : function ( data ) { // ajax request result }, // magic method! _ajaxSetup : function () { return { actionName : \"baz\" , className : \"app\\\\foo\\\\FooAction\" } } } return Foo ; });","title":"Ajax Requests"},{"location":"javascript/legacy-api/#phrases","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < script data-relocate = \"true\" > $ ( function () { WCF . Language . addObject ({ 'app.foo.bar' : '{lang}app.foo.bar{/lang}' }); console . log ( WCF . Language . get ( \"app.foo.bar\" )); }); </ script > <!-- NEW API --> < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . addObject ({ 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' }); console . log ( Language . get ( \"app.foo.bar\" )); }); </ script >","title":"Phrases"},{"location":"javascript/legacy-api/#event-listener","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < script data-relocate = \"true\" > $ ( function () { WCF . System . Event . addListener ( \"app.foo.bar\" , \"makeSnafucated\" , function ( data ) { console . log ( \"Event was invoked.\" ); }); WCF . System . Event . fireEvent ( \"app.foo.bar\" , \"makeSnafucated\" , { some : \"data\" }); }); </ script > <!-- NEW API --> < script data-relocate = \"true\" > require ([ \"EventHandler\" ], function ( EventHandler ) { EventHandler . add ( \"app.foo.bar\" , \"makeSnafucated\" , function ( data ) { console . log ( \"Event was invoked\" ); }); EventHandler . fire ( \"app.foo.bar\" , \"makeSnafucated\" , { some : \"data\" }); }); </ script >","title":"Event-Listener"},{"location":"javascript/new-api_ajax/","text":"Ajax Requests - JavaScript API # Promise -based API for DatabaseObjectAction # WoltLab Suite 5.5 introduces a new API for Ajax requests that uses Promise s to control the code flow. It does not rely on references to existing objects and does not use arbitrary callbacks to handle the setup and handling of the request. Usage # MyModule.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import * as Ajax from \"./Ajax\" ; type ResponseGetLatestFoo = { template : string ; }; export class MyModule { private readonly bar : string ; private readonly objectId : number ; constructor ( objectId : number , bar : string , buttonId : string ) { this . bar = bar ; this . objectId = objectId ; const button = document . getElementById ( buttonId ); button ? . addEventListener ( \"click\" , ( event ) => void this . click ( event )); } async click ( event : MouseEvent ) : Promise < void > { event . preventDefault (); const button = event . currentTarget as HTMLElement ; if ( button . classList . contains ( \"disabled\" )) { return ; } button . classList . add ( \"disabled\" ); try { const response = ( await Ajax . dboAction ( \"getLatestFoo\" , \"wcf\\\\data\\\\foo\\\\FooAction\" ) . objectIds ([ this . objectId ]) . payload ({ bar : this.bar }) . dispatch ()) as ResponseGetLatestFoo ; document . getElementById ( \"latestFoo\" ) ! . innerHTML = response . template ; } finally { button . classList . remove ( \"disabled\" ); } } } export default MyModule ; The actual code to dispatch and evaluate a request is only four lines long and offers full IDE auto completion support. This example uses a finally block to reset the button class once the request has finished, regardless of the result. If you do not handle the errors (or chose not to handle some errors), the global rejection handler will take care of this and show an dialog that informs about the failed request. This mimics the behavior of the _ajaxFailure() callback in the legacy API. Aborting in-flight requests # Sometimes new requests are dispatched against the same API before the response from the previous has arrived. This applies to either long running requests or requests that are dispatched in rapid succession, for example, looking up values when the user is actively typing into a search field. RapidRequests.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import * as Ajax from \"./Ajax\" ; export class RapidRequests { private lastRequest : AbortController | undefined = undefined ; constructor ( inputId : string ) { const input = document . getElementById ( inputId ) as HTMLInputElement ; input . addEventListener ( \"input\" , ( event ) => void this . input ( event )); } async input ( event : Event ) : Promise < void > { event . preventDefault (); const input = event . currentTarget as HTMLInputElement ; const value = input . value . trim (); if ( this . lastRequest ) { this . lastRequest . abort (); } if ( value ) { const request = Ajax . dboAction ( \"getSuggestions\" , \"wcf\\\\data\\\\bar\\\\BarAction\" ). payload ({ value }); this . lastRequest = request . getAbortController (); const response = await request . dispatch (); // Handle the response } } } export default RapidRequests ; Ajax inside Modules (Legacy API) # The Ajax component was designed to be used from inside modules where an object reference is used to delegate request callbacks. This is acomplished through a set of magic methods that are automatically called when the request is created or its state has changed. _ajaxSetup() # The lazy initialization is performed upon the first invocation from the callee, using the magic _ajaxSetup() method to retrieve the basic configuration for this and any future requests. The data returned by _ajaxSetup() is cached and the data will be used to pre-populate the request data before sending it. The callee can overwrite any of these properties. It is intended to reduce the overhead when issuing request when these requests share the same properties, such as accessing the same endpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // App/Foo.js define ([ \"Ajax\" ], function ( Ajax ) { \"use strict\" ; function Foo () {}; Foo . prototype = { one : function () { // this will issue an ajax request with the parameter `value` set to `1` Ajax . api ( this ); }, two : function () { // this request is almost identical to the one issued with `.one()`, but // the value is now set to `2` for this invocation only. Ajax . api ( this , { parameters : { value : 2 } }); }, _ajaxSetup : function () { return { data : { actionName : \"makeSnafucated\" , className : \"app\\\\data\\\\foo\\\\FooAction\" , parameters : { value : 1 } } } } }; return Foo ; }); Request Settings # The object returned by the aforementioned _ajaxSetup() callback can contain these values: data # Defaults to {} . A plain JavaScript object that contains the request data that represents the form data of the request. The parameters key is recognized by the PHP Ajax API and becomes accessible through $this->parameters . contentType # Defaults to application/x-www-form-urlencoded; charset=UTF-8 . The request content type, sets the Content-Type HTTP header if it is not empty. responseType # Defaults to application/json . The server must respond with the Content-Type HTTP header set to this value, otherwise the request will be treated as failed. Requests for application/json will have the return body attempted to be evaluated as JSON. Other content types will only be validated based on the HTTP header, but no additional transformation is performed. For example, setting the responseType to application/xml will check the HTTP header, but will not transform the data parameter, you'll still receive a string in _ajaxSuccess ! type # Defaults to POST . The HTTP Verb used for this request. url # Defaults to an empty string. Manual override for the request endpoint, it will be automatically set to the Core API endpoint if left empty. If the Core API endpoint is used, the options includeRequestedWith and withCredentials will be force-set to true. withCredentials # Enabling this parameter for any domain other than the current will trigger a CORS preflight request. Defaults to false . Include cookies with this requested, is always true when url is (implicitly) set to the Core API endpoint. autoAbort # Defaults to false . When set to true , any pending responses to earlier requests will be silently discarded when issuing a new request. This only makes sense if the new request is meant to completely replace the result of the previous one, regardless of its reponse body. Typical use-cases include input field with suggestions, where possible values are requested from the server, but the input changed faster than the server was able to reply. In this particular case the client is not interested in the result for an earlier value, auto-aborting these requests avoids implementing this logic in the requesting code. ignoreError # Defaults to false . Any failing request will invoke the failure -callback to check if an error message should be displayed. Enabling this option will suppress the general error overlay that reports a failed request. You can achieve the same result by returning false in the failure -callback. silent # Defaults to false . Enabling this option will suppress the loading indicator overlay for this request, other non-\"silent\" requests will still trigger the loading indicator. includeRequestedWith # Enabling this parameter for any domain other than the current will trigger a CORS preflight request. Defaults to true . Sets the custom HTTP header X-Requested-With: XMLHttpRequest for the request, it is automatically set to true when url is pointing at the WSC API endpoint. failure # Defaults to null . Optional callback function that will be invoked for requests that have failed for one of these reasons: 1. The request timed out. 2. The HTTP status is not 2xx or 304 . 3. A responseType was set, but the response HTTP header Content-Type did not match the expected value. 4. The responseType was set to application/json , but the response body was not valid JSON. The callback function receives the parameter xhr (the XMLHttpRequest object) and options (deep clone of the request parameters). If the callback returns false , the general error overlay for failed requests will be suppressed. There will be no error overlay if ignoreError is set to true or if the request failed while attempting to evaluate the response body as JSON. finalize # Defaults to null . Optional callback function that will be invoked once the request has completed, regardless if it succeeded or failed. The only parameter it receives is options (the request parameters object), but it does not receive the request's XMLHttpRequest . success # Defaults to null . This semi-optional callback function will always be set to _ajaxSuccess() when invoking Ajax.api() . It receives four parameters: 1. data - The request's response body as a string, or a JavaScript object if contentType was set to application/json . 2. responseText - The unmodified response body, it equals the value for data for non-JSON requests. 3. xhr - The underlying XMLHttpRequest object. 4. requestData - The request parameters that were supplied when the request was issued. _ajaxSuccess() # This callback method is automatically called for successful AJAX requests, it receives four parameters, with the first one containing either the response body as a string, or a JavaScript object for JSON requests. _ajaxFailure() # Optional callback function that is invoked for failed requests, it will be automatically called if the callee implements it, otherwise the global error handler will be executed. Single Requests Without a Module (Legacy API) # The Ajax.api() method expects an object that is used to extract the request configuration as well as providing the callback functions when the request state changes. You can issue a simple Ajax request without object binding through Ajax.apiOnce() that will destroy the instance after the request was finalized. This method is significantly more expensive for repeated requests and does not offer deriving modules from altering the behavior. It is strongly recommended to always use Ajax.api() for requests to the WSC API endpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 < script data-relocate = \"true\" > require ([ \"Ajax\" ], function ( Ajax ) { Ajax . apiOnce ({ data : { actionName : \"makeSnafucated\" , className : \"app\\\\data\\\\foo\\\\FooAction\" , parameters : { value : 3 } }, success : function ( data ) { elBySel ( \".some-element\" ). textContent = data . bar ; } }) }); </ script >","title":"Ajax"},{"location":"javascript/new-api_ajax/#ajax-requests-javascript-api","text":"","title":"Ajax Requests - JavaScript API"},{"location":"javascript/new-api_ajax/#promise-based-api-for-databaseobjectaction","text":"WoltLab Suite 5.5 introduces a new API for Ajax requests that uses Promise s to control the code flow. It does not rely on references to existing objects and does not use arbitrary callbacks to handle the setup and handling of the request.","title":"Promise-based API for DatabaseObjectAction"},{"location":"javascript/new-api_ajax/#usage","text":"MyModule.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import * as Ajax from \"./Ajax\" ; type ResponseGetLatestFoo = { template : string ; }; export class MyModule { private readonly bar : string ; private readonly objectId : number ; constructor ( objectId : number , bar : string , buttonId : string ) { this . bar = bar ; this . objectId = objectId ; const button = document . getElementById ( buttonId ); button ? . addEventListener ( \"click\" , ( event ) => void this . click ( event )); } async click ( event : MouseEvent ) : Promise < void > { event . preventDefault (); const button = event . currentTarget as HTMLElement ; if ( button . classList . contains ( \"disabled\" )) { return ; } button . classList . add ( \"disabled\" ); try { const response = ( await Ajax . dboAction ( \"getLatestFoo\" , \"wcf\\\\data\\\\foo\\\\FooAction\" ) . objectIds ([ this . objectId ]) . payload ({ bar : this.bar }) . dispatch ()) as ResponseGetLatestFoo ; document . getElementById ( \"latestFoo\" ) ! . innerHTML = response . template ; } finally { button . classList . remove ( \"disabled\" ); } } } export default MyModule ; The actual code to dispatch and evaluate a request is only four lines long and offers full IDE auto completion support. This example uses a finally block to reset the button class once the request has finished, regardless of the result. If you do not handle the errors (or chose not to handle some errors), the global rejection handler will take care of this and show an dialog that informs about the failed request. This mimics the behavior of the _ajaxFailure() callback in the legacy API.","title":"Usage"},{"location":"javascript/new-api_ajax/#aborting-in-flight-requests","text":"Sometimes new requests are dispatched against the same API before the response from the previous has arrived. This applies to either long running requests or requests that are dispatched in rapid succession, for example, looking up values when the user is actively typing into a search field. RapidRequests.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import * as Ajax from \"./Ajax\" ; export class RapidRequests { private lastRequest : AbortController | undefined = undefined ; constructor ( inputId : string ) { const input = document . getElementById ( inputId ) as HTMLInputElement ; input . addEventListener ( \"input\" , ( event ) => void this . input ( event )); } async input ( event : Event ) : Promise < void > { event . preventDefault (); const input = event . currentTarget as HTMLInputElement ; const value = input . value . trim (); if ( this . lastRequest ) { this . lastRequest . abort (); } if ( value ) { const request = Ajax . dboAction ( \"getSuggestions\" , \"wcf\\\\data\\\\bar\\\\BarAction\" ). payload ({ value }); this . lastRequest = request . getAbortController (); const response = await request . dispatch (); // Handle the response } } } export default RapidRequests ;","title":"Aborting in-flight requests"},{"location":"javascript/new-api_ajax/#ajax-inside-modules-legacy-api","text":"The Ajax component was designed to be used from inside modules where an object reference is used to delegate request callbacks. This is acomplished through a set of magic methods that are automatically called when the request is created or its state has changed.","title":"Ajax inside Modules (Legacy API)"},{"location":"javascript/new-api_ajax/#_ajaxsetup","text":"The lazy initialization is performed upon the first invocation from the callee, using the magic _ajaxSetup() method to retrieve the basic configuration for this and any future requests. The data returned by _ajaxSetup() is cached and the data will be used to pre-populate the request data before sending it. The callee can overwrite any of these properties. It is intended to reduce the overhead when issuing request when these requests share the same properties, such as accessing the same endpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // App/Foo.js define ([ \"Ajax\" ], function ( Ajax ) { \"use strict\" ; function Foo () {}; Foo . prototype = { one : function () { // this will issue an ajax request with the parameter `value` set to `1` Ajax . api ( this ); }, two : function () { // this request is almost identical to the one issued with `.one()`, but // the value is now set to `2` for this invocation only. Ajax . api ( this , { parameters : { value : 2 } }); }, _ajaxSetup : function () { return { data : { actionName : \"makeSnafucated\" , className : \"app\\\\data\\\\foo\\\\FooAction\" , parameters : { value : 1 } } } } }; return Foo ; });","title":"_ajaxSetup()"},{"location":"javascript/new-api_ajax/#request-settings","text":"The object returned by the aforementioned _ajaxSetup() callback can contain these values:","title":"Request Settings"},{"location":"javascript/new-api_ajax/#data","text":"Defaults to {} . A plain JavaScript object that contains the request data that represents the form data of the request. The parameters key is recognized by the PHP Ajax API and becomes accessible through $this->parameters .","title":"data"},{"location":"javascript/new-api_ajax/#contenttype","text":"Defaults to application/x-www-form-urlencoded; charset=UTF-8 . The request content type, sets the Content-Type HTTP header if it is not empty.","title":"contentType"},{"location":"javascript/new-api_ajax/#responsetype","text":"Defaults to application/json . The server must respond with the Content-Type HTTP header set to this value, otherwise the request will be treated as failed. Requests for application/json will have the return body attempted to be evaluated as JSON. Other content types will only be validated based on the HTTP header, but no additional transformation is performed. For example, setting the responseType to application/xml will check the HTTP header, but will not transform the data parameter, you'll still receive a string in _ajaxSuccess !","title":"responseType"},{"location":"javascript/new-api_ajax/#type","text":"Defaults to POST . The HTTP Verb used for this request.","title":"type"},{"location":"javascript/new-api_ajax/#url","text":"Defaults to an empty string. Manual override for the request endpoint, it will be automatically set to the Core API endpoint if left empty. If the Core API endpoint is used, the options includeRequestedWith and withCredentials will be force-set to true.","title":"url"},{"location":"javascript/new-api_ajax/#withcredentials","text":"Enabling this parameter for any domain other than the current will trigger a CORS preflight request. Defaults to false . Include cookies with this requested, is always true when url is (implicitly) set to the Core API endpoint.","title":"withCredentials"},{"location":"javascript/new-api_ajax/#autoabort","text":"Defaults to false . When set to true , any pending responses to earlier requests will be silently discarded when issuing a new request. This only makes sense if the new request is meant to completely replace the result of the previous one, regardless of its reponse body. Typical use-cases include input field with suggestions, where possible values are requested from the server, but the input changed faster than the server was able to reply. In this particular case the client is not interested in the result for an earlier value, auto-aborting these requests avoids implementing this logic in the requesting code.","title":"autoAbort"},{"location":"javascript/new-api_ajax/#ignoreerror","text":"Defaults to false . Any failing request will invoke the failure -callback to check if an error message should be displayed. Enabling this option will suppress the general error overlay that reports a failed request. You can achieve the same result by returning false in the failure -callback.","title":"ignoreError"},{"location":"javascript/new-api_ajax/#silent","text":"Defaults to false . Enabling this option will suppress the loading indicator overlay for this request, other non-\"silent\" requests will still trigger the loading indicator.","title":"silent"},{"location":"javascript/new-api_ajax/#includerequestedwith","text":"Enabling this parameter for any domain other than the current will trigger a CORS preflight request. Defaults to true . Sets the custom HTTP header X-Requested-With: XMLHttpRequest for the request, it is automatically set to true when url is pointing at the WSC API endpoint.","title":"includeRequestedWith"},{"location":"javascript/new-api_ajax/#failure","text":"Defaults to null . Optional callback function that will be invoked for requests that have failed for one of these reasons: 1. The request timed out. 2. The HTTP status is not 2xx or 304 . 3. A responseType was set, but the response HTTP header Content-Type did not match the expected value. 4. The responseType was set to application/json , but the response body was not valid JSON. The callback function receives the parameter xhr (the XMLHttpRequest object) and options (deep clone of the request parameters). If the callback returns false , the general error overlay for failed requests will be suppressed. There will be no error overlay if ignoreError is set to true or if the request failed while attempting to evaluate the response body as JSON.","title":"failure"},{"location":"javascript/new-api_ajax/#finalize","text":"Defaults to null . Optional callback function that will be invoked once the request has completed, regardless if it succeeded or failed. The only parameter it receives is options (the request parameters object), but it does not receive the request's XMLHttpRequest .","title":"finalize"},{"location":"javascript/new-api_ajax/#success","text":"Defaults to null . This semi-optional callback function will always be set to _ajaxSuccess() when invoking Ajax.api() . It receives four parameters: 1. data - The request's response body as a string, or a JavaScript object if contentType was set to application/json . 2. responseText - The unmodified response body, it equals the value for data for non-JSON requests. 3. xhr - The underlying XMLHttpRequest object. 4. requestData - The request parameters that were supplied when the request was issued.","title":"success"},{"location":"javascript/new-api_ajax/#_ajaxsuccess","text":"This callback method is automatically called for successful AJAX requests, it receives four parameters, with the first one containing either the response body as a string, or a JavaScript object for JSON requests.","title":"_ajaxSuccess()"},{"location":"javascript/new-api_ajax/#_ajaxfailure","text":"Optional callback function that is invoked for failed requests, it will be automatically called if the callee implements it, otherwise the global error handler will be executed.","title":"_ajaxFailure()"},{"location":"javascript/new-api_ajax/#single-requests-without-a-module-legacy-api","text":"The Ajax.api() method expects an object that is used to extract the request configuration as well as providing the callback functions when the request state changes. You can issue a simple Ajax request without object binding through Ajax.apiOnce() that will destroy the instance after the request was finalized. This method is significantly more expensive for repeated requests and does not offer deriving modules from altering the behavior. It is strongly recommended to always use Ajax.api() for requests to the WSC API endpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 < script data-relocate = \"true\" > require ([ \"Ajax\" ], function ( Ajax ) { Ajax . apiOnce ({ data : { actionName : \"makeSnafucated\" , className : \"app\\\\data\\\\foo\\\\FooAction\" , parameters : { value : 3 } }, success : function ( data ) { elBySel ( \".some-element\" ). textContent = data . bar ; } }) }); </ script >","title":"Single Requests Without a Module (Legacy API)"},{"location":"javascript/new-api_browser/","text":"Browser and Screen Sizes - JavaScript API # Ui/Screen # CSS offers powerful media queries that alter the layout depending on the screen sizes, including but not limited to changes between landscape and portrait mode on mobile devices. The Ui/Screen module exposes a consistent interface to execute JavaScript code based on the same media queries that are available in the CSS code already. It features support for unmatching and executing code when a rule matches for the first time during the page lifecycle. Supported Aliases # You can pass in custom media queries, but it is strongly recommended to use the built-in media queries that match the same dimensions as your CSS. Alias Media Query screen-xs (max-width: 544px) screen-sm (min-width: 545px) and (max-width: 768px) screen-sm-down (max-width: 768px) screen-sm-up (min-width: 545px) screen-sm-md (min-width: 545px) and (max-width: 1024px) screen-md (min-width: 769px) and (max-width: 1024px) screen-md-down (max-width: 1024px) screen-md-up (min-width: 769px) screen-lg (min-width: 1025px) on(query: string, callbacks: Object): string # Registers a set of callback functions for the provided media query, the possible keys are match , unmatch and setup . The method returns a randomly generated UUIDv4 that is used to identify these callbacks and allows them to be removed via .remove() . remove(query: string, uuid: string) # Removes all callbacks for a media query that match the UUIDv4 that was previously obtained from the call to .on() . is(query: string): boolean # Tests if the provided media query currently matches and returns true on match. scrollDisable() # Temporarily prevents the page from being scrolled, until .scrollEnable() is called. scrollEnable() # Enables page scrolling again, unless another pending action has also prevented the page scrolling. Environment # The Environment module uses a mixture of feature detection and user agent sniffing to determine the browser and platform. In general, its results have proven to be very accurate, but it should be taken with a grain of salt regardless. Especially the browser checks are designed to be your last resort, please use feature detection instead whenever it is possible! Sometimes it may be necessary to alter the behavior of your code depending on the browser platform (e. g. mobile devices) or based on a specific browser in order to work-around some quirks. browser(): string # Attempts to detect browsers based on their technology and supported CSS vendor prefixes, and although somewhat reliable for major browsers, it is highly recommended to use feature detection instead. Possible values: - chrome (includes Opera 15+ and Vivaldi) - firefox - safari - microsoft (Internet Explorer and Edge) - other (default) platform(): string # Attempts to detect the browser platform using user agent sniffing. Possible values: - ios - android - windows (IE Mobile) - mobile (generic mobile device) - desktop (default)","title":"Browser and Screen Sizes"},{"location":"javascript/new-api_browser/#browser-and-screen-sizes-javascript-api","text":"","title":"Browser and Screen Sizes - JavaScript API"},{"location":"javascript/new-api_browser/#uiscreen","text":"CSS offers powerful media queries that alter the layout depending on the screen sizes, including but not limited to changes between landscape and portrait mode on mobile devices. The Ui/Screen module exposes a consistent interface to execute JavaScript code based on the same media queries that are available in the CSS code already. It features support for unmatching and executing code when a rule matches for the first time during the page lifecycle.","title":"Ui/Screen"},{"location":"javascript/new-api_browser/#supported-aliases","text":"You can pass in custom media queries, but it is strongly recommended to use the built-in media queries that match the same dimensions as your CSS. Alias Media Query screen-xs (max-width: 544px) screen-sm (min-width: 545px) and (max-width: 768px) screen-sm-down (max-width: 768px) screen-sm-up (min-width: 545px) screen-sm-md (min-width: 545px) and (max-width: 1024px) screen-md (min-width: 769px) and (max-width: 1024px) screen-md-down (max-width: 1024px) screen-md-up (min-width: 769px) screen-lg (min-width: 1025px)","title":"Supported Aliases"},{"location":"javascript/new-api_browser/#onquery-string-callbacks-object-string","text":"Registers a set of callback functions for the provided media query, the possible keys are match , unmatch and setup . The method returns a randomly generated UUIDv4 that is used to identify these callbacks and allows them to be removed via .remove() .","title":"on(query: string, callbacks: Object): string"},{"location":"javascript/new-api_browser/#removequery-string-uuid-string","text":"Removes all callbacks for a media query that match the UUIDv4 that was previously obtained from the call to .on() .","title":"remove(query: string, uuid: string)"},{"location":"javascript/new-api_browser/#isquery-string-boolean","text":"Tests if the provided media query currently matches and returns true on match.","title":"is(query: string): boolean"},{"location":"javascript/new-api_browser/#scrolldisable","text":"Temporarily prevents the page from being scrolled, until .scrollEnable() is called.","title":"scrollDisable()"},{"location":"javascript/new-api_browser/#scrollenable","text":"Enables page scrolling again, unless another pending action has also prevented the page scrolling.","title":"scrollEnable()"},{"location":"javascript/new-api_browser/#environment","text":"The Environment module uses a mixture of feature detection and user agent sniffing to determine the browser and platform. In general, its results have proven to be very accurate, but it should be taken with a grain of salt regardless. Especially the browser checks are designed to be your last resort, please use feature detection instead whenever it is possible! Sometimes it may be necessary to alter the behavior of your code depending on the browser platform (e. g. mobile devices) or based on a specific browser in order to work-around some quirks.","title":"Environment"},{"location":"javascript/new-api_browser/#browser-string","text":"Attempts to detect browsers based on their technology and supported CSS vendor prefixes, and although somewhat reliable for major browsers, it is highly recommended to use feature detection instead. Possible values: - chrome (includes Opera 15+ and Vivaldi) - firefox - safari - microsoft (Internet Explorer and Edge) - other (default)","title":"browser(): string"},{"location":"javascript/new-api_browser/#platform-string","text":"Attempts to detect the browser platform using user agent sniffing. Possible values: - ios - android - windows (IE Mobile) - mobile (generic mobile device) - desktop (default)","title":"platform(): string"},{"location":"javascript/new-api_core/","text":"Core Modules and Functions - JavaScript API # A brief overview of common methods that may be useful when writing any module. Core # clone(object: Object): Object # Creates a deep-clone of the provided object by value, removing any references on the original element, including arrays. However, this does not clone references to non-plain objects, these instances will be copied by reference. 1 2 3 4 5 6 7 require ([ \"Core\" ], function ( Core ) { var obj1 = { a : 1 }; var obj2 = Core . clone ( obj1 ); console . log ( obj1 === obj2 ); // output: false console . log ( obj2 . hasOwnProperty ( \"a\" ) && obj2 . a === 1 ); // output: true }); extend(base: Object, ...merge: Object[]): Object # Accepts an infinite amount of plain objects as parameters, values will be copied from the 2nd...nth object into the first object. The first parameter will be cloned and the resulting object is returned. 1 2 3 4 5 6 7 8 9 10 require ([ \"Core\" ], function ( Core ) { var obj1 = { a : 2 }; var obj2 = { a : 1 , b : 2 }; var obj = Core . extend ({ b : 1 }, obj1 , obj2 ); console . log ( obj . b === 2 ); // output: true console . log ( obj . hasOwnProperty ( \"a\" ) && obj . a === 2 ); // output: false }); inherit(base: Object, target: Object, merge?: Object) # Derives the second object's prototype from the first object, afterwards the derived class will pass the instanceof check against the original class. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); App . Baz = App . Foo . extend ({ makeSnafucated : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); // App/Baz.js define ([ \"Core\" , \"./Foo\" ], function ( Core , Foo ) { \"use strict\" ; function Baz () {}; Core . inherit ( Baz , Foo , { makeSnafucated : function () {} }); return Baz ; }); isPlainObject(object: Object): boolean # Verifies if an object is a plain JavaScript object and not an object instance. 1 2 3 4 5 6 7 8 9 10 11 12 13 require ([ \"Core\" ], function ( Core ) { function Foo () {} Foo . prototype = { hello : \"world\" ; }; var obj1 = { hello : \"world\" }; var obj2 = new Foo (); console . log ( Core . isPlainObject ( obj1 )); // output: true console . log ( obj1 . hello === obj2 . hello ); // output: true console . log ( Core . isPlainObject ( obj2 )); // output: false }); triggerEvent(element: Element, eventName: string) # Creates and dispatches a synthetic JavaScript event on an element. 1 2 3 4 require ([ \"Core\" ], function ( Core ) { var element = elBySel ( \".some-element\" ); Core . triggerEvent ( element , \"click\" ); }); Language # add(key: string, value: string) # Registers a new phrase. 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . add ( 'app.foo.bar' , '{jslang}app.foo.bar{/jslang}' ); }); </ script > addObject(object: Object) # Registers a list of phrases using a plain object. 1 2 3 4 5 6 7 < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . addObject ({ 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' }); }); </ script > get(key: string, parameters?: Object): string # Retrieves a phrase by its key, optionally supporting basic template scripting with dynamic variables passed using the parameters object. 1 2 3 4 5 6 require ([ \"Language\" ], function ( Language ) { var title = Language . get ( \"app.foo.title\" ); var content = Language . get ( \"app.foo.content\" , { some : \"value\" }); }); StringUtil # escapeHTML(str: string): string # Escapes special HTML characters by converting them into an HTML entity. Character Replacement & & \" " < < > > escapeRegExp(str: string): string # Escapes a list of characters that have a special meaning in regular expressions and could alter the behavior when embedded into regular expressions. lcfirst(str: string): string # Makes a string's first character lowercase. ucfirst(str: string): string # Makes a string's first character uppercase. unescapeHTML(str: string): string # Converts some HTML entities into their original character. This is the reverse function of escapeHTML() .","title":"Core Functions"},{"location":"javascript/new-api_core/#core-modules-and-functions-javascript-api","text":"A brief overview of common methods that may be useful when writing any module.","title":"Core Modules and Functions - JavaScript API"},{"location":"javascript/new-api_core/#core","text":"","title":"Core"},{"location":"javascript/new-api_core/#cloneobject-object-object","text":"Creates a deep-clone of the provided object by value, removing any references on the original element, including arrays. However, this does not clone references to non-plain objects, these instances will be copied by reference. 1 2 3 4 5 6 7 require ([ \"Core\" ], function ( Core ) { var obj1 = { a : 1 }; var obj2 = Core . clone ( obj1 ); console . log ( obj1 === obj2 ); // output: false console . log ( obj2 . hasOwnProperty ( \"a\" ) && obj2 . a === 1 ); // output: true });","title":"clone(object: Object): Object"},{"location":"javascript/new-api_core/#extendbase-object-merge-object-object","text":"Accepts an infinite amount of plain objects as parameters, values will be copied from the 2nd...nth object into the first object. The first parameter will be cloned and the resulting object is returned. 1 2 3 4 5 6 7 8 9 10 require ([ \"Core\" ], function ( Core ) { var obj1 = { a : 2 }; var obj2 = { a : 1 , b : 2 }; var obj = Core . extend ({ b : 1 }, obj1 , obj2 ); console . log ( obj . b === 2 ); // output: true console . log ( obj . hasOwnProperty ( \"a\" ) && obj . a === 2 ); // output: false });","title":"extend(base: Object, ...merge: Object[]): Object"},{"location":"javascript/new-api_core/#inheritbase-object-target-object-merge-object","text":"Derives the second object's prototype from the first object, afterwards the derived class will pass the instanceof check against the original class. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // App.js window . App = {}; App . Foo = Class . extend ({ bar : function () {} }); App . Baz = App . Foo . extend ({ makeSnafucated : function () {} }); // --- NEW API --- // App/Foo.js define ([], function () { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () {} }; return Foo ; }); // App/Baz.js define ([ \"Core\" , \"./Foo\" ], function ( Core , Foo ) { \"use strict\" ; function Baz () {}; Core . inherit ( Baz , Foo , { makeSnafucated : function () {} }); return Baz ; });","title":"inherit(base: Object, target: Object, merge?: Object)"},{"location":"javascript/new-api_core/#isplainobjectobject-object-boolean","text":"Verifies if an object is a plain JavaScript object and not an object instance. 1 2 3 4 5 6 7 8 9 10 11 12 13 require ([ \"Core\" ], function ( Core ) { function Foo () {} Foo . prototype = { hello : \"world\" ; }; var obj1 = { hello : \"world\" }; var obj2 = new Foo (); console . log ( Core . isPlainObject ( obj1 )); // output: true console . log ( obj1 . hello === obj2 . hello ); // output: true console . log ( Core . isPlainObject ( obj2 )); // output: false });","title":"isPlainObject(object: Object): boolean"},{"location":"javascript/new-api_core/#triggereventelement-element-eventname-string","text":"Creates and dispatches a synthetic JavaScript event on an element. 1 2 3 4 require ([ \"Core\" ], function ( Core ) { var element = elBySel ( \".some-element\" ); Core . triggerEvent ( element , \"click\" ); });","title":"triggerEvent(element: Element, eventName: string)"},{"location":"javascript/new-api_core/#language","text":"","title":"Language"},{"location":"javascript/new-api_core/#addkey-string-value-string","text":"Registers a new phrase. 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . add ( 'app.foo.bar' , '{jslang}app.foo.bar{/jslang}' ); }); </ script >","title":"add(key: string, value: string)"},{"location":"javascript/new-api_core/#addobjectobject-object","text":"Registers a list of phrases using a plain object. 1 2 3 4 5 6 7 < script data-relocate = \"true\" > require ([ \"Language\" ], function ( Language ) { Language . addObject ({ 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' }); }); </ script >","title":"addObject(object: Object)"},{"location":"javascript/new-api_core/#getkey-string-parameters-object-string","text":"Retrieves a phrase by its key, optionally supporting basic template scripting with dynamic variables passed using the parameters object. 1 2 3 4 5 6 require ([ \"Language\" ], function ( Language ) { var title = Language . get ( \"app.foo.title\" ); var content = Language . get ( \"app.foo.content\" , { some : \"value\" }); });","title":"get(key: string, parameters?: Object): string"},{"location":"javascript/new-api_core/#stringutil","text":"","title":"StringUtil"},{"location":"javascript/new-api_core/#escapehtmlstr-string-string","text":"Escapes special HTML characters by converting them into an HTML entity. Character Replacement & & \" " < < > >","title":"escapeHTML(str: string): string"},{"location":"javascript/new-api_core/#escaperegexpstr-string-string","text":"Escapes a list of characters that have a special meaning in regular expressions and could alter the behavior when embedded into regular expressions.","title":"escapeRegExp(str: string): string"},{"location":"javascript/new-api_core/#lcfirststr-string-string","text":"Makes a string's first character lowercase.","title":"lcfirst(str: string): string"},{"location":"javascript/new-api_core/#ucfirststr-string-string","text":"Makes a string's first character uppercase.","title":"ucfirst(str: string): string"},{"location":"javascript/new-api_core/#unescapehtmlstr-string-string","text":"Converts some HTML entities into their original character. This is the reverse function of escapeHTML() .","title":"unescapeHTML(str: string): string"},{"location":"javascript/new-api_data-structures/","text":"Data Structures - JavaScript API # These data structures are deprecated since version 5.4. Refer to our migration guide on how to replace them. Introduction # JavaScript offers only limited types of collections to hold and iterate over data. Despite the ongoing efforts in ES6 and newer, these new data structures and access methods, such as for \u2026 of , are not available in the still supported Internet Explorer 11. Dictionary # Represents a simple key-value map, but unlike the use of plain objects, will always to guarantee to iterate over directly set values only. In supported browsers this will use a native Map internally, otherwise a plain object. set(key: string, value: any) # Adds or updates an item using the provided key. Numeric keys will be converted into strings. delete(key: string) # Removes an item from the collection. has(key: string): boolean # Returns true if the key is contained in the collection. get(key: string): any # Returns the value for the provided key, or undefined if the key was not found. Use .has() to check for key existence. forEach(callback: (value: any, key: string) => void) # Iterates over all items in the collection in an arbitrary order and invokes the supplied callback with the value and the key. size: number # This read-only property counts the number of items in the collection. List # Represents a list of unique values. In supported browsers this will use a native Set internally, otherwise an array. add(value: any) # Adds a value to the list. If the value is already part of the list, this method will silently abort. clear() # Resets the collection. delete(value: any): boolean # Attempts to remove a value from the list, it returns true if the value has been part of the list. forEach(callback: (value: any) => void) # Iterates over all values in the list in an arbitrary order and invokes the supplied callback for each value. has(value: any): boolean # Returns true if the provided value is part of this list. size: number # This read-only property counts the number of items in the list. ObjectMap # This class uses a WeakMap internally, the keys are only weakly referenced and do not prevent garbage collection. Represents a collection where any kind of objects, such as class instances or DOM elements, can be used as key. These keys are weakly referenced and will not prevent garbage collection from happening, but this also means that it is not possible to enumerate or iterate over the stored keys and values. This class is especially useful when you want to store additional data for objects that may get disposed on runtime, such as DOM elements. Using any regular data collections will cause the object to be referenced indefinitely, preventing the garbage collection from removing orphaned objects. set(key: Object, value: Object) # Adds the key with the provided value to the map, if the key was already part of the collection, its value is overwritten. delete(key: Object) # Attempts to remove a key from the collection. The method will abort silently if the key is not part of the collection. has(key: Object): boolean # Returns true if there is a value for the provided key in this collection. get(key: Object): Object | undefined # Retrieves the value of the provided key, or undefined if the key was not found.","title":"Data Structures"},{"location":"javascript/new-api_data-structures/#data-structures-javascript-api","text":"These data structures are deprecated since version 5.4. Refer to our migration guide on how to replace them.","title":"Data Structures - JavaScript API"},{"location":"javascript/new-api_data-structures/#introduction","text":"JavaScript offers only limited types of collections to hold and iterate over data. Despite the ongoing efforts in ES6 and newer, these new data structures and access methods, such as for \u2026 of , are not available in the still supported Internet Explorer 11.","title":"Introduction"},{"location":"javascript/new-api_data-structures/#dictionary","text":"Represents a simple key-value map, but unlike the use of plain objects, will always to guarantee to iterate over directly set values only. In supported browsers this will use a native Map internally, otherwise a plain object.","title":"Dictionary"},{"location":"javascript/new-api_data-structures/#setkey-string-value-any","text":"Adds or updates an item using the provided key. Numeric keys will be converted into strings.","title":"set(key: string, value: any)"},{"location":"javascript/new-api_data-structures/#deletekey-string","text":"Removes an item from the collection.","title":"delete(key: string)"},{"location":"javascript/new-api_data-structures/#haskey-string-boolean","text":"Returns true if the key is contained in the collection.","title":"has(key: string): boolean"},{"location":"javascript/new-api_data-structures/#getkey-string-any","text":"Returns the value for the provided key, or undefined if the key was not found. Use .has() to check for key existence.","title":"get(key: string): any"},{"location":"javascript/new-api_data-structures/#foreachcallback-value-any-key-string-void","text":"Iterates over all items in the collection in an arbitrary order and invokes the supplied callback with the value and the key.","title":"forEach(callback: (value: any, key: string) => void)"},{"location":"javascript/new-api_data-structures/#size-number","text":"This read-only property counts the number of items in the collection.","title":"size: number"},{"location":"javascript/new-api_data-structures/#list","text":"Represents a list of unique values. In supported browsers this will use a native Set internally, otherwise an array.","title":"List"},{"location":"javascript/new-api_data-structures/#addvalue-any","text":"Adds a value to the list. If the value is already part of the list, this method will silently abort.","title":"add(value: any)"},{"location":"javascript/new-api_data-structures/#clear","text":"Resets the collection.","title":"clear()"},{"location":"javascript/new-api_data-structures/#deletevalue-any-boolean","text":"Attempts to remove a value from the list, it returns true if the value has been part of the list.","title":"delete(value: any): boolean"},{"location":"javascript/new-api_data-structures/#foreachcallback-value-any-void","text":"Iterates over all values in the list in an arbitrary order and invokes the supplied callback for each value.","title":"forEach(callback: (value: any) => void)"},{"location":"javascript/new-api_data-structures/#hasvalue-any-boolean","text":"Returns true if the provided value is part of this list.","title":"has(value: any): boolean"},{"location":"javascript/new-api_data-structures/#size-number_1","text":"This read-only property counts the number of items in the list.","title":"size: number"},{"location":"javascript/new-api_data-structures/#objectmap","text":"This class uses a WeakMap internally, the keys are only weakly referenced and do not prevent garbage collection. Represents a collection where any kind of objects, such as class instances or DOM elements, can be used as key. These keys are weakly referenced and will not prevent garbage collection from happening, but this also means that it is not possible to enumerate or iterate over the stored keys and values. This class is especially useful when you want to store additional data for objects that may get disposed on runtime, such as DOM elements. Using any regular data collections will cause the object to be referenced indefinitely, preventing the garbage collection from removing orphaned objects.","title":"ObjectMap"},{"location":"javascript/new-api_data-structures/#setkey-object-value-object","text":"Adds the key with the provided value to the map, if the key was already part of the collection, its value is overwritten.","title":"set(key: Object, value: Object)"},{"location":"javascript/new-api_data-structures/#deletekey-object","text":"Attempts to remove a key from the collection. The method will abort silently if the key is not part of the collection.","title":"delete(key: Object)"},{"location":"javascript/new-api_data-structures/#haskey-object-boolean","text":"Returns true if there is a value for the provided key in this collection.","title":"has(key: Object): boolean"},{"location":"javascript/new-api_data-structures/#getkey-object-object-undefined","text":"Retrieves the value of the provided key, or undefined if the key was not found.","title":"get(key: Object): Object | undefined"},{"location":"javascript/new-api_dialogs/","text":"Dialogs - JavaScript API # Introduction # Dialogs are full screen overlays that cover the currently visible window area using a semi-opague backdrop and a prominently placed dialog window in the foreground. They shift the attention away from the original content towards the dialog and usually contain additional details and/or dedicated form inputs. _dialogSetup() # The lazy initialization is performed upon the first invocation from the callee, using the magic _dialogSetup() method to retrieve the basic configuration for the dialog construction and any event callbacks. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // App/Foo.js define ([ \"Ui/Dialog\" ], function ( UiDialog ) { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () { // this will open the dialog constructed by _dialogSetup UiDialog . open ( this ); }, _dialogSetup : function () { return { id : \"myDialog\" , source : \"<p>Hello World!</p>\" , options : { onClose : function () { // the fancy dialog was closed! } } } } }; return Foo ; }); id: string # The id is used to identify a dialog on runtime, but is also part of the first- time setup when the dialog has not been opened before. If source is undefined , the module attempts to construct the dialog using an element with the same id. source: any # There are six different types of value that source does allow and each of them changes how the initial dialog is constructed: undefined The dialog exists already and the value of id should be used to identify the element. null The HTML is provided using the second argument of .open() . () => void If the source is a function, it is executed and is expected to start the dialog initialization itself. Object Plain objects are interpreted as parameters for an Ajax request, in particular source.data will be used to issue the request. It is possible to specify the key source.after as a callback (content: Element, responseData: Object) => void that is executed after the dialog was opened. string The string is expected to be plain HTML that should be used to construct the dialog. DocumentFragment A new container <div> with the provided id is created and the contents of the DocumentFragment is appended to it. This container is then used for the dialog. options: Object # All configuration options and callbacks are handled through this object. options.backdropCloseOnClick: boolean # Defaults to true . Clicks on the dialog backdrop will close the top-most dialog. This option will be force-disabled if the option closeable is set to false . options.closable: boolean # Defaults to true . Enables the close button in the dialog title, when disabled the dialog can be closed through the .close() API call only. options.closeButtonLabel: string # Defaults to Language.get(\"wcf.global.button.close\") . The phrase that is displayed in the tooltip for the close button. options.closeConfirmMessage: string # Defaults to \"\" . Shows a confirmation dialog using the configured message before closing the dialog. The dialog will not be closed if the dialog is rejected by the user. options.title: string # Defaults to \"\" . The phrase that is displayed in the dialog title. options.onBeforeClose: (id: string) => void # Defaults to null . The callback is executed when the user clicks on the close button or, if enabled, on the backdrop. The callback is responsible to close the dialog by itself, the default close behavior is automatically prevented. options.onClose: (id: string) => void # Defaults to null . The callback is notified once the dialog is about to be closed, but is still visible at this point. It is not possible to abort the close operation at this point. options.onShow: (content: Element) => void # Defaults to null . Receives the dialog content element as its only argument, allowing the callback to modify the DOM or to register event listeners before the dialog is presented to the user. The dialog is already visible at call time, but the dialog has not been finalized yet. setTitle(id: string | Object, title: string) # Sets the title of a dialog. setCallback(id: string | Object, key: string, value: (data: any) => void | null) # Sets a callback function after the dialog initialization, the special value null will remove a previously set callback. Valid values for key are onBeforeClose , onClose and onShow . rebuild(id: string | Object) # Rebuilds a dialog by performing various calculations on the maximum dialog height in regards to the overflow handling and adjustments for embedded forms. This method is automatically invoked whenever a dialog is shown, after invoking the options.onShow callback. close(id: string | Object) # Closes an open dialog, this will neither trigger a confirmation dialog, nor does it invoke the options.onBeforeClose callback. The options.onClose callback will always be invoked, but it cannot abort the close operation. getDialog(id: string | Object): Object # This method returns an internal data object by reference, any modifications made do have an effect on the dialogs behavior and in particular no validation is performed on the modification. It is strongly recommended to use the .set*() methods only. Returns the internal dialog data that is attached to a dialog. The most important key is .content which holds a reference to the dialog's inner content element. isOpen(id: string | Object): boolean # Returns true if the dialog exists and is open.","title":"Dialogs"},{"location":"javascript/new-api_dialogs/#dialogs-javascript-api","text":"","title":"Dialogs - JavaScript API"},{"location":"javascript/new-api_dialogs/#introduction","text":"Dialogs are full screen overlays that cover the currently visible window area using a semi-opague backdrop and a prominently placed dialog window in the foreground. They shift the attention away from the original content towards the dialog and usually contain additional details and/or dedicated form inputs.","title":"Introduction"},{"location":"javascript/new-api_dialogs/#_dialogsetup","text":"The lazy initialization is performed upon the first invocation from the callee, using the magic _dialogSetup() method to retrieve the basic configuration for the dialog construction and any event callbacks. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // App/Foo.js define ([ \"Ui/Dialog\" ], function ( UiDialog ) { \"use strict\" ; function Foo () {}; Foo . prototype = { bar : function () { // this will open the dialog constructed by _dialogSetup UiDialog . open ( this ); }, _dialogSetup : function () { return { id : \"myDialog\" , source : \"<p>Hello World!</p>\" , options : { onClose : function () { // the fancy dialog was closed! } } } } }; return Foo ; });","title":"_dialogSetup()"},{"location":"javascript/new-api_dialogs/#id-string","text":"The id is used to identify a dialog on runtime, but is also part of the first- time setup when the dialog has not been opened before. If source is undefined , the module attempts to construct the dialog using an element with the same id.","title":"id: string"},{"location":"javascript/new-api_dialogs/#source-any","text":"There are six different types of value that source does allow and each of them changes how the initial dialog is constructed: undefined The dialog exists already and the value of id should be used to identify the element. null The HTML is provided using the second argument of .open() . () => void If the source is a function, it is executed and is expected to start the dialog initialization itself. Object Plain objects are interpreted as parameters for an Ajax request, in particular source.data will be used to issue the request. It is possible to specify the key source.after as a callback (content: Element, responseData: Object) => void that is executed after the dialog was opened. string The string is expected to be plain HTML that should be used to construct the dialog. DocumentFragment A new container <div> with the provided id is created and the contents of the DocumentFragment is appended to it. This container is then used for the dialog.","title":"source: any"},{"location":"javascript/new-api_dialogs/#options-object","text":"All configuration options and callbacks are handled through this object.","title":"options: Object"},{"location":"javascript/new-api_dialogs/#optionsbackdropcloseonclick-boolean","text":"Defaults to true . Clicks on the dialog backdrop will close the top-most dialog. This option will be force-disabled if the option closeable is set to false .","title":"options.backdropCloseOnClick: boolean"},{"location":"javascript/new-api_dialogs/#optionsclosable-boolean","text":"Defaults to true . Enables the close button in the dialog title, when disabled the dialog can be closed through the .close() API call only.","title":"options.closable: boolean"},{"location":"javascript/new-api_dialogs/#optionsclosebuttonlabel-string","text":"Defaults to Language.get(\"wcf.global.button.close\") . The phrase that is displayed in the tooltip for the close button.","title":"options.closeButtonLabel: string"},{"location":"javascript/new-api_dialogs/#optionscloseconfirmmessage-string","text":"Defaults to \"\" . Shows a confirmation dialog using the configured message before closing the dialog. The dialog will not be closed if the dialog is rejected by the user.","title":"options.closeConfirmMessage: string"},{"location":"javascript/new-api_dialogs/#optionstitle-string","text":"Defaults to \"\" . The phrase that is displayed in the dialog title.","title":"options.title: string"},{"location":"javascript/new-api_dialogs/#optionsonbeforeclose-id-string-void","text":"Defaults to null . The callback is executed when the user clicks on the close button or, if enabled, on the backdrop. The callback is responsible to close the dialog by itself, the default close behavior is automatically prevented.","title":"options.onBeforeClose: (id: string) => void"},{"location":"javascript/new-api_dialogs/#optionsonclose-id-string-void","text":"Defaults to null . The callback is notified once the dialog is about to be closed, but is still visible at this point. It is not possible to abort the close operation at this point.","title":"options.onClose: (id: string) => void"},{"location":"javascript/new-api_dialogs/#optionsonshow-content-element-void","text":"Defaults to null . Receives the dialog content element as its only argument, allowing the callback to modify the DOM or to register event listeners before the dialog is presented to the user. The dialog is already visible at call time, but the dialog has not been finalized yet.","title":"options.onShow: (content: Element) => void"},{"location":"javascript/new-api_dialogs/#settitleid-string-object-title-string","text":"Sets the title of a dialog.","title":"setTitle(id: string | Object, title: string)"},{"location":"javascript/new-api_dialogs/#setcallbackid-string-object-key-string-value-data-any-void-null","text":"Sets a callback function after the dialog initialization, the special value null will remove a previously set callback. Valid values for key are onBeforeClose , onClose and onShow .","title":"setCallback(id: string | Object, key: string, value: (data: any) => void | null)"},{"location":"javascript/new-api_dialogs/#rebuildid-string-object","text":"Rebuilds a dialog by performing various calculations on the maximum dialog height in regards to the overflow handling and adjustments for embedded forms. This method is automatically invoked whenever a dialog is shown, after invoking the options.onShow callback.","title":"rebuild(id: string | Object)"},{"location":"javascript/new-api_dialogs/#closeid-string-object","text":"Closes an open dialog, this will neither trigger a confirmation dialog, nor does it invoke the options.onBeforeClose callback. The options.onClose callback will always be invoked, but it cannot abort the close operation.","title":"close(id: string | Object)"},{"location":"javascript/new-api_dialogs/#getdialogid-string-object-object","text":"This method returns an internal data object by reference, any modifications made do have an effect on the dialogs behavior and in particular no validation is performed on the modification. It is strongly recommended to use the .set*() methods only. Returns the internal dialog data that is attached to a dialog. The most important key is .content which holds a reference to the dialog's inner content element.","title":"getDialog(id: string | Object): Object"},{"location":"javascript/new-api_dialogs/#isopenid-string-object-boolean","text":"Returns true if the dialog exists and is open.","title":"isOpen(id: string | Object): boolean"},{"location":"javascript/new-api_dom/","text":"Working with the DOM - JavaScript API # Helper Functions # There is large set of helper functions that assist you when working with the DOM tree and its elements. These functions are globally available and do not require explicit module imports. Dom/Util # createFragmentFromHtml(html: string): DocumentFragment # Parses a HTML string and creates a DocumentFragment object that holds the resulting nodes. identify(element: Element): string # Retrieves the unique identifier ( id ) of an element. If it does not currently have an id assigned, a generic identifier is used instead. outerHeight(element: Element, styles?: CSSStyleDeclaration): number # Computes the outer height of an element using the element's offsetHeight and the sum of the rounded down values for margin-top and margin-bottom . outerWidth(element: Element, styles?: CSSStyleDeclaration): number # Computes the outer width of an element using the element's offsetWidth and the sum of the rounded down values for margin-left and margin-right . outerDimensions(element: Element): { height: number, width: number } # Computes the outer dimensions of an element including its margins. offset(element: Element): { top: number, left: number } # Computes the element's offset relative to the top left corner of the document. setInnerHtml(element: Element, innerHtml: string) # Sets the inner HTML of an element via element.innerHTML = innerHtml . Browsers do not evaluate any embedded <script> tags, therefore this method extracts each of them, creates new <script> tags and inserts them in their original order of appearance. contains(element: Element, child: Element): boolean # Evaluates if element is a direct or indirect parent element of child . unwrapChildNodes(element: Element) # Moves all child nodes out of element while maintaining their order, then removes element from the document. Dom/ChangeListener # This class is used to observe specific changes to the DOM, for example after an Ajax request has completed. For performance reasons this is a manually-invoked listener that does not rely on a MutationObserver . 1 2 3 4 5 6 7 8 require ([ \"Dom/ChangeListener\" ], function ( DomChangeListener ) { DomChangeListener . add ( \"App/Foo\" , function () { // the DOM may have been altered significantly }); // propagate changes to the DOM DomChangeListener . trigger (); });","title":"DOM"},{"location":"javascript/new-api_dom/#working-with-the-dom-javascript-api","text":"","title":"Working with the DOM - JavaScript API"},{"location":"javascript/new-api_dom/#helper-functions","text":"There is large set of helper functions that assist you when working with the DOM tree and its elements. These functions are globally available and do not require explicit module imports.","title":"Helper Functions"},{"location":"javascript/new-api_dom/#domutil","text":"","title":"Dom/Util"},{"location":"javascript/new-api_dom/#createfragmentfromhtmlhtml-string-documentfragment","text":"Parses a HTML string and creates a DocumentFragment object that holds the resulting nodes.","title":"createFragmentFromHtml(html: string): DocumentFragment"},{"location":"javascript/new-api_dom/#identifyelement-element-string","text":"Retrieves the unique identifier ( id ) of an element. If it does not currently have an id assigned, a generic identifier is used instead.","title":"identify(element: Element): string"},{"location":"javascript/new-api_dom/#outerheightelement-element-styles-cssstyledeclaration-number","text":"Computes the outer height of an element using the element's offsetHeight and the sum of the rounded down values for margin-top and margin-bottom .","title":"outerHeight(element: Element, styles?: CSSStyleDeclaration): number"},{"location":"javascript/new-api_dom/#outerwidthelement-element-styles-cssstyledeclaration-number","text":"Computes the outer width of an element using the element's offsetWidth and the sum of the rounded down values for margin-left and margin-right .","title":"outerWidth(element: Element, styles?: CSSStyleDeclaration): number"},{"location":"javascript/new-api_dom/#outerdimensionselement-element-height-number-width-number","text":"Computes the outer dimensions of an element including its margins.","title":"outerDimensions(element: Element): { height: number, width: number }"},{"location":"javascript/new-api_dom/#offsetelement-element-top-number-left-number","text":"Computes the element's offset relative to the top left corner of the document.","title":"offset(element: Element): { top: number, left: number }"},{"location":"javascript/new-api_dom/#setinnerhtmlelement-element-innerhtml-string","text":"Sets the inner HTML of an element via element.innerHTML = innerHtml . Browsers do not evaluate any embedded <script> tags, therefore this method extracts each of them, creates new <script> tags and inserts them in their original order of appearance.","title":"setInnerHtml(element: Element, innerHtml: string)"},{"location":"javascript/new-api_dom/#containselement-element-child-element-boolean","text":"Evaluates if element is a direct or indirect parent element of child .","title":"contains(element: Element, child: Element): boolean"},{"location":"javascript/new-api_dom/#unwrapchildnodeselement-element","text":"Moves all child nodes out of element while maintaining their order, then removes element from the document.","title":"unwrapChildNodes(element: Element)"},{"location":"javascript/new-api_dom/#domchangelistener","text":"This class is used to observe specific changes to the DOM, for example after an Ajax request has completed. For performance reasons this is a manually-invoked listener that does not rely on a MutationObserver . 1 2 3 4 5 6 7 8 require ([ \"Dom/ChangeListener\" ], function ( DomChangeListener ) { DomChangeListener . add ( \"App/Foo\" , function () { // the DOM may have been altered significantly }); // propagate changes to the DOM DomChangeListener . trigger (); });","title":"Dom/ChangeListener"},{"location":"javascript/new-api_events/","text":"Event Handling - JavaScript API # EventKey # This class offers a set of static methods that can be used to determine if some common keys are being pressed. Internally it compares either the .key property if it is supported or the value of .which . 1 2 3 4 5 6 7 require ([ \"EventKey\" ], function ( EventKey ) { elBySel ( \".some-input\" ). addEventListener ( \"keydown\" , function ( event ) { if ( EventKey . Enter ( event )) { // the `Enter` key was pressed } }); }); ArrowDown(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u2193 key. ArrowLeft(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u2190 key. ArrowRight(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u2192 key. ArrowUp(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u2191 key. Comma(event: KeyboardEvent): boolean # Returns true if the user has pressed the , key. Enter(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u21b2 key. Escape(event: KeyboardEvent): boolean # Returns true if the user has pressed the Esc key. Tab(event: KeyboardEvent): boolean # Returns true if the user has pressed the \u21b9 key. EventHandler # A synchronous event system based on string identifiers rather than DOM elements, similar to the PHP event system in WoltLab Suite. Any components can listen to events or trigger events itself at any time. Identifiying Events with the Developer Tools # The Developer Tools offer an easy option to identify existing events that are fired while code is being executed. You can enable this watch mode through your browser's console using Devtools.toggleEventLogging() : 1 2 3 4 > Devtools.toggleEventLogging(); < Event logging enabled < [Devtools.EventLogging] Firing event: bar @ com.example.app.foo < [Devtools.EventLogging] Firing event: baz @ com.example.app.foo add(identifier: string, action: string, callback: (data: Object) => void): string # Adding an event listeners returns a randomly generated UUIDv4 that is used to identify the listener. This UUID is required to remove a specific listener through the remove() method. fire(identifier: string, action: string, data?: Object) # Triggers an event using an optional data object that is passed to each listener by reference. remove(identifier: string, action: string, uuid: string) # Removes a previously registered event listener using the UUID returned by add() . removeAll(identifier: string, action: string) # Removes all event listeners registered for the provided identifier and action . removeAllBySuffix(identifier: string, suffix: string) # Removes all event listeners for an identifier whose action ends with the value of suffix .","title":"Event Handling"},{"location":"javascript/new-api_events/#event-handling-javascript-api","text":"","title":"Event Handling - JavaScript API"},{"location":"javascript/new-api_events/#eventkey","text":"This class offers a set of static methods that can be used to determine if some common keys are being pressed. Internally it compares either the .key property if it is supported or the value of .which . 1 2 3 4 5 6 7 require ([ \"EventKey\" ], function ( EventKey ) { elBySel ( \".some-input\" ). addEventListener ( \"keydown\" , function ( event ) { if ( EventKey . Enter ( event )) { // the `Enter` key was pressed } }); });","title":"EventKey"},{"location":"javascript/new-api_events/#arrowdownevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u2193 key.","title":"ArrowDown(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#arrowleftevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u2190 key.","title":"ArrowLeft(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#arrowrightevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u2192 key.","title":"ArrowRight(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#arrowupevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u2191 key.","title":"ArrowUp(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#commaevent-keyboardevent-boolean","text":"Returns true if the user has pressed the , key.","title":"Comma(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#enterevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u21b2 key.","title":"Enter(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#escapeevent-keyboardevent-boolean","text":"Returns true if the user has pressed the Esc key.","title":"Escape(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#tabevent-keyboardevent-boolean","text":"Returns true if the user has pressed the \u21b9 key.","title":"Tab(event: KeyboardEvent): boolean"},{"location":"javascript/new-api_events/#eventhandler","text":"A synchronous event system based on string identifiers rather than DOM elements, similar to the PHP event system in WoltLab Suite. Any components can listen to events or trigger events itself at any time.","title":"EventHandler"},{"location":"javascript/new-api_events/#identifiying-events-with-the-developer-tools","text":"The Developer Tools offer an easy option to identify existing events that are fired while code is being executed. You can enable this watch mode through your browser's console using Devtools.toggleEventLogging() : 1 2 3 4 > Devtools.toggleEventLogging(); < Event logging enabled < [Devtools.EventLogging] Firing event: bar @ com.example.app.foo < [Devtools.EventLogging] Firing event: baz @ com.example.app.foo","title":"Identifiying Events with the Developer Tools"},{"location":"javascript/new-api_events/#addidentifier-string-action-string-callback-data-object-void-string","text":"Adding an event listeners returns a randomly generated UUIDv4 that is used to identify the listener. This UUID is required to remove a specific listener through the remove() method.","title":"add(identifier: string, action: string, callback: (data: Object) => void): string"},{"location":"javascript/new-api_events/#fireidentifier-string-action-string-data-object","text":"Triggers an event using an optional data object that is passed to each listener by reference.","title":"fire(identifier: string, action: string, data?: Object)"},{"location":"javascript/new-api_events/#removeidentifier-string-action-string-uuid-string","text":"Removes a previously registered event listener using the UUID returned by add() .","title":"remove(identifier: string, action: string, uuid: string)"},{"location":"javascript/new-api_events/#removeallidentifier-string-action-string","text":"Removes all event listeners registered for the provided identifier and action .","title":"removeAll(identifier: string, action: string)"},{"location":"javascript/new-api_events/#removeallbysuffixidentifier-string-suffix-string","text":"Removes all event listeners for an identifier whose action ends with the value of suffix .","title":"removeAllBySuffix(identifier: string, suffix: string)"},{"location":"javascript/new-api_ui/","text":"User Interface - JavaScript API # Ui/Alignment # Calculates the alignment of one element relative to another element, with support for boundary constraints, alignment restrictions and additional pointer elements. set(element: Element, referenceElement: Element, options: Object) # Calculates and sets the alignment of the element element . verticalOffset: number # Defaults to 0 . Creates a gap between the element and the reference element, in pixels. pointer: boolean # Defaults to false . Sets the position of the pointer element, requires an existing child of the element with the CSS class .elementPointer . pointerOffset: number # Defaults to 4 . The margin from the left/right edge of the element and is used to avoid the arrow from being placed right at the edge. Does not apply when aligning the element to the reference elemnent's center. pointerClassNames: string[] # Defaults to [] . If your element uses CSS-only pointers, such as using the ::before or ::after pseudo selectors, you can specifiy two separate CSS class names that control the alignment: pointerClassNames[0] is applied to the element when the pointer is displayed at the bottom. pointerClassNames[1] is used to align the pointer to the right side of the element. refDimensionsElement: Element # Defaults to null . An alternative element that will be used to determine the position and dimensions of the reference element. This can be useful if you reference element is contained in a wrapper element with alternating dimensions. horizontal: string # This value is automatically flipped for RTL (right-to-left) languages, left is changed into right and vice versa. Defaults to \"left\" . Sets the prefered alignment, accepts either left or right . The value left instructs the module to align the element with the left boundary of the reference element. The horizontal alignment is used as the default and a flip only occurs, if there is not enough space in the desired direction. If the element exceeds the boundaries in both directions, the value of horizontal is used. vertical: string # Defaults to \"bottom\" . Sets the prefered alignment, accepts either bottom or top . The value bottom instructs the module to align the element below the reference element. The vertical alignment is used as the default and a flip only occurs, if there is not enough space in the desired direction. If the element exceeds the boundaries in both directions, the value of vertical is used. allowFlip: string # The value for horizontal is automatically flipped for RTL (right-to-left) languages, left is changed into right and vice versa. This setting only controls the behavior when violating space constraints, therefore the aforementioned transformation is always applied. Defaults to \"both\" . Restricts the automatic alignment flipping if the element exceeds the window boundaries in the instructed direction. both - No restrictions. horizontal - Element can be aligned with the left or the right boundary of the reference element, but the vertical position is fixed. vertical - Element can be aligned below or above the reference element, but the vertical position is fixed. none - No flipping can occur, the element will be aligned regardless of any space constraints. Ui/CloseOverlay # Register elements that should be closed when the user clicks anywhere else, such as drop-down menus or tooltips. 1 2 3 4 5 require ([ \"Ui/CloseOverlay\" ], function ( UiCloseOverlay ) { UiCloseOverlay . add ( \"App/Foo\" , function () { // invoked, close something }); }); add(identifier: string, callback: () => void) # Adds a callback that will be invoked when the user clicks anywhere else. Ui/Confirmation # Prompt the user to make a decision before carrying out an action, such as a safety warning before permanently deleting content. 1 2 3 4 5 6 7 8 require ([ \"Ui/Confirmation\" ], function ( UiConfirmation ) { UiConfirmation . show ({ confirm : function () { // the user has confirmed the dialog }, message : \"Do you really want to continue?\" }); }); show(options: Object) # Displays a dialog overlay with actions buttons to confirm or reject the dialog. cancel: (parameters: Object) => void # Defaults to null . Callback that is invoked when the dialog was rejected. confirm: (parameters: Object) => void # Defaults to null . Callback that is invoked when the user has confirmed the dialog. message: string # Defaults to '\"\"'. Text that is displayed in the content area of the dialog, optionally this can be HTML, but this requires messageIsHtml to be enabled. messageIsHtml # Defaults to false . The message option is interpreted as text-only, setting this option to true will cause the message to be evaluated as HTML. parameters: Object # Optional list of parameter options that will be passed to the cancel() and confirm() callbacks. template: string # An optional HTML template that will be inserted into the dialog content area, but after the message section. Ui/Notification # Displays a simple notification at the very top of the window, such as a success message for Ajax based actions. 1 2 3 4 5 6 7 8 9 require ([ \"Ui/Notification\" ], function ( UiNotification ) { UiNotification . show ( \"Your changes have been saved.\" , function () { // this callback will be invoked after 2 seconds }, \"success\" ); }); show(message: string, callback?: () => void, cssClassName?: string) # Shows the notification and executes the callback after 2 seconds.","title":"User Interface"},{"location":"javascript/new-api_ui/#user-interface-javascript-api","text":"","title":"User Interface - JavaScript API"},{"location":"javascript/new-api_ui/#uialignment","text":"Calculates the alignment of one element relative to another element, with support for boundary constraints, alignment restrictions and additional pointer elements.","title":"Ui/Alignment"},{"location":"javascript/new-api_ui/#setelement-element-referenceelement-element-options-object","text":"Calculates and sets the alignment of the element element .","title":"set(element: Element, referenceElement: Element, options: Object)"},{"location":"javascript/new-api_ui/#verticaloffset-number","text":"Defaults to 0 . Creates a gap between the element and the reference element, in pixels.","title":"verticalOffset: number"},{"location":"javascript/new-api_ui/#pointer-boolean","text":"Defaults to false . Sets the position of the pointer element, requires an existing child of the element with the CSS class .elementPointer .","title":"pointer: boolean"},{"location":"javascript/new-api_ui/#pointeroffset-number","text":"Defaults to 4 . The margin from the left/right edge of the element and is used to avoid the arrow from being placed right at the edge. Does not apply when aligning the element to the reference elemnent's center.","title":"pointerOffset: number"},{"location":"javascript/new-api_ui/#pointerclassnames-string","text":"Defaults to [] . If your element uses CSS-only pointers, such as using the ::before or ::after pseudo selectors, you can specifiy two separate CSS class names that control the alignment: pointerClassNames[0] is applied to the element when the pointer is displayed at the bottom. pointerClassNames[1] is used to align the pointer to the right side of the element.","title":"pointerClassNames: string[]"},{"location":"javascript/new-api_ui/#refdimensionselement-element","text":"Defaults to null . An alternative element that will be used to determine the position and dimensions of the reference element. This can be useful if you reference element is contained in a wrapper element with alternating dimensions.","title":"refDimensionsElement: Element"},{"location":"javascript/new-api_ui/#horizontal-string","text":"This value is automatically flipped for RTL (right-to-left) languages, left is changed into right and vice versa. Defaults to \"left\" . Sets the prefered alignment, accepts either left or right . The value left instructs the module to align the element with the left boundary of the reference element. The horizontal alignment is used as the default and a flip only occurs, if there is not enough space in the desired direction. If the element exceeds the boundaries in both directions, the value of horizontal is used.","title":"horizontal: string"},{"location":"javascript/new-api_ui/#vertical-string","text":"Defaults to \"bottom\" . Sets the prefered alignment, accepts either bottom or top . The value bottom instructs the module to align the element below the reference element. The vertical alignment is used as the default and a flip only occurs, if there is not enough space in the desired direction. If the element exceeds the boundaries in both directions, the value of vertical is used.","title":"vertical: string"},{"location":"javascript/new-api_ui/#allowflip-string","text":"The value for horizontal is automatically flipped for RTL (right-to-left) languages, left is changed into right and vice versa. This setting only controls the behavior when violating space constraints, therefore the aforementioned transformation is always applied. Defaults to \"both\" . Restricts the automatic alignment flipping if the element exceeds the window boundaries in the instructed direction. both - No restrictions. horizontal - Element can be aligned with the left or the right boundary of the reference element, but the vertical position is fixed. vertical - Element can be aligned below or above the reference element, but the vertical position is fixed. none - No flipping can occur, the element will be aligned regardless of any space constraints.","title":"allowFlip: string"},{"location":"javascript/new-api_ui/#uicloseoverlay","text":"Register elements that should be closed when the user clicks anywhere else, such as drop-down menus or tooltips. 1 2 3 4 5 require ([ \"Ui/CloseOverlay\" ], function ( UiCloseOverlay ) { UiCloseOverlay . add ( \"App/Foo\" , function () { // invoked, close something }); });","title":"Ui/CloseOverlay"},{"location":"javascript/new-api_ui/#addidentifier-string-callback-void","text":"Adds a callback that will be invoked when the user clicks anywhere else.","title":"add(identifier: string, callback: () => void)"},{"location":"javascript/new-api_ui/#uiconfirmation","text":"Prompt the user to make a decision before carrying out an action, such as a safety warning before permanently deleting content. 1 2 3 4 5 6 7 8 require ([ \"Ui/Confirmation\" ], function ( UiConfirmation ) { UiConfirmation . show ({ confirm : function () { // the user has confirmed the dialog }, message : \"Do you really want to continue?\" }); });","title":"Ui/Confirmation"},{"location":"javascript/new-api_ui/#showoptions-object","text":"Displays a dialog overlay with actions buttons to confirm or reject the dialog.","title":"show(options: Object)"},{"location":"javascript/new-api_ui/#cancel-parameters-object-void","text":"Defaults to null . Callback that is invoked when the dialog was rejected.","title":"cancel: (parameters: Object) => void"},{"location":"javascript/new-api_ui/#confirm-parameters-object-void","text":"Defaults to null . Callback that is invoked when the user has confirmed the dialog.","title":"confirm: (parameters: Object) => void"},{"location":"javascript/new-api_ui/#message-string","text":"Defaults to '\"\"'. Text that is displayed in the content area of the dialog, optionally this can be HTML, but this requires messageIsHtml to be enabled.","title":"message: string"},{"location":"javascript/new-api_ui/#messageishtml","text":"Defaults to false . The message option is interpreted as text-only, setting this option to true will cause the message to be evaluated as HTML.","title":"messageIsHtml"},{"location":"javascript/new-api_ui/#parameters-object","text":"Optional list of parameter options that will be passed to the cancel() and confirm() callbacks.","title":"parameters: Object"},{"location":"javascript/new-api_ui/#template-string","text":"An optional HTML template that will be inserted into the dialog content area, but after the message section.","title":"template: string"},{"location":"javascript/new-api_ui/#uinotification","text":"Displays a simple notification at the very top of the window, such as a success message for Ajax based actions. 1 2 3 4 5 6 7 8 9 require ([ \"Ui/Notification\" ], function ( UiNotification ) { UiNotification . show ( \"Your changes have been saved.\" , function () { // this callback will be invoked after 2 seconds }, \"success\" ); });","title":"Ui/Notification"},{"location":"javascript/new-api_ui/#showmessage-string-callback-void-cssclassname-string","text":"Shows the notification and executes the callback after 2 seconds.","title":"show(message: string, callback?: () => void, cssClassName?: string)"},{"location":"javascript/new-api_writing-a-module/","text":"Writing a Module - JavaScript API # Introduction # The new JavaScript-API was introduced with WoltLab Suite 3.0 and was a major change in all regards. The previously used API heavily relied on larger JavaScript files that contained a lot of different components with hidden dependencies and suffered from extensive jQuery usage for historic reasons. Eventually a new API was designed that solves the issues with the legacy API by following a few basic principles: 1. Vanilla ES5-JavaScript. It allows us to achieve the best performance across all platforms, there is simply no reason to use jQuery today and the performance penalty on mobile devices is a real issue. 2. Strict usage of modules. Each component is placed in an own file and all dependencies are explicitly declared and injected at the top.Eventually we settled with AMD-style modules using require.js which offers both lazy loading and \"ahead of time\"-compilatio with r.js . 3. No jQuery-based components on page init. Nothing is more annoying than loading a page and then wait for JavaScript to modify the page before it becomes usable, forcing the user to sit and wait. Heavily optimized vanilla JavaScript components offered the speed we wanted. 4. Limited backwards-compatibility. The new API should make it easy to update existing components by providing similar interfaces, while still allowing legacy code to run side-by-side for best compatibility and to avoid rewritting everything from the start. Defining a Module # The default location for modules is js/ in the Core's app dir, but every app and plugin can register their own lookup path by providing the path using a template-listener on requirePaths@headIncludeJavaScript . For this example we'll assume the file is placed at js/WoltLabSuite/Core/Ui/Foo.js , the module name is therefore WoltLabSuite/Core/Ui/Foo , it is automatically derived from the file path and name. For further instructions on how to define and require modules head over to the RequireJS API . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 define ([ \"Ajax\" , \"WoltLabSuite/Core/Ui/Bar\" ], function ( Ajax , UiBar ) { \"use strict\" ; function Foo () { this . init (); } Foo . prototype = { init : function () { elBySel ( \".myButton\" ). addEventListener ( WCF_CLICK_EVENT , this . _click . bind ( this )); }, _click : function ( event ) { event . preventDefault (); if ( UiBar . isSnafucated ()) { Ajax . api ( this ); } }, _ajaxSuccess : function ( data ) { console . log ( \"Received response\" , data ); }, _ajaxSetup : function () { return { data : { actionName : \"makeSnafucated\" , className : \"wcf\\\\data\\\\foo\\\\FooAction\" } }; } } return Foo ; }); Loading a Module # Modules can then be loaded through their derived name: 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"WoltLabSuite/Core/Ui/Foo\" ], function ( UiFoo ) { new UiFoo (); }); </ script > Module Aliases # Some common modules have short-hand aliases that can be used to include them without writing out their full name. You can still use their original path, but it is strongly recommended to use the aliases for consistency. Alias Full Path Ajax WoltLabSuite/Core/Ajax AjaxJsonp WoltLabSuite/Core/Ajax/Jsonp AjaxRequest WoltLabSuite/Core/Ajax/Request CallbackList WoltLabSuite/Core/CallbackList ColorUtil WoltLabSuite/Core/ColorUtil Core WoltLabSuite/Core/Core DateUtil WoltLabSuite/Core/Date/Util Devtools WoltLabSuite/Core/Devtools Dictionary WoltLabSuite/Core/Dictionary Dom/ChangeListener WoltLabSuite/Core/Dom/Change/Listener Dom/Traverse WoltLabSuite/Core/Dom/Traverse Dom/Util WoltLabSuite/Core/Dom/Util Environment WoltLabSuite/Core/Environment EventHandler WoltLabSuite/Core/Event/Handler EventKey WoltLabSuite/Core/Event/Key Language WoltLabSuite/Core/Language List WoltLabSuite/Core/List ObjectMap WoltLabSuite/Core/ObjectMap Permission WoltLabSuite/Core/Permission StringUtil WoltLabSuite/Core/StringUtil Ui/Alignment WoltLabSuite/Core/Ui/Alignment Ui/CloseOverlay WoltLabSuite/Core/Ui/CloseOverlay Ui/Confirmation WoltLabSuite/Core/Ui/Confirmation Ui/Dialog WoltLabSuite/Core/Ui/Dialog Ui/Notification WoltLabSuite/Core/Ui/Notification Ui/ReusableDropdown WoltLabSuite/Core/Ui/Dropdown/Reusable Ui/Screen WoltLabSuite/Core/Ui/Screen Ui/Scroll WoltLabSuite/Core/Ui/Scroll Ui/SimpleDropdown WoltLabSuite/Core/Ui/Dropdown/Simple Ui/TabMenu WoltLabSuite/Core/Ui/TabMenu Upload WoltLabSuite/Core/Upload User WoltLabSuite/Core/User","title":"Writing a module"},{"location":"javascript/new-api_writing-a-module/#writing-a-module-javascript-api","text":"","title":"Writing a Module - JavaScript API"},{"location":"javascript/new-api_writing-a-module/#introduction","text":"The new JavaScript-API was introduced with WoltLab Suite 3.0 and was a major change in all regards. The previously used API heavily relied on larger JavaScript files that contained a lot of different components with hidden dependencies and suffered from extensive jQuery usage for historic reasons. Eventually a new API was designed that solves the issues with the legacy API by following a few basic principles: 1. Vanilla ES5-JavaScript. It allows us to achieve the best performance across all platforms, there is simply no reason to use jQuery today and the performance penalty on mobile devices is a real issue. 2. Strict usage of modules. Each component is placed in an own file and all dependencies are explicitly declared and injected at the top.Eventually we settled with AMD-style modules using require.js which offers both lazy loading and \"ahead of time\"-compilatio with r.js . 3. No jQuery-based components on page init. Nothing is more annoying than loading a page and then wait for JavaScript to modify the page before it becomes usable, forcing the user to sit and wait. Heavily optimized vanilla JavaScript components offered the speed we wanted. 4. Limited backwards-compatibility. The new API should make it easy to update existing components by providing similar interfaces, while still allowing legacy code to run side-by-side for best compatibility and to avoid rewritting everything from the start.","title":"Introduction"},{"location":"javascript/new-api_writing-a-module/#defining-a-module","text":"The default location for modules is js/ in the Core's app dir, but every app and plugin can register their own lookup path by providing the path using a template-listener on requirePaths@headIncludeJavaScript . For this example we'll assume the file is placed at js/WoltLabSuite/Core/Ui/Foo.js , the module name is therefore WoltLabSuite/Core/Ui/Foo , it is automatically derived from the file path and name. For further instructions on how to define and require modules head over to the RequireJS API . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 define ([ \"Ajax\" , \"WoltLabSuite/Core/Ui/Bar\" ], function ( Ajax , UiBar ) { \"use strict\" ; function Foo () { this . init (); } Foo . prototype = { init : function () { elBySel ( \".myButton\" ). addEventListener ( WCF_CLICK_EVENT , this . _click . bind ( this )); }, _click : function ( event ) { event . preventDefault (); if ( UiBar . isSnafucated ()) { Ajax . api ( this ); } }, _ajaxSuccess : function ( data ) { console . log ( \"Received response\" , data ); }, _ajaxSetup : function () { return { data : { actionName : \"makeSnafucated\" , className : \"wcf\\\\data\\\\foo\\\\FooAction\" } }; } } return Foo ; });","title":"Defining a Module"},{"location":"javascript/new-api_writing-a-module/#loading-a-module","text":"Modules can then be loaded through their derived name: 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"WoltLabSuite/Core/Ui/Foo\" ], function ( UiFoo ) { new UiFoo (); }); </ script >","title":"Loading a Module"},{"location":"javascript/new-api_writing-a-module/#module-aliases","text":"Some common modules have short-hand aliases that can be used to include them without writing out their full name. You can still use their original path, but it is strongly recommended to use the aliases for consistency. Alias Full Path Ajax WoltLabSuite/Core/Ajax AjaxJsonp WoltLabSuite/Core/Ajax/Jsonp AjaxRequest WoltLabSuite/Core/Ajax/Request CallbackList WoltLabSuite/Core/CallbackList ColorUtil WoltLabSuite/Core/ColorUtil Core WoltLabSuite/Core/Core DateUtil WoltLabSuite/Core/Date/Util Devtools WoltLabSuite/Core/Devtools Dictionary WoltLabSuite/Core/Dictionary Dom/ChangeListener WoltLabSuite/Core/Dom/Change/Listener Dom/Traverse WoltLabSuite/Core/Dom/Traverse Dom/Util WoltLabSuite/Core/Dom/Util Environment WoltLabSuite/Core/Environment EventHandler WoltLabSuite/Core/Event/Handler EventKey WoltLabSuite/Core/Event/Key Language WoltLabSuite/Core/Language List WoltLabSuite/Core/List ObjectMap WoltLabSuite/Core/ObjectMap Permission WoltLabSuite/Core/Permission StringUtil WoltLabSuite/Core/StringUtil Ui/Alignment WoltLabSuite/Core/Ui/Alignment Ui/CloseOverlay WoltLabSuite/Core/Ui/CloseOverlay Ui/Confirmation WoltLabSuite/Core/Ui/Confirmation Ui/Dialog WoltLabSuite/Core/Ui/Dialog Ui/Notification WoltLabSuite/Core/Ui/Notification Ui/ReusableDropdown WoltLabSuite/Core/Ui/Dropdown/Reusable Ui/Screen WoltLabSuite/Core/Ui/Screen Ui/Scroll WoltLabSuite/Core/Ui/Scroll Ui/SimpleDropdown WoltLabSuite/Core/Ui/Dropdown/Simple Ui/TabMenu WoltLabSuite/Core/Ui/TabMenu Upload WoltLabSuite/Core/Upload User WoltLabSuite/Core/User","title":"Module Aliases"},{"location":"javascript/typescript/","text":"TypeScript # Consuming WoltLab Suite\u2019s Types # To consume the types of WoltLab Suite, you will need to install the @woltlab/wcf npm package using a git URL that refers to the appropriate branch of WoltLab/WCF . A full package.json that includes WoltLab Suite, TypeScript, eslint and Prettier could look like the following. package.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 { \"devDependencies\" : { \"@typescript-eslint/eslint-plugin\" : \"^4.6.1\" , \"@typescript-eslint/parser\" : \"^4.6.1\" , \"eslint\" : \"^7.12.1\" , \"eslint-config-prettier\" : \"^6.15.0\" , \"prettier\" : \"^2.1.2\" , \"tslib\" : \"^2.0.3\" , \"typescript\" : \"^4.1.3\" }, \"dependencies\" : { \"@woltlab/wcf\" : \"https://github.com/WoltLab/WCF.git#master\" } } After installing the types using npm, you will also need to configure tsconfig.json to take the types into account. To do so, you will need to add them to the compilerOptions.paths option. A complete tsconfig.json file that matches the configuration of WoltLab Suite could look like the following. tsconfig.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 { \"include\" : [ \"node_modules/@woltlab/wcf/global.d.ts\" , \"ts/**/*\" ], \"compilerOptions\" : { \"target\" : \"es2017\" , \"module\" : \"amd\" , \"rootDir\" : \"ts/\" , \"outDir\" : \"files/js/\" , \"lib\" : [ \"dom\" , \"es2017\" ], \"strictNullChecks\" : true , \"moduleResolution\" : \"node\" , \"esModuleInterop\" : true , \"noImplicitThis\" : true , \"strictBindCallApply\" : true , \"baseUrl\" : \".\" , \"paths\" : { \"*\" : [ \"node_modules/@woltlab/wcf/ts/*\" ] }, \"importHelpers\" : true } } After this initial set-up, you would place your TypeScript source files into the ts/ folder of your project. The generated JavaScript target files will be placed into files/js/ and thus will be installed by the file PIP . Additional Tools # WoltLab Suite uses additional tools to ensure the high quality and a consistent code style of the TypeScript modules. The current configuration of these tools is as follows. It is recommended to re-use this configuration as is. .prettierrc 1 2 trailingComma: all printWidth: 120 .eslintrc.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 module . exports = { root : true , parser : \"@typescript-eslint/parser\" , parserOptions : { tsconfigRootDir : __dirname , project : [ \"./tsconfig.json\" ] }, plugins : [ \"@typescript-eslint\" ], extends : [ \"eslint:recommended\" , \"plugin:@typescript-eslint/recommended\" , \"plugin:@typescript-eslint/recommended-requiring-type-checking\" , \"prettier\" , \"prettier/@typescript-eslint\" ], rules : { \"@typescript-eslint/ban-types\" : [ \"error\" , { types : { \"object\" : false }, extendDefaults : true } ], \"@typescript-eslint/no-explicit-any\" : 0 , \"@typescript-eslint/no-non-null-assertion\" : 0 , \"@typescript-eslint/no-unsafe-assignment\" : 0 , \"@typescript-eslint/no-unsafe-call\" : 0 , \"@typescript-eslint/no-unsafe-member-access\" : 0 , \"@typescript-eslint/no-unsafe-return\" : 0 , \"@typescript-eslint/no-unused-vars\" : [ \"error\" , { \"argsIgnorePattern\" : \"^_\" } ] } }; .eslintignore 1 **/*.js This .gitattributes configuration will automatically collapse the generated JavaScript target files in GitHub\u2019s Diff view. You will not need it if you do not use git or GitHub. .gitattributes 1 files/js/**/*.js linguist-generated Writing a simple module # After completing this initial set-up you can start writing your first TypeScript module. The TypeScript compiler can be launched in Watch Mode by running npx tsc -w . WoltLab Suite\u2019s modules can be imported using the standard ECMAScript module import syntax by specifying the full module name. The public API of the module can also be exported using the standard ECMAScript module export syntax. ts/Example.ts 1 2 3 4 5 import * as Language from \"WoltLabSuite/Core/Language\" ; export function run () { alert ( Language . get ( \"wcf.foo.bar\" )); } This simple example module will compile to plain JavaScript that is compatible with the AMD loader that is used by WoltLab Suite. files/js/Example.js 1 2 3 4 5 6 7 8 9 10 define ([ \"require\" , \"exports\" , \"tslib\" , \"WoltLabSuite/Core/Language\" ], function ( require , exports , tslib_1 , Language ) { \"use strict\" ; Object . defineProperty ( exports , \"__esModule\" , { value : true }); exports . run = void 0 ; Language = tslib_1 . __importStar ( Language ); function run () { alert ( Language . get ( \"wcf.foo.bar\" )); } exports . run = run ; }); Within templates it can be consumed as follows. 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"Example\" ], ( Example ) => { Example . run (); // Alerts the contents of the `wcf.foo.bar` phrase. }); </ script >","title":"TypeScript"},{"location":"javascript/typescript/#typescript","text":"","title":"TypeScript"},{"location":"javascript/typescript/#consuming-woltlab-suites-types","text":"To consume the types of WoltLab Suite, you will need to install the @woltlab/wcf npm package using a git URL that refers to the appropriate branch of WoltLab/WCF . A full package.json that includes WoltLab Suite, TypeScript, eslint and Prettier could look like the following. package.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 { \"devDependencies\" : { \"@typescript-eslint/eslint-plugin\" : \"^4.6.1\" , \"@typescript-eslint/parser\" : \"^4.6.1\" , \"eslint\" : \"^7.12.1\" , \"eslint-config-prettier\" : \"^6.15.0\" , \"prettier\" : \"^2.1.2\" , \"tslib\" : \"^2.0.3\" , \"typescript\" : \"^4.1.3\" }, \"dependencies\" : { \"@woltlab/wcf\" : \"https://github.com/WoltLab/WCF.git#master\" } } After installing the types using npm, you will also need to configure tsconfig.json to take the types into account. To do so, you will need to add them to the compilerOptions.paths option. A complete tsconfig.json file that matches the configuration of WoltLab Suite could look like the following. tsconfig.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 { \"include\" : [ \"node_modules/@woltlab/wcf/global.d.ts\" , \"ts/**/*\" ], \"compilerOptions\" : { \"target\" : \"es2017\" , \"module\" : \"amd\" , \"rootDir\" : \"ts/\" , \"outDir\" : \"files/js/\" , \"lib\" : [ \"dom\" , \"es2017\" ], \"strictNullChecks\" : true , \"moduleResolution\" : \"node\" , \"esModuleInterop\" : true , \"noImplicitThis\" : true , \"strictBindCallApply\" : true , \"baseUrl\" : \".\" , \"paths\" : { \"*\" : [ \"node_modules/@woltlab/wcf/ts/*\" ] }, \"importHelpers\" : true } } After this initial set-up, you would place your TypeScript source files into the ts/ folder of your project. The generated JavaScript target files will be placed into files/js/ and thus will be installed by the file PIP .","title":"Consuming WoltLab Suite\u2019s Types"},{"location":"javascript/typescript/#additional-tools","text":"WoltLab Suite uses additional tools to ensure the high quality and a consistent code style of the TypeScript modules. The current configuration of these tools is as follows. It is recommended to re-use this configuration as is. .prettierrc 1 2 trailingComma: all printWidth: 120 .eslintrc.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 module . exports = { root : true , parser : \"@typescript-eslint/parser\" , parserOptions : { tsconfigRootDir : __dirname , project : [ \"./tsconfig.json\" ] }, plugins : [ \"@typescript-eslint\" ], extends : [ \"eslint:recommended\" , \"plugin:@typescript-eslint/recommended\" , \"plugin:@typescript-eslint/recommended-requiring-type-checking\" , \"prettier\" , \"prettier/@typescript-eslint\" ], rules : { \"@typescript-eslint/ban-types\" : [ \"error\" , { types : { \"object\" : false }, extendDefaults : true } ], \"@typescript-eslint/no-explicit-any\" : 0 , \"@typescript-eslint/no-non-null-assertion\" : 0 , \"@typescript-eslint/no-unsafe-assignment\" : 0 , \"@typescript-eslint/no-unsafe-call\" : 0 , \"@typescript-eslint/no-unsafe-member-access\" : 0 , \"@typescript-eslint/no-unsafe-return\" : 0 , \"@typescript-eslint/no-unused-vars\" : [ \"error\" , { \"argsIgnorePattern\" : \"^_\" } ] } }; .eslintignore 1 **/*.js This .gitattributes configuration will automatically collapse the generated JavaScript target files in GitHub\u2019s Diff view. You will not need it if you do not use git or GitHub. .gitattributes 1 files/js/**/*.js linguist-generated","title":"Additional Tools"},{"location":"javascript/typescript/#writing-a-simple-module","text":"After completing this initial set-up you can start writing your first TypeScript module. The TypeScript compiler can be launched in Watch Mode by running npx tsc -w . WoltLab Suite\u2019s modules can be imported using the standard ECMAScript module import syntax by specifying the full module name. The public API of the module can also be exported using the standard ECMAScript module export syntax. ts/Example.ts 1 2 3 4 5 import * as Language from \"WoltLabSuite/Core/Language\" ; export function run () { alert ( Language . get ( \"wcf.foo.bar\" )); } This simple example module will compile to plain JavaScript that is compatible with the AMD loader that is used by WoltLab Suite. files/js/Example.js 1 2 3 4 5 6 7 8 9 10 define ([ \"require\" , \"exports\" , \"tslib\" , \"WoltLabSuite/Core/Language\" ], function ( require , exports , tslib_1 , Language ) { \"use strict\" ; Object . defineProperty ( exports , \"__esModule\" , { value : true }); exports . run = void 0 ; Language = tslib_1 . __importStar ( Language ); function run () { alert ( Language . get ( \"wcf.foo.bar\" )); } exports . run = run ; }); Within templates it can be consumed as follows. 1 2 3 4 5 < script data-relocate = \"true\" > require ([ \"Example\" ], ( Example ) => { Example . run (); // Alerts the contents of the `wcf.foo.bar` phrase. }); </ script >","title":"Writing a simple module"},{"location":"migration/wcf21/css/","text":"WCF 2.1.x - CSS # The LESS compiler has been in use since WoltLab Community Framework 2.0, but was replaced with a SCSS compiler in WoltLab Suite 3.0. This change was motivated by SCSS becoming the de facto standard for CSS pre-processing and some really annoying shortcomings in the old LESS compiler. The entire CSS has been rewritten from scratch, please read the docs on CSS to learn what has changed.","title":"CSS"},{"location":"migration/wcf21/css/#wcf-21x-css","text":"The LESS compiler has been in use since WoltLab Community Framework 2.0, but was replaced with a SCSS compiler in WoltLab Suite 3.0. This change was motivated by SCSS becoming the de facto standard for CSS pre-processing and some really annoying shortcomings in the old LESS compiler. The entire CSS has been rewritten from scratch, please read the docs on CSS to learn what has changed.","title":"WCF 2.1.x - CSS"},{"location":"migration/wcf21/package/","text":"WCF 2.1.x - Package Components # package.xml # Short Instructions # Instructions can now omit the filename, causing them to use the default filename if defined by the package installation plugin (in short: PIP ). Unless overridden it will default to the PIP's class name with the first letter being lower-cased, e.g. EventListenerPackageInstallationPlugin implies the filename eventListener.xml . The file is always assumed to be in the archive's root, files located in subdirectories need to be explicitly stated, just as it worked before. Every PIP can define a custom filename if the default value cannot be properly derived. For example the ACPMenu -pip would default to aCPMenu.xml , requiring the class to explicitly override the default filename with acpMenu.xml for readability. Example # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <instructions type= \"install\" > <!-- assumes `eventListener.xml` --> <instruction type= \"eventListener\" /> <!-- assumes `install.sql` --> <instruction type= \"sql\" /> <!-- assumes `language/*.xml` --> <instruction type= \"language\" /> <!-- exceptions --> <!-- assumes `files.tar` --> <instruction type= \"file\" /> <!-- no default value, requires relative path --> <instruction type= \"script\" > acp/install_com.woltlab.wcf_3.0.php </instruction> </instructions> Exceptions # These exceptions represent the built-in PIPs only, 3rd party plugins and apps may define their own exceptions. PIP Default Value acpTemplate acptemplates.tar file files.tar language language/*.xml script (No default value) sql install.sql template templates.tar acpMenu.xml # Renamed Categories # The following categories have been renamed, menu items need to be adjusted to reflect the new names: Old Value New Value wcf.acp.menu.link.system wcf.acp.menu.link.configuration wcf.acp.menu.link.display wcf.acp.menu.link.customization wcf.acp.menu.link.community wcf.acp.menu.link.application Submenu Items # Menu items can now offer additional actions to be accessed from within the menu using an icon-based navigation. This step avoids filling the menu with dozens of Add \u2026 links, shifting the focus on to actual items. Adding more than one action is not recommended and you should at maximum specify two actions per item. Example # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <!-- category --> <acpmenuitem name= \"wcf.acp.menu.link.group\" > <parent> wcf.acp.menu.link.user </parent> <showorder> 2 </showorder> </acpmenuitem> <!-- menu item --> <acpmenuitem name= \"wcf.acp.menu.link.group.list\" > <controller> wcf\\acp\\page\\UserGroupListPage </controller> <parent> wcf.acp.menu.link.group </parent> <permissions> admin.user.canEditGroup,admin.user.canDeleteGroup </permissions> </acpmenuitem> <!-- menu item action --> <acpmenuitem name= \"wcf.acp.menu.link.group.add\" > <controller> wcf\\acp\\form\\UserGroupAddForm </controller> <!-- actions are defined by menu items of menu items --> <parent> wcf.acp.menu.link.group.list </parent> <permissions> admin.user.canAddGroup </permissions> <!-- required FontAwesome icon name used for display --> <icon> fa-plus </icon> </acpmenuitem> Common Icon Names # You should use the same icon names for the (logically) same task, unifying the meaning of items and making the actions predictable. Meaning Icon Name Result Add or create fa-plus Search fa-search Upload fa-upload box.xml # The box PIP has been added. cronjob.xml # Legacy cronjobs are assigned a non-deterministic generic name, the only way to assign them a name is removing them and then adding them again. Cronjobs can now be assigned a name using the name attribute as in <cronjob name=\"com.woltlab.wcf.refreshPackageUpdates\"> , it will be used to identify cronjobs during an update or delete. eventListener.xml # Legacy event listeners are assigned a non-deterministic generic name, the only way to assign them a name is removing them and then adding them again. Event listeners can now be assigned a name using the name attribute as in <eventlistener name=\"sessionPageAccessLog\"> , it will be used to identify event listeners during an update or delete. menu.xml # The menu PIP has been added. menuItem.xml # The menuItem PIP has been added. objectType.xml # The definition com.woltlab.wcf.user.dashboardContainer has been removed, it was previously used to register pages that qualify for dashboard boxes. Since WoltLab Suite 3.0, all pages registered through the page.xml are valid containers and therefore there is no need for this definition anymore. The definitions com.woltlab.wcf.page and com.woltlab.wcf.user.online.location have been superseded by the page.xml , they're no longer supported. option.xml # The module.display category has been renamed into module.customization . page.xml # The page PIP has been added. pageMenu.xml # The pageMenu.xml has been superseded by the page.xml and is no longer available.","title":"Package Components"},{"location":"migration/wcf21/package/#wcf-21x-package-components","text":"","title":"WCF 2.1.x - Package Components"},{"location":"migration/wcf21/package/#packagexml","text":"","title":"package.xml"},{"location":"migration/wcf21/package/#short-instructions","text":"Instructions can now omit the filename, causing them to use the default filename if defined by the package installation plugin (in short: PIP ). Unless overridden it will default to the PIP's class name with the first letter being lower-cased, e.g. EventListenerPackageInstallationPlugin implies the filename eventListener.xml . The file is always assumed to be in the archive's root, files located in subdirectories need to be explicitly stated, just as it worked before. Every PIP can define a custom filename if the default value cannot be properly derived. For example the ACPMenu -pip would default to aCPMenu.xml , requiring the class to explicitly override the default filename with acpMenu.xml for readability.","title":"Short Instructions"},{"location":"migration/wcf21/package/#example","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <instructions type= \"install\" > <!-- assumes `eventListener.xml` --> <instruction type= \"eventListener\" /> <!-- assumes `install.sql` --> <instruction type= \"sql\" /> <!-- assumes `language/*.xml` --> <instruction type= \"language\" /> <!-- exceptions --> <!-- assumes `files.tar` --> <instruction type= \"file\" /> <!-- no default value, requires relative path --> <instruction type= \"script\" > acp/install_com.woltlab.wcf_3.0.php </instruction> </instructions>","title":"Example"},{"location":"migration/wcf21/package/#exceptions","text":"These exceptions represent the built-in PIPs only, 3rd party plugins and apps may define their own exceptions. PIP Default Value acpTemplate acptemplates.tar file files.tar language language/*.xml script (No default value) sql install.sql template templates.tar","title":"Exceptions"},{"location":"migration/wcf21/package/#acpmenuxml","text":"","title":"acpMenu.xml"},{"location":"migration/wcf21/package/#renamed-categories","text":"The following categories have been renamed, menu items need to be adjusted to reflect the new names: Old Value New Value wcf.acp.menu.link.system wcf.acp.menu.link.configuration wcf.acp.menu.link.display wcf.acp.menu.link.customization wcf.acp.menu.link.community wcf.acp.menu.link.application","title":"Renamed Categories"},{"location":"migration/wcf21/package/#submenu-items","text":"Menu items can now offer additional actions to be accessed from within the menu using an icon-based navigation. This step avoids filling the menu with dozens of Add \u2026 links, shifting the focus on to actual items. Adding more than one action is not recommended and you should at maximum specify two actions per item.","title":"Submenu Items"},{"location":"migration/wcf21/package/#example_1","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <!-- category --> <acpmenuitem name= \"wcf.acp.menu.link.group\" > <parent> wcf.acp.menu.link.user </parent> <showorder> 2 </showorder> </acpmenuitem> <!-- menu item --> <acpmenuitem name= \"wcf.acp.menu.link.group.list\" > <controller> wcf\\acp\\page\\UserGroupListPage </controller> <parent> wcf.acp.menu.link.group </parent> <permissions> admin.user.canEditGroup,admin.user.canDeleteGroup </permissions> </acpmenuitem> <!-- menu item action --> <acpmenuitem name= \"wcf.acp.menu.link.group.add\" > <controller> wcf\\acp\\form\\UserGroupAddForm </controller> <!-- actions are defined by menu items of menu items --> <parent> wcf.acp.menu.link.group.list </parent> <permissions> admin.user.canAddGroup </permissions> <!-- required FontAwesome icon name used for display --> <icon> fa-plus </icon> </acpmenuitem>","title":"Example"},{"location":"migration/wcf21/package/#common-icon-names","text":"You should use the same icon names for the (logically) same task, unifying the meaning of items and making the actions predictable. Meaning Icon Name Result Add or create fa-plus Search fa-search Upload fa-upload","title":"Common Icon Names"},{"location":"migration/wcf21/package/#boxxml","text":"The box PIP has been added.","title":"box.xml"},{"location":"migration/wcf21/package/#cronjobxml","text":"Legacy cronjobs are assigned a non-deterministic generic name, the only way to assign them a name is removing them and then adding them again. Cronjobs can now be assigned a name using the name attribute as in <cronjob name=\"com.woltlab.wcf.refreshPackageUpdates\"> , it will be used to identify cronjobs during an update or delete.","title":"cronjob.xml"},{"location":"migration/wcf21/package/#eventlistenerxml","text":"Legacy event listeners are assigned a non-deterministic generic name, the only way to assign them a name is removing them and then adding them again. Event listeners can now be assigned a name using the name attribute as in <eventlistener name=\"sessionPageAccessLog\"> , it will be used to identify event listeners during an update or delete.","title":"eventListener.xml"},{"location":"migration/wcf21/package/#menuxml","text":"The menu PIP has been added.","title":"menu.xml"},{"location":"migration/wcf21/package/#menuitemxml","text":"The menuItem PIP has been added.","title":"menuItem.xml"},{"location":"migration/wcf21/package/#objecttypexml","text":"The definition com.woltlab.wcf.user.dashboardContainer has been removed, it was previously used to register pages that qualify for dashboard boxes. Since WoltLab Suite 3.0, all pages registered through the page.xml are valid containers and therefore there is no need for this definition anymore. The definitions com.woltlab.wcf.page and com.woltlab.wcf.user.online.location have been superseded by the page.xml , they're no longer supported.","title":"objectType.xml"},{"location":"migration/wcf21/package/#optionxml","text":"The module.display category has been renamed into module.customization .","title":"option.xml"},{"location":"migration/wcf21/package/#pagexml","text":"The page PIP has been added.","title":"page.xml"},{"location":"migration/wcf21/package/#pagemenuxml","text":"The pageMenu.xml has been superseded by the page.xml and is no longer available.","title":"pageMenu.xml"},{"location":"migration/wcf21/php/","text":"WCF 2.1.x - PHP # Message Processing # WoltLab Suite 3.0 finally made the transition from raw bbcode to bbcode-flavored HTML, with many new features related to message processing being added. This change impacts both message validation and storing, requiring slightly different APIs to get the job done. Input Processing for Storage # The returned HTML is an intermediate representation with a maximum of meta data embedded into it, designed to be stored in the database. Some bbcodes are replaced during this process, for example [b]\u2026[/b] becomes <strong>\u2026</strong> , while others are converted into a metacode tag for later processing. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $message , $messageObjectType , $messageObjectID ); $html = $processor -> getHtml (); The $messageObjectID can be zero if the element did not exist before, but it should be non-zero when saving an edited message. Embedded Objects # Embedded objects need to be registered after saving the message, but once again you can use the processor instance to do the job. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $message , $messageObjectType , $messageObjectID ); $html = $processor -> getHtml (); // at this point the message is saved to database and the created object // `$example` is a `DatabaseObject` with the id column `$exampleID` $processor -> setObjectID ( $example -> exampleID ); if ( \\wcf\\system\\message\\embedded\\object\\MessageEmbeddedObjectManager :: getInstance () -> registerObjects ( $processor )) { // there is at least one embedded object, this is also the point at which you // would set `hasEmbeddedObjects` to true (if implemented by your type) ( new \\wcf\\data\\example\\ExampleEditor ( $example )) -> update ([ 'hasEmbeddedObjects' => 1 ]); } Rendering the Message # The output processor will parse the intermediate HTML and finalize the output for display. This step is highly dynamic and allows for bbcode evaluation and contextual output based on the viewer's permissions. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> process ( $html , $messageObjectType , $messageObjectID ); $renderedHtml = $processor -> getHtml (); Simplified Output # At some point there can be the need of a simplified output HTML that includes only basic HTML formatting and reduces more sophisticated bbcodes into a simpler representation. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> setOutputType ( 'text/simplified-html' ); $processor -> process ( \u2026 ); Plaintext Output # The text/plain output type will strip down the simplified HTML into pure text, suitable for text-only output such as the plaintext representation of an email. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> setOutputType ( 'text/plain' ); $processor -> process ( \u2026 ); Rebuilding Data # Converting from BBCode # Enabling message conversion for HTML messages is undefined and yields unexpected results. Legacy message that still use raw bbcodes must be converted to be properly parsed by the html processors. This process is enabled by setting the fourth parameter of process() to true . 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $html , $messageObjectType , $messageObjectID , true ); $renderedHtml = $processor -> getHtml (); Extracting Embedded Objects # The process() method of the input processor is quite expensive, as it runs through the full message validation including the invocation of HTMLPurifier. This is perfectly fine when dealing with single messages, but when you're handling messages in bulk to extract their embedded objects, you're better of with processEmbeddedContent() . This method deconstructs the message, but skips all validation and expects the input to be perfectly valid, that is the output of a previous run of process() saved to storage. 1 2 3 4 5 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> processEmbeddedContent ( $html , $messageObjectType , $messageObjectID ); // invoke `MessageEmbeddedObjectManager::registerObjects` here Breadcrumbs / Page Location # Breadcrumbs used to be added left to right, but parent locations are added from the bottom to the top, starting with the first ancestor and going upwards. In most cases you simply need to reverse the order. Breadcrumbs used to be a lose collection of arbitrary links, but are now represented by actual page objects and the control has shifted over to the PageLocationManager . 1 2 3 4 5 6 <? php // before \\wcf\\system\\WCF :: getBreadcrumbs () -> add ( new \\wcf\\system\\breadcrumb\\Breadcrumb ( 'title' , 'link' )); // after \\wcf\\system\\page\\PageLocationManager :: getInstance () -> addParentLocation ( $pageIdentifier , $pageObjectID , $object ); Pages and Forms # The property $activeMenuItem has been deprecated for the front end and is no longer evaluated at runtime. Recognition of the active item is entirely based around the invoked controller class name and its definition in the page table. You need to properly register your pages for this feature to work. Search # ISearchableObjectType # Added the setLocation() method that is used to set the current page location based on the search result. SearchIndexManager # The methods SearchIndexManager::add() and SearchIndexManager::update() have been deprecated and forward their call to the new method SearchIndexManager::set() .","title":"PHP API"},{"location":"migration/wcf21/php/#wcf-21x-php","text":"","title":"WCF 2.1.x - PHP"},{"location":"migration/wcf21/php/#message-processing","text":"WoltLab Suite 3.0 finally made the transition from raw bbcode to bbcode-flavored HTML, with many new features related to message processing being added. This change impacts both message validation and storing, requiring slightly different APIs to get the job done.","title":"Message Processing"},{"location":"migration/wcf21/php/#input-processing-for-storage","text":"The returned HTML is an intermediate representation with a maximum of meta data embedded into it, designed to be stored in the database. Some bbcodes are replaced during this process, for example [b]\u2026[/b] becomes <strong>\u2026</strong> , while others are converted into a metacode tag for later processing. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $message , $messageObjectType , $messageObjectID ); $html = $processor -> getHtml (); The $messageObjectID can be zero if the element did not exist before, but it should be non-zero when saving an edited message.","title":"Input Processing for Storage"},{"location":"migration/wcf21/php/#embedded-objects","text":"Embedded objects need to be registered after saving the message, but once again you can use the processor instance to do the job. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $message , $messageObjectType , $messageObjectID ); $html = $processor -> getHtml (); // at this point the message is saved to database and the created object // `$example` is a `DatabaseObject` with the id column `$exampleID` $processor -> setObjectID ( $example -> exampleID ); if ( \\wcf\\system\\message\\embedded\\object\\MessageEmbeddedObjectManager :: getInstance () -> registerObjects ( $processor )) { // there is at least one embedded object, this is also the point at which you // would set `hasEmbeddedObjects` to true (if implemented by your type) ( new \\wcf\\data\\example\\ExampleEditor ( $example )) -> update ([ 'hasEmbeddedObjects' => 1 ]); }","title":"Embedded Objects"},{"location":"migration/wcf21/php/#rendering-the-message","text":"The output processor will parse the intermediate HTML and finalize the output for display. This step is highly dynamic and allows for bbcode evaluation and contextual output based on the viewer's permissions. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> process ( $html , $messageObjectType , $messageObjectID ); $renderedHtml = $processor -> getHtml ();","title":"Rendering the Message"},{"location":"migration/wcf21/php/#simplified-output","text":"At some point there can be the need of a simplified output HTML that includes only basic HTML formatting and reduces more sophisticated bbcodes into a simpler representation. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> setOutputType ( 'text/simplified-html' ); $processor -> process ( \u2026 );","title":"Simplified Output"},{"location":"migration/wcf21/php/#plaintext-output","text":"The text/plain output type will strip down the simplified HTML into pure text, suitable for text-only output such as the plaintext representation of an email. 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\output\\HtmlOutputProcessor (); $processor -> setOutputType ( 'text/plain' ); $processor -> process ( \u2026 );","title":"Plaintext Output"},{"location":"migration/wcf21/php/#rebuilding-data","text":"","title":"Rebuilding Data"},{"location":"migration/wcf21/php/#converting-from-bbcode","text":"Enabling message conversion for HTML messages is undefined and yields unexpected results. Legacy message that still use raw bbcodes must be converted to be properly parsed by the html processors. This process is enabled by setting the fourth parameter of process() to true . 1 2 3 4 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> process ( $html , $messageObjectType , $messageObjectID , true ); $renderedHtml = $processor -> getHtml ();","title":"Converting from BBCode"},{"location":"migration/wcf21/php/#extracting-embedded-objects","text":"The process() method of the input processor is quite expensive, as it runs through the full message validation including the invocation of HTMLPurifier. This is perfectly fine when dealing with single messages, but when you're handling messages in bulk to extract their embedded objects, you're better of with processEmbeddedContent() . This method deconstructs the message, but skips all validation and expects the input to be perfectly valid, that is the output of a previous run of process() saved to storage. 1 2 3 4 5 <? php $processor = new \\wcf\\system\\html\\input\\HtmlInputProcessor (); $processor -> processEmbeddedContent ( $html , $messageObjectType , $messageObjectID ); // invoke `MessageEmbeddedObjectManager::registerObjects` here","title":"Extracting Embedded Objects"},{"location":"migration/wcf21/php/#breadcrumbs-page-location","text":"Breadcrumbs used to be added left to right, but parent locations are added from the bottom to the top, starting with the first ancestor and going upwards. In most cases you simply need to reverse the order. Breadcrumbs used to be a lose collection of arbitrary links, but are now represented by actual page objects and the control has shifted over to the PageLocationManager . 1 2 3 4 5 6 <? php // before \\wcf\\system\\WCF :: getBreadcrumbs () -> add ( new \\wcf\\system\\breadcrumb\\Breadcrumb ( 'title' , 'link' )); // after \\wcf\\system\\page\\PageLocationManager :: getInstance () -> addParentLocation ( $pageIdentifier , $pageObjectID , $object );","title":"Breadcrumbs / Page Location"},{"location":"migration/wcf21/php/#pages-and-forms","text":"The property $activeMenuItem has been deprecated for the front end and is no longer evaluated at runtime. Recognition of the active item is entirely based around the invoked controller class name and its definition in the page table. You need to properly register your pages for this feature to work.","title":"Pages and Forms"},{"location":"migration/wcf21/php/#search","text":"","title":"Search"},{"location":"migration/wcf21/php/#isearchableobjecttype","text":"Added the setLocation() method that is used to set the current page location based on the search result.","title":"ISearchableObjectType"},{"location":"migration/wcf21/php/#searchindexmanager","text":"The methods SearchIndexManager::add() and SearchIndexManager::update() have been deprecated and forward their call to the new method SearchIndexManager::set() .","title":"SearchIndexManager"},{"location":"migration/wcf21/templates/","text":"WCF 2.1.x - Templates # Page Layout # The template structure has been overhauled and it is no longer required nor recommended to include internal templates, such as documentHeader , headInclude or userNotice . Instead use a simple {include file='header'} that now takes care of of the entire application frame. Templates must not include a trailing </body></html> after including the footer template. The documentHeader , headInclude and userNotice template should no longer be included manually, the same goes with the <body> element, please use {include file='header'} instead. The sidebarOrientation variable for the header template has been removed and no longer works. header.boxHeadline has been unified and now reads header.contentHeader Please see the full example at the end of this page for more information. Sidebars # Sidebars are now dynamically populated by the box system, this requires a small change to unify the markup. Additionally the usage of <fieldset> has been deprecated due to browser inconsistencies and bugs and should be replaced with section.box . Previous markup used in WoltLab Community Framework 2.1 and earlier: 1 2 3 4 5 6 7 < fieldset > < legend > <!-- Title --> </ legend > < div > <!-- Content --> </ div > </ fieldset > The new markup since WoltLab Suite 3.0: 1 2 3 4 5 6 7 < section class = \"box\" > < h2 class = \"boxTitle\" > <!-- Title --> </ h2 > < div class = \"boxContent\" > <!-- Content --> </ div > </ section > Forms # The input tag for session ids SID_INPUT_TAG has been deprecated and no longer yields any content, it can be safely removed. In previous versions forms have been wrapped in <div class=\"container containerPadding marginTop\">\u2026</div> which no longer has any effect and should be removed. If you're using the preview feature for WYSIWYG-powered input fields, you need to alter the preview button include instruction: 1 { include file = 'messageFormPreviewButton' previewMessageObjectType = 'com.example.foo.bar' previewMessageObjectID = 0 } The message object id should be non-zero when editing. Icons # The old .icon-<iconName> classes have been removed, you are required to use the official .fa-<iconName> class names from FontAwesome. This does not affect the generic classes .icon (indicates an icon) and .icon<size> (e.g. .icon16 that sets the dimensions), these are still required and have not been deprecated. Before: 1 < span class = \"icon icon16 icon-list\" > Now: 1 < span class = \"icon icon16 fa-list\" > Changed Icon Names # Quite a few icon names have been renamed, the official wiki lists the new icon names in FontAwesome 4. Changed Classes # .dataList has been replaced and should now read <ol class=\"inlineList commaSeparated\"> (same applies to <ul> ) .framedIconList has been changed into .userAvatarList Removed Elements and Classes # <nav class=\"jsClipboardEditor\"> and <div class=\"jsClipboardContainer\"> have been replaced with a floating button. The anchors a.toTopLink have been replaced with a floating button. Avatars should no longer receive the class framed The dl.condensed class, as seen in the editor tab menu, is no longer required. Anything related to sidebarCollapsed has been removed as sidebars are no longer collapsible. Simple Example # The code below includes only the absolute minimum required to display a page, the content title is already included in the output. 1 2 3 4 5 6 7 { include file = 'header' } <div class=\"section\"> Hello World! </div> { include file = 'footer' } Full Example # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 { * The page title is automatically set using the page definition, avoid setting it if you can! If you really need to modify the title, you can still reference the original title with: {$__wcf->getActivePage()->getTitle()} * } { capture assign = 'pageTitle' } Custom Page Title { /capture } { * NOTICE: The content header goes here, see the section after this to learn more. * } { * you must not use `headContent` for JavaScript * } { capture assign = 'headContent' } <link rel=\"alternate\" type=\"application/rss+xml\" title=\" { lang } wcf.global.button.rss { /lang } \" href=\"\u2026\"> { /capture } { * optional, content will be added to the top of the left sidebar * } { capture assign = 'sidebarLeft' } \u2026 { event name = 'boxes' } { /capture } { * optional, content will be added to the top of the right sidebar * } { capture assign = 'sidebarRight' } \u2026 { event name = 'boxes' } { /capture } { capture assign = 'headerNavigation' } <li><a href=\"#\" title=\"Custom Button\" class=\"jsTooltip\"><span class=\"icon icon16 fa-check\"></span> <span class=\"invisible\">Custom Button</span></a></li> { /capture } { include file = 'header' } { hascontent } <div class=\"paginationTop\"> { content } { pages \u2026 } { /content } </div> { /hascontent } { * the actual content * } <div class=\"section\"> \u2026 </div> <footer class=\"contentFooter\"> { * skip this if you're not using any pagination * } { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } <nav class=\"contentFooterNavigation\"> <ul> <li><a href=\"\u2026\" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span>Custom Button</span></a></li> { event name = 'contentFooterNavigation' } </ul> </nav> </footer> <script data-relocate=\"true\"> /* any JavaScript code you need */ </script> { * do not include `</body></html>` here, the footer template is the last bit of code! * } { include file = 'footer' } Content Header # There are two different methods to set the content header, one sets only the actual values, but leaves the outer HTML untouched, that is generated by the header template. This is the recommended approach and you should avoid using the alternative method whenever possible. Recommended Approach # 1 2 3 4 5 6 { * This is automatically set using the page data and should not be set manually! * } { capture assign = 'contentTitle' } Custom Content Title { /capture } { capture assign = 'contentDescription' } Optional description that is displayed right after the title. { /capture } { capture assign = 'contentHeaderNavigation' } List of navigation buttons displayed right next to the title. { /capture } Alternative # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { capture assign = 'contentHeader' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\">Custom Content Title</h1> <p class=\"contentHeaderDescription\">Custom Content Description</p> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'CustomController' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span>Custom Button</span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { /capture }","title":"Templates"},{"location":"migration/wcf21/templates/#wcf-21x-templates","text":"","title":"WCF 2.1.x - Templates"},{"location":"migration/wcf21/templates/#page-layout","text":"The template structure has been overhauled and it is no longer required nor recommended to include internal templates, such as documentHeader , headInclude or userNotice . Instead use a simple {include file='header'} that now takes care of of the entire application frame. Templates must not include a trailing </body></html> after including the footer template. The documentHeader , headInclude and userNotice template should no longer be included manually, the same goes with the <body> element, please use {include file='header'} instead. The sidebarOrientation variable for the header template has been removed and no longer works. header.boxHeadline has been unified and now reads header.contentHeader Please see the full example at the end of this page for more information.","title":"Page Layout"},{"location":"migration/wcf21/templates/#sidebars","text":"Sidebars are now dynamically populated by the box system, this requires a small change to unify the markup. Additionally the usage of <fieldset> has been deprecated due to browser inconsistencies and bugs and should be replaced with section.box . Previous markup used in WoltLab Community Framework 2.1 and earlier: 1 2 3 4 5 6 7 < fieldset > < legend > <!-- Title --> </ legend > < div > <!-- Content --> </ div > </ fieldset > The new markup since WoltLab Suite 3.0: 1 2 3 4 5 6 7 < section class = \"box\" > < h2 class = \"boxTitle\" > <!-- Title --> </ h2 > < div class = \"boxContent\" > <!-- Content --> </ div > </ section >","title":"Sidebars"},{"location":"migration/wcf21/templates/#forms","text":"The input tag for session ids SID_INPUT_TAG has been deprecated and no longer yields any content, it can be safely removed. In previous versions forms have been wrapped in <div class=\"container containerPadding marginTop\">\u2026</div> which no longer has any effect and should be removed. If you're using the preview feature for WYSIWYG-powered input fields, you need to alter the preview button include instruction: 1 { include file = 'messageFormPreviewButton' previewMessageObjectType = 'com.example.foo.bar' previewMessageObjectID = 0 } The message object id should be non-zero when editing.","title":"Forms"},{"location":"migration/wcf21/templates/#icons","text":"The old .icon-<iconName> classes have been removed, you are required to use the official .fa-<iconName> class names from FontAwesome. This does not affect the generic classes .icon (indicates an icon) and .icon<size> (e.g. .icon16 that sets the dimensions), these are still required and have not been deprecated. Before: 1 < span class = \"icon icon16 icon-list\" > Now: 1 < span class = \"icon icon16 fa-list\" >","title":"Icons"},{"location":"migration/wcf21/templates/#changed-icon-names","text":"Quite a few icon names have been renamed, the official wiki lists the new icon names in FontAwesome 4.","title":"Changed Icon Names"},{"location":"migration/wcf21/templates/#changed-classes","text":".dataList has been replaced and should now read <ol class=\"inlineList commaSeparated\"> (same applies to <ul> ) .framedIconList has been changed into .userAvatarList","title":"Changed Classes"},{"location":"migration/wcf21/templates/#removed-elements-and-classes","text":"<nav class=\"jsClipboardEditor\"> and <div class=\"jsClipboardContainer\"> have been replaced with a floating button. The anchors a.toTopLink have been replaced with a floating button. Avatars should no longer receive the class framed The dl.condensed class, as seen in the editor tab menu, is no longer required. Anything related to sidebarCollapsed has been removed as sidebars are no longer collapsible.","title":"Removed Elements and Classes"},{"location":"migration/wcf21/templates/#simple-example","text":"The code below includes only the absolute minimum required to display a page, the content title is already included in the output. 1 2 3 4 5 6 7 { include file = 'header' } <div class=\"section\"> Hello World! </div> { include file = 'footer' }","title":"Simple Example"},{"location":"migration/wcf21/templates/#full-example","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 { * The page title is automatically set using the page definition, avoid setting it if you can! If you really need to modify the title, you can still reference the original title with: {$__wcf->getActivePage()->getTitle()} * } { capture assign = 'pageTitle' } Custom Page Title { /capture } { * NOTICE: The content header goes here, see the section after this to learn more. * } { * you must not use `headContent` for JavaScript * } { capture assign = 'headContent' } <link rel=\"alternate\" type=\"application/rss+xml\" title=\" { lang } wcf.global.button.rss { /lang } \" href=\"\u2026\"> { /capture } { * optional, content will be added to the top of the left sidebar * } { capture assign = 'sidebarLeft' } \u2026 { event name = 'boxes' } { /capture } { * optional, content will be added to the top of the right sidebar * } { capture assign = 'sidebarRight' } \u2026 { event name = 'boxes' } { /capture } { capture assign = 'headerNavigation' } <li><a href=\"#\" title=\"Custom Button\" class=\"jsTooltip\"><span class=\"icon icon16 fa-check\"></span> <span class=\"invisible\">Custom Button</span></a></li> { /capture } { include file = 'header' } { hascontent } <div class=\"paginationTop\"> { content } { pages \u2026 } { /content } </div> { /hascontent } { * the actual content * } <div class=\"section\"> \u2026 </div> <footer class=\"contentFooter\"> { * skip this if you're not using any pagination * } { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } <nav class=\"contentFooterNavigation\"> <ul> <li><a href=\"\u2026\" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span>Custom Button</span></a></li> { event name = 'contentFooterNavigation' } </ul> </nav> </footer> <script data-relocate=\"true\"> /* any JavaScript code you need */ </script> { * do not include `</body></html>` here, the footer template is the last bit of code! * } { include file = 'footer' }","title":"Full Example"},{"location":"migration/wcf21/templates/#content-header","text":"There are two different methods to set the content header, one sets only the actual values, but leaves the outer HTML untouched, that is generated by the header template. This is the recommended approach and you should avoid using the alternative method whenever possible.","title":"Content Header"},{"location":"migration/wcf21/templates/#recommended-approach","text":"1 2 3 4 5 6 { * This is automatically set using the page data and should not be set manually! * } { capture assign = 'contentTitle' } Custom Content Title { /capture } { capture assign = 'contentDescription' } Optional description that is displayed right after the title. { /capture } { capture assign = 'contentHeaderNavigation' } List of navigation buttons displayed right next to the title. { /capture }","title":"Recommended Approach"},{"location":"migration/wcf21/templates/#alternative","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { capture assign = 'contentHeader' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\">Custom Content Title</h1> <p class=\"contentHeaderDescription\">Custom Content Description</p> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'CustomController' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span>Custom Button</span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { /capture }","title":"Alternative"},{"location":"migration/wsc30/css/","text":"Migrating from WSC 3.0 - CSS # New Style Variables # The new style variables are only applied to styles that have the compatibility set to WSC 3.1 wcfContentContainer # The page content is encapsulated in a new container that wraps around the inner content, but excludes the sidebars, header and page navigation elements. $wcfContentContainerBackground - background color $wcfContentContainerBorder - border color wcfEditorButton # These variables control the appearance of the editor toolbar and its buttons. $wcfEditorButtonBackground - button and toolbar background color $wcfEditorButtonBackgroundActive - active button background color $wcfEditorButtonText - text color for available buttons $wcfEditorButtonTextActive - text color for active buttons $wcfEditorButtonTextDisabled - text color for disabled buttons Color Variables in alert.scss # The color values for <small class=\"innerError\"> used to be hardcoded values, but have now been changed to use the values for error messages ( wcfStatusError* ) instead.","title":"CSS"},{"location":"migration/wsc30/css/#migrating-from-wsc-30-css","text":"","title":"Migrating from WSC 3.0 - CSS"},{"location":"migration/wsc30/css/#new-style-variables","text":"The new style variables are only applied to styles that have the compatibility set to WSC 3.1","title":"New Style Variables"},{"location":"migration/wsc30/css/#wcfcontentcontainer","text":"The page content is encapsulated in a new container that wraps around the inner content, but excludes the sidebars, header and page navigation elements. $wcfContentContainerBackground - background color $wcfContentContainerBorder - border color","title":"wcfContentContainer"},{"location":"migration/wsc30/css/#wcfeditorbutton","text":"These variables control the appearance of the editor toolbar and its buttons. $wcfEditorButtonBackground - button and toolbar background color $wcfEditorButtonBackgroundActive - active button background color $wcfEditorButtonText - text color for available buttons $wcfEditorButtonTextActive - text color for active buttons $wcfEditorButtonTextDisabled - text color for disabled buttons","title":"wcfEditorButton"},{"location":"migration/wsc30/css/#color-variables-in-alertscss","text":"The color values for <small class=\"innerError\"> used to be hardcoded values, but have now been changed to use the values for error messages ( wcfStatusError* ) instead.","title":"Color Variables in alert.scss"},{"location":"migration/wsc30/javascript/","text":"Migrating from WSC 3.0 - JavaScript # Accelerated Guest View / Tiny Builds # The new tiny builds are highly optimized variants of existing JavaScript files and modules, aiming for significant performance improvements for guests and search engines alike. This is accomplished by heavily restricting page interaction to read-only actions whenever possible, which in return removes the need to provide certain JavaScript modules in general. For example, disallowing guests to write any formatted messages will in return remove the need to provide the WYSIWYG editor at all. But it doesn't stop there, there are a lot of other modules that provide additional features for the editor, and by excluding the editor, we can also exclude these modules too. Long story short, the tiny mode guarantees that certain actions will never be carried out by guests or search engines, therefore some modules are not going to be needed by them ever. Code Templates for Tiny Builds # The following examples assume that you use the virtual constant COMPILER_TARGET_DEFAULT as a switch for the optimized code path. This is also the constant used by the official build scripts for JavaScript files . We recommend that you provide a mock implementation for existing code to ensure 3rd party compatibility. It is enough to provide a bare object or class that exposes the original properties using the same primitive data types. This is intended to provide a soft-fail for implementations that are not aware of the tiny mode yet, but is not required for classes that did not exist until now. Legacy JavaScript # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 if ( COMPILER_TARGET_DEFAULT ) { WCF . Example . Foo = { makeSnafucated : function () { return \"Hello World\" ; } }; WCF . Example . Bar = Class . extend ({ foobar : \"baz\" , foo : function ( $bar ) { return $bar + this . foobar ; } }); } else { WCF . Example . Foo = { makeSnafucated : function () {} }; WCF . Example . Bar = Class . extend ({ foobar : \"\" , foo : function () {} }); } require.js Modules # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 define ([ \"some\" , \"fancy\" , \"dependencies\" ], function ( Some , Fancy , Dependencies ) { \"use strict\" ; if ( ! COMPILER_TARGET_DEFAULT ) { var Fake = function () {}; Fake . prototype = { init : function () {}, makeSnafucated : function () {} }; return Fake ; } function MyAwesomeClass ( niceArgument ) { this . init ( niceArgument ); } MyAwesomeClass . prototype = { init : function ( niceArgument ) { if ( niceArgument ) { this . makeSnafucated (); } }, makeSnafucated : function () { console . log ( \"Hello World\" ); } } return MyAwesomeClass ; }); Including tinified builds through {js} # The {js} template-plugin has been updated to include support for tiny builds controlled through the optional flag hasTiny=true : 1 {js application='wcf' file='WCF.Example' hasTiny=true} This line generates a different output depending on the debug mode and the user login-state. Real Error Messages for AJAX Responses # The errorMessage property in the returned response object for failed AJAX requests contained an exception-specific but still highly generic error message. This issue has been around for quite a long time and countless of implementations are relying on this false behavior, eventually forcing us to leave the value unchanged. This problem is solved by adding the new property realErrorMessage that exposes the message exactly as it was provided and now matches the value that would be displayed to users in traditional forms. Example Code # 1 2 3 4 5 6 7 8 9 define ([ 'Ajax' ], function ( Ajax ) { return { // ... _ajaxFailure : function ( responseData , responseText , xhr , requestData ) { console . log ( responseData . realErrorMessage ); } // ... }; }); Simplified Form Submit in Dialogs # Forms embedded in dialogs often do not contain the HTML <form> -element and instead rely on JavaScript click- and key-handlers to emulate a <form> -like submit behavior. This has spawned a great amount of nearly identical implementations that all aim to handle the form submit through the Enter -key, still leaving some dialogs behind. WoltLab Suite 3.1 offers automatic form submit that is enabled through a set of specific conditions and data attributes: There must be a submit button that matches the selector .formSubmit > input[type=\"submit\"], .formSubmit > button[data-type=\"submit\"] . The dialog object provided to UiDialog.open() implements the method _dialogSubmit() . Input fields require the attribute data-dialog-submit-on-enter=\"true\" to be set, the type must be one of number , password , search , tel , text or url . Clicking on the submit button or pressing the Enter -key in any watched input field will start the submit process. This is done automatically and does not require a manual interaction in your code, therefore you should not bind any click listeners on the submit button yourself. Any input field with the required attribute set will be validated to contain a non-empty string after processing the value with String.prototype.trim() . An empty field will abort the submit process and display a visible error message next to the offending field. Helper Function for Inline Error Messages # Displaying inline error messages on-the-fly required quite a few DOM operations that were quite simple but also super repetitive and thus error-prone when incorrectly copied over. The global helper function elInnerError() was added to provide a simple and consistent behavior of inline error messages. You can display an error message by invoking elInnerError(elementRef, \"Your Error Message\") , it will insert a new <small class=\"innerError\"> and sets the given message. If there is already an inner error present, then the message will be replaced instead. Hiding messages is done by setting the 2nd parameter to false or an empty string: elInnerError(elementRef, false) elInnerError(elementRef, '') The special values null and undefined are supported too, but their usage is discouraged, because they make it harder to understand the intention by reading the code: elInnerError(elementRef, null) elInnerError(elementRef) Example Code # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 require ([ 'Language' ], function ( Language )) { var input = elBySel ( 'input[type=\"text\"]' ); if ( input . value . trim () === '' ) { // displays a new inline error or replaces the message if there is one already elInnerError ( input , Language . get ( 'wcf.global.form.error.empty' )); } else { // removes the inline error if it exists elInnerError ( input , false ); } // the above condition is equivalent to this: elInnerError ( input , ( input . value . trim () === '' ? Language . get ( 'wcf.global.form.error.empty' ) : false )); }","title":"JavaScript API"},{"location":"migration/wsc30/javascript/#migrating-from-wsc-30-javascript","text":"","title":"Migrating from WSC 3.0 - JavaScript"},{"location":"migration/wsc30/javascript/#accelerated-guest-view-tiny-builds","text":"The new tiny builds are highly optimized variants of existing JavaScript files and modules, aiming for significant performance improvements for guests and search engines alike. This is accomplished by heavily restricting page interaction to read-only actions whenever possible, which in return removes the need to provide certain JavaScript modules in general. For example, disallowing guests to write any formatted messages will in return remove the need to provide the WYSIWYG editor at all. But it doesn't stop there, there are a lot of other modules that provide additional features for the editor, and by excluding the editor, we can also exclude these modules too. Long story short, the tiny mode guarantees that certain actions will never be carried out by guests or search engines, therefore some modules are not going to be needed by them ever.","title":"Accelerated Guest View / Tiny Builds"},{"location":"migration/wsc30/javascript/#code-templates-for-tiny-builds","text":"The following examples assume that you use the virtual constant COMPILER_TARGET_DEFAULT as a switch for the optimized code path. This is also the constant used by the official build scripts for JavaScript files . We recommend that you provide a mock implementation for existing code to ensure 3rd party compatibility. It is enough to provide a bare object or class that exposes the original properties using the same primitive data types. This is intended to provide a soft-fail for implementations that are not aware of the tiny mode yet, but is not required for classes that did not exist until now.","title":"Code Templates for Tiny Builds"},{"location":"migration/wsc30/javascript/#legacy-javascript","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 if ( COMPILER_TARGET_DEFAULT ) { WCF . Example . Foo = { makeSnafucated : function () { return \"Hello World\" ; } }; WCF . Example . Bar = Class . extend ({ foobar : \"baz\" , foo : function ( $bar ) { return $bar + this . foobar ; } }); } else { WCF . Example . Foo = { makeSnafucated : function () {} }; WCF . Example . Bar = Class . extend ({ foobar : \"\" , foo : function () {} }); }","title":"Legacy JavaScript"},{"location":"migration/wsc30/javascript/#requirejs-modules","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 define ([ \"some\" , \"fancy\" , \"dependencies\" ], function ( Some , Fancy , Dependencies ) { \"use strict\" ; if ( ! COMPILER_TARGET_DEFAULT ) { var Fake = function () {}; Fake . prototype = { init : function () {}, makeSnafucated : function () {} }; return Fake ; } function MyAwesomeClass ( niceArgument ) { this . init ( niceArgument ); } MyAwesomeClass . prototype = { init : function ( niceArgument ) { if ( niceArgument ) { this . makeSnafucated (); } }, makeSnafucated : function () { console . log ( \"Hello World\" ); } } return MyAwesomeClass ; });","title":"require.js Modules"},{"location":"migration/wsc30/javascript/#including-tinified-builds-through-js","text":"The {js} template-plugin has been updated to include support for tiny builds controlled through the optional flag hasTiny=true : 1 {js application='wcf' file='WCF.Example' hasTiny=true} This line generates a different output depending on the debug mode and the user login-state.","title":"Including tinified builds through {js}"},{"location":"migration/wsc30/javascript/#real-error-messages-for-ajax-responses","text":"The errorMessage property in the returned response object for failed AJAX requests contained an exception-specific but still highly generic error message. This issue has been around for quite a long time and countless of implementations are relying on this false behavior, eventually forcing us to leave the value unchanged. This problem is solved by adding the new property realErrorMessage that exposes the message exactly as it was provided and now matches the value that would be displayed to users in traditional forms.","title":"Real Error Messages for AJAX Responses"},{"location":"migration/wsc30/javascript/#example-code","text":"1 2 3 4 5 6 7 8 9 define ([ 'Ajax' ], function ( Ajax ) { return { // ... _ajaxFailure : function ( responseData , responseText , xhr , requestData ) { console . log ( responseData . realErrorMessage ); } // ... }; });","title":"Example Code"},{"location":"migration/wsc30/javascript/#simplified-form-submit-in-dialogs","text":"Forms embedded in dialogs often do not contain the HTML <form> -element and instead rely on JavaScript click- and key-handlers to emulate a <form> -like submit behavior. This has spawned a great amount of nearly identical implementations that all aim to handle the form submit through the Enter -key, still leaving some dialogs behind. WoltLab Suite 3.1 offers automatic form submit that is enabled through a set of specific conditions and data attributes: There must be a submit button that matches the selector .formSubmit > input[type=\"submit\"], .formSubmit > button[data-type=\"submit\"] . The dialog object provided to UiDialog.open() implements the method _dialogSubmit() . Input fields require the attribute data-dialog-submit-on-enter=\"true\" to be set, the type must be one of number , password , search , tel , text or url . Clicking on the submit button or pressing the Enter -key in any watched input field will start the submit process. This is done automatically and does not require a manual interaction in your code, therefore you should not bind any click listeners on the submit button yourself. Any input field with the required attribute set will be validated to contain a non-empty string after processing the value with String.prototype.trim() . An empty field will abort the submit process and display a visible error message next to the offending field.","title":"Simplified Form Submit in Dialogs"},{"location":"migration/wsc30/javascript/#helper-function-for-inline-error-messages","text":"Displaying inline error messages on-the-fly required quite a few DOM operations that were quite simple but also super repetitive and thus error-prone when incorrectly copied over. The global helper function elInnerError() was added to provide a simple and consistent behavior of inline error messages. You can display an error message by invoking elInnerError(elementRef, \"Your Error Message\") , it will insert a new <small class=\"innerError\"> and sets the given message. If there is already an inner error present, then the message will be replaced instead. Hiding messages is done by setting the 2nd parameter to false or an empty string: elInnerError(elementRef, false) elInnerError(elementRef, '') The special values null and undefined are supported too, but their usage is discouraged, because they make it harder to understand the intention by reading the code: elInnerError(elementRef, null) elInnerError(elementRef)","title":"Helper Function for Inline Error Messages"},{"location":"migration/wsc30/javascript/#example-code_1","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 require ([ 'Language' ], function ( Language )) { var input = elBySel ( 'input[type=\"text\"]' ); if ( input . value . trim () === '' ) { // displays a new inline error or replaces the message if there is one already elInnerError ( input , Language . get ( 'wcf.global.form.error.empty' )); } else { // removes the inline error if it exists elInnerError ( input , false ); } // the above condition is equivalent to this: elInnerError ( input , ( input . value . trim () === '' ? Language . get ( 'wcf.global.form.error.empty' ) : false )); }","title":"Example Code"},{"location":"migration/wsc30/package/","text":"Migrating from WSC 3.0 - Package Components # Cronjob Scheduler uses Server Timezone # The execution time of cronjobs was previously calculated based on the coordinated universal time (UTC). This was changed in WoltLab Suite 3.1 to use the server timezone or, to be precise, the default timezone set in the administration control panel. Exclude Pages from becoming a Landing Page # Some pages do not qualify as landing page, because they're designed around specific expectations that aren't matched in all cases. Examples include the user control panel and its sub-pages that cannot be accessed by guests and will therefore break the landing page for those. While it is somewhat to be expected from control panel pages, there are enough pages that fall under the same restrictions, but aren't easily recognized as such by an administrator. You can exclude these pages by adding <excludeFromLandingPage>1</excludeFromLandingPage> (case-sensitive) to the relevant pages in your page.xml . Example Code # 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/tornado/page.xsd\" > <import> <page identifier= \"com.example.foo.Bar\" > <!-- ... --> <excludeFromLandingPage> 1 </excludeFromLandingPage> <!-- ... --> </page> </import> </data> New Package Installation Plugin for Media Providers # Please refer to the documentation of the mediaProvider.xml to learn more. Limited Forward-Compatibility for Plugins # Please refer to the documentation of the <compatibility> tag in the package.xml .","title":"Package Components"},{"location":"migration/wsc30/package/#migrating-from-wsc-30-package-components","text":"","title":"Migrating from WSC 3.0 - Package Components"},{"location":"migration/wsc30/package/#cronjob-scheduler-uses-server-timezone","text":"The execution time of cronjobs was previously calculated based on the coordinated universal time (UTC). This was changed in WoltLab Suite 3.1 to use the server timezone or, to be precise, the default timezone set in the administration control panel.","title":"Cronjob Scheduler uses Server Timezone"},{"location":"migration/wsc30/package/#exclude-pages-from-becoming-a-landing-page","text":"Some pages do not qualify as landing page, because they're designed around specific expectations that aren't matched in all cases. Examples include the user control panel and its sub-pages that cannot be accessed by guests and will therefore break the landing page for those. While it is somewhat to be expected from control panel pages, there are enough pages that fall under the same restrictions, but aren't easily recognized as such by an administrator. You can exclude these pages by adding <excludeFromLandingPage>1</excludeFromLandingPage> (case-sensitive) to the relevant pages in your page.xml .","title":"Exclude Pages from becoming a Landing Page"},{"location":"migration/wsc30/package/#example-code","text":"1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/tornado/page.xsd\" > <import> <page identifier= \"com.example.foo.Bar\" > <!-- ... --> <excludeFromLandingPage> 1 </excludeFromLandingPage> <!-- ... --> </page> </import> </data>","title":"Example Code"},{"location":"migration/wsc30/package/#new-package-installation-plugin-for-media-providers","text":"Please refer to the documentation of the mediaProvider.xml to learn more.","title":"New Package Installation Plugin for Media Providers"},{"location":"migration/wsc30/package/#limited-forward-compatibility-for-plugins","text":"Please refer to the documentation of the <compatibility> tag in the package.xml .","title":"Limited Forward-Compatibility for Plugins"},{"location":"migration/wsc30/php/","text":"Migrating from WSC 3.0 - PHP # Approval-System for Comments # Comments can now be set to require approval by a moderator before being published. This feature is disabled by default if you do not provide a permission in the manager class, enabling it requires a new permission that has to be provided in a special property of your manage implementation. files/lib/system/comment/manager/ExampleCommentManager.class.php 1 2 3 4 <? php class ExampleCommentManager extends AbstractCommentManager { protected $permissionAddWithoutModeration = 'foo.bar.example.canAddCommentWithoutModeration' ; } Raw HTML in User Activity Events # User activity events were previously encapsulated inside <div class=\"htmlContent\">\u2026</div> , with impacts on native elements such as lists. You can now disable the class usage by defining your event as raw HTML: files/lib/system/user/activity/event/ExampleUserActivityEvent.class.php 1 2 3 4 5 <? php class ExampleUserActivityEvent { // enables raw HTML for output, defaults to `false` protected $isRawHtml = true ; } Permission to View Likes of an Object # Being able to view the like summary of an object was restricted to users that were able to like the object itself. This creates situations where the object type in general is likable, but the particular object cannot be liked by the current users, while also denying them to view the like summary (but it gets partly exposed through the footer note/summary!). Implement the interface \\wcf\\data\\like\\IRestrictedLikeObjectTypeProvider in your object provider to add support for this new permission check. files/lib/data/example/LikeableExampleProvider.class.php 1 2 3 4 5 6 7 <? php class LikeableExampleProvider extends ExampleProvider implements IRestrictedLikeObjectTypeProvider , IViewableLikeProvider { public function canViewLikes ( ILikeObject $object ) { // perform your permission checks here return true ; } } Developer Tools: Sync Feature # The synchronization feature of the newly added developer tools works by invoking a package installation plugin (PIP) outside of a regular installation, while simulating the basic environment that is already exposed by the API. However, not all PIPs qualify for this kind of execution, especially because it could be invoked multiple times in a row by the user. This is solved by requiring a special marking for PIPs that have no side-effects (= idempotent) when invoked any amount of times with the same arguments. There's another feature that allows all matching PIPs to be executed in a row using a single button click. In order to solve dependencies on other PIPs, any implementing PIP must also provide the method getSyncDependencies() that returns the dependent PIPs in an arbitrary order. files/lib/data/package/plugin/ExamplePackageInstallationPlugin.class.php 1 2 3 4 5 6 7 <? php class ExamplePackageInstallationPlugin extends AbstractXMLPackageInstallationPlugin implements IIdempotentPackageInstallationPlugin { public static function getSyncDependencies () { // provide a list of dependent PIPs in arbitrary order return []; } } Media Providers # Media providers were added through regular SQL queries in earlier versions, but this is neither convenient, nor did it offer a reliable method to update an existing provider. WoltLab Suite 3.1 adds a new mediaProvider -PIP that also offers a className parameter to off-load the result evaluation and HTML generation. Example Implementation # mediaProvider.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/tornado/mediaProvider.xsd\" > <import> <provider name= \"example\" > <title> Example Provider </title> <regex> https?://example.com/watch?v=(?P <ID> [a-zA-Z0-9]) </regex> <className> wcf\\system\\bbcode\\media\\provider\\ExampleBBCodeMediaProvider </className> </provider> </import> </data> PHP Callback # The full match is provided for $url , while any capture groups from the regular expression are assigned to $matches . 1 2 3 4 5 6 <? php class ExampleBBCodeMediaProvider implements IBBCodeMediaProvider { public function parse ( $url , array $matches = []) { return \"final HTML output\" ; } } Re-Evaluate HTML Messages # You need to manually set the disallowed bbcodes in order to avoid unintentional bbcode evaluation. Please see this commit for a reference implementation inside worker processes. The HtmlInputProcessor only supported two ways to handle an existing HTML message: Load the string through process() and run it through the validation and sanitation process, both of them are rather expensive operations and do not qualify for rebuild data workers. Detect embedded content using processEmbeddedContent() which bypasses most tasks that are carried out by process() which aren't required, but does not allow a modification of the message. The newly added method reprocess($message, $objectType, $objectID) solves this short-coming by offering a full bbcode and text re-evaluation while bypassing any input filters, assuming that the input HTML was already filtered previously. Example Usage # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php // rebuild data workers tend to contain code similar to this: foreach ( $this -> objectList as $message ) { // ... if ( ! $message -> enableHtml ) { // ... } else { // OLD: $this -> getHtmlInputProcessor () -> processEmbeddedContent ( $message -> message , 'com.example.foo.message' , $message -> messageID ); // REPLACE WITH: $this -> getHtmlInputProcessor () -> reprocess ( $message -> message , 'com.example.foo.message' , $message -> messageID ); $data [ 'message' ] = $this -> getHtmlInputProcessor () -> getHtml (); } // ... }","title":"PHP API"},{"location":"migration/wsc30/php/#migrating-from-wsc-30-php","text":"","title":"Migrating from WSC 3.0 - PHP"},{"location":"migration/wsc30/php/#approval-system-for-comments","text":"Comments can now be set to require approval by a moderator before being published. This feature is disabled by default if you do not provide a permission in the manager class, enabling it requires a new permission that has to be provided in a special property of your manage implementation. files/lib/system/comment/manager/ExampleCommentManager.class.php 1 2 3 4 <? php class ExampleCommentManager extends AbstractCommentManager { protected $permissionAddWithoutModeration = 'foo.bar.example.canAddCommentWithoutModeration' ; }","title":"Approval-System for Comments"},{"location":"migration/wsc30/php/#raw-html-in-user-activity-events","text":"User activity events were previously encapsulated inside <div class=\"htmlContent\">\u2026</div> , with impacts on native elements such as lists. You can now disable the class usage by defining your event as raw HTML: files/lib/system/user/activity/event/ExampleUserActivityEvent.class.php 1 2 3 4 5 <? php class ExampleUserActivityEvent { // enables raw HTML for output, defaults to `false` protected $isRawHtml = true ; }","title":"Raw HTML in User Activity Events"},{"location":"migration/wsc30/php/#permission-to-view-likes-of-an-object","text":"Being able to view the like summary of an object was restricted to users that were able to like the object itself. This creates situations where the object type in general is likable, but the particular object cannot be liked by the current users, while also denying them to view the like summary (but it gets partly exposed through the footer note/summary!). Implement the interface \\wcf\\data\\like\\IRestrictedLikeObjectTypeProvider in your object provider to add support for this new permission check. files/lib/data/example/LikeableExampleProvider.class.php 1 2 3 4 5 6 7 <? php class LikeableExampleProvider extends ExampleProvider implements IRestrictedLikeObjectTypeProvider , IViewableLikeProvider { public function canViewLikes ( ILikeObject $object ) { // perform your permission checks here return true ; } }","title":"Permission to View Likes of an Object"},{"location":"migration/wsc30/php/#developer-tools-sync-feature","text":"The synchronization feature of the newly added developer tools works by invoking a package installation plugin (PIP) outside of a regular installation, while simulating the basic environment that is already exposed by the API. However, not all PIPs qualify for this kind of execution, especially because it could be invoked multiple times in a row by the user. This is solved by requiring a special marking for PIPs that have no side-effects (= idempotent) when invoked any amount of times with the same arguments. There's another feature that allows all matching PIPs to be executed in a row using a single button click. In order to solve dependencies on other PIPs, any implementing PIP must also provide the method getSyncDependencies() that returns the dependent PIPs in an arbitrary order. files/lib/data/package/plugin/ExamplePackageInstallationPlugin.class.php 1 2 3 4 5 6 7 <? php class ExamplePackageInstallationPlugin extends AbstractXMLPackageInstallationPlugin implements IIdempotentPackageInstallationPlugin { public static function getSyncDependencies () { // provide a list of dependent PIPs in arbitrary order return []; } }","title":"Developer Tools: Sync Feature"},{"location":"migration/wsc30/php/#media-providers","text":"Media providers were added through regular SQL queries in earlier versions, but this is neither convenient, nor did it offer a reliable method to update an existing provider. WoltLab Suite 3.1 adds a new mediaProvider -PIP that also offers a className parameter to off-load the result evaluation and HTML generation.","title":"Media Providers"},{"location":"migration/wsc30/php/#example-implementation","text":"mediaProvider.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/tornado/mediaProvider.xsd\" > <import> <provider name= \"example\" > <title> Example Provider </title> <regex> https?://example.com/watch?v=(?P <ID> [a-zA-Z0-9]) </regex> <className> wcf\\system\\bbcode\\media\\provider\\ExampleBBCodeMediaProvider </className> </provider> </import> </data>","title":"Example Implementation"},{"location":"migration/wsc30/php/#php-callback","text":"The full match is provided for $url , while any capture groups from the regular expression are assigned to $matches . 1 2 3 4 5 6 <? php class ExampleBBCodeMediaProvider implements IBBCodeMediaProvider { public function parse ( $url , array $matches = []) { return \"final HTML output\" ; } }","title":"PHP Callback"},{"location":"migration/wsc30/php/#re-evaluate-html-messages","text":"You need to manually set the disallowed bbcodes in order to avoid unintentional bbcode evaluation. Please see this commit for a reference implementation inside worker processes. The HtmlInputProcessor only supported two ways to handle an existing HTML message: Load the string through process() and run it through the validation and sanitation process, both of them are rather expensive operations and do not qualify for rebuild data workers. Detect embedded content using processEmbeddedContent() which bypasses most tasks that are carried out by process() which aren't required, but does not allow a modification of the message. The newly added method reprocess($message, $objectType, $objectID) solves this short-coming by offering a full bbcode and text re-evaluation while bypassing any input filters, assuming that the input HTML was already filtered previously.","title":"Re-Evaluate HTML Messages"},{"location":"migration/wsc30/php/#example-usage","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php // rebuild data workers tend to contain code similar to this: foreach ( $this -> objectList as $message ) { // ... if ( ! $message -> enableHtml ) { // ... } else { // OLD: $this -> getHtmlInputProcessor () -> processEmbeddedContent ( $message -> message , 'com.example.foo.message' , $message -> messageID ); // REPLACE WITH: $this -> getHtmlInputProcessor () -> reprocess ( $message -> message , 'com.example.foo.message' , $message -> messageID ); $data [ 'message' ] = $this -> getHtmlInputProcessor () -> getHtml (); } // ... }","title":"Example Usage"},{"location":"migration/wsc30/templates/","text":"Migrating from WSC 3.0 - Templates # Comment-System Overhaul # Unfortunately, there has been a breaking change related to the creation of comments. You need to apply the changes below before being able to create new comments. Adding Comments # Existing implementations need to include a new template right before including the generic commentList template. 1 2 3 4 < ul id = \"exampleCommentList\" class = \"commentList containerList\" data- ... > {include file='commentListAddComment' wysiwygSelector='exampleCommentListAddComment'} {include file='commentList'} </ ul > Redesigned ACP User List # Custom interaction buttons were previously added through the template event rowButtons and were merely a link-like element with an icon inside. This is still valid and supported for backwards-compatibility, but it is recommend to adapt to the new drop-down-style options using the new template event dropdownItems . 1 2 3 4 5 <!-- button for usage with the `rowButtons` event --> < span class = \"icon icon16 fa-list jsTooltip\" title = \"Button Title\" ></ span > <!-- new drop-down item for the `dropdownItems` event --> < li >< a href = \"#\" class = \"jsMyButton\" > Button Title </ a ></ li > Sidebar Toogle-Buttons on Mobile Device # You cannot override the button label for sidebars containing navigation menus. The page sidebars are automatically collapsed and presented as one or, when both sidebar are present, two condensed buttons. They use generic sidebar-related labels when open or closed, with the exception of embedded menus which will change the button label to read \"Show/Hide Navigation\". You can provide a custom label before including the sidebars by assigning the new labels to a few special variables: 1 2 3 4 {assign var='__sidebarLeftShow' value='Show Left Sidebar'} {assign var='__sidebarLeftHide' value='Hide Left Sidebar'} {assign var='__sidebarRightShow' value='Show Right Sidebar'} {assign var='__sidebarRightHide' value='Hide Right Sidebar'}","title":"Templates"},{"location":"migration/wsc30/templates/#migrating-from-wsc-30-templates","text":"","title":"Migrating from WSC 3.0 - Templates"},{"location":"migration/wsc30/templates/#comment-system-overhaul","text":"Unfortunately, there has been a breaking change related to the creation of comments. You need to apply the changes below before being able to create new comments.","title":"Comment-System Overhaul"},{"location":"migration/wsc30/templates/#adding-comments","text":"Existing implementations need to include a new template right before including the generic commentList template. 1 2 3 4 < ul id = \"exampleCommentList\" class = \"commentList containerList\" data- ... > {include file='commentListAddComment' wysiwygSelector='exampleCommentListAddComment'} {include file='commentList'} </ ul >","title":"Adding Comments"},{"location":"migration/wsc30/templates/#redesigned-acp-user-list","text":"Custom interaction buttons were previously added through the template event rowButtons and were merely a link-like element with an icon inside. This is still valid and supported for backwards-compatibility, but it is recommend to adapt to the new drop-down-style options using the new template event dropdownItems . 1 2 3 4 5 <!-- button for usage with the `rowButtons` event --> < span class = \"icon icon16 fa-list jsTooltip\" title = \"Button Title\" ></ span > <!-- new drop-down item for the `dropdownItems` event --> < li >< a href = \"#\" class = \"jsMyButton\" > Button Title </ a ></ li >","title":"Redesigned ACP User List"},{"location":"migration/wsc30/templates/#sidebar-toogle-buttons-on-mobile-device","text":"You cannot override the button label for sidebars containing navigation menus. The page sidebars are automatically collapsed and presented as one or, when both sidebar are present, two condensed buttons. They use generic sidebar-related labels when open or closed, with the exception of embedded menus which will change the button label to read \"Show/Hide Navigation\". You can provide a custom label before including the sidebars by assigning the new labels to a few special variables: 1 2 3 4 {assign var='__sidebarLeftShow' value='Show Left Sidebar'} {assign var='__sidebarLeftHide' value='Hide Left Sidebar'} {assign var='__sidebarRightShow' value='Show Right Sidebar'} {assign var='__sidebarRightHide' value='Hide Right Sidebar'}","title":"Sidebar Toogle-Buttons on Mobile Device"},{"location":"migration/wsc31/form-builder/","text":"Migrating from WSC 3.1 - Form Builder # Example: Two Text Form Fields # As the first example, the pre-WoltLab Suite Core 5.2 versions of the forms to add and edit persons from the first part of the tutorial series will be updated to the new form builder API. This form is the perfect first examples as it is very simple with only two text fields whose only restriction is that they have to be filled out and that their values may not be longer than 255 characters each. As a reminder, here are the two relevant PHP files and the relevant template file: files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractForm ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\WCF ; use wcf\\util\\StringUtil ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * first name of the person * @var string */ public $firstName = '' ; /** * last name of the person * @var string */ public $lastName = '' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'action' => 'add' , 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]); } /** * @inheritDoc */ public function readFormParameters () { parent :: readFormParameters (); if ( isset ( $_POST [ 'firstName' ])) $this -> firstName = StringUtil :: trim ( $_POST [ 'firstName' ]); if ( isset ( $_POST [ 'lastName' ])) $this -> lastName = StringUtil :: trim ( $_POST [ 'lastName' ]); } /** * @inheritDoc */ public function save () { parent :: save (); $this -> objectAction = new PersonAction ([], 'create' , [ 'data' => array_merge ( $this -> additionalFields , [ 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]) ]); $this -> objectAction -> executeAction (); $this -> saved (); // reset values $this -> firstName = '' ; $this -> lastName = '' ; // show success message WCF :: getTPL () -> assign ( 'success' , true ); } /** * @inheritDoc */ public function validate () { parent :: validate (); // validate first name if ( empty ( $this -> firstName )) { throw new UserInputException ( 'firstName' ); } if ( mb_strlen ( $this -> firstName ) > 255 ) { throw new UserInputException ( 'firstName' , 'tooLong' ); } // validate last name if ( empty ( $this -> lastName )) { throw new UserInputException ( 'lastName' ); } if ( mb_strlen ( $this -> lastName ) > 255 ) { throw new UserInputException ( 'lastName' , 'tooLong' ); } } } files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractForm ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\WCF ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * edited person object * @var Person */ public $person = null ; /** * id of the edited person * @var integer */ public $personID = 0 ; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'action' => 'edit' , 'person' => $this -> person ]); } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( empty ( $_POST )) { $this -> firstName = $this -> person -> firstName ; $this -> lastName = $this -> person -> lastName ; } } /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) $this -> personID = intval ( $_REQUEST [ 'id' ]); $this -> person = new Person ( $this -> personID ); if ( ! $this -> person -> personID ) { throw new IllegalLinkException (); } } /** * @inheritDoc */ public function save () { AbstractForm :: save (); $this -> objectAction = new PersonAction ([ $this -> person ], 'update' , [ 'data' => array_merge ( $this -> additionalFields , [ 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]) ]); $this -> objectAction -> executeAction (); $this -> saved (); // show success message WCF :: getTPL () -> assign ( 'success' , true ); } } acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { include file = 'formError' } { if $success | isset } <p class=\"success\"> { lang } wcf.global.success. { $action }{ /lang } </p> { /if } <form method=\"post\" action=\" { if $action == 'add' }{ link controller = 'PersonAdd' }{ /link }{ else }{ link controller = 'PersonEdit' object = $person }{ /link }{ /if } \"> <div class=\"section\"> <dl { if $errorField == 'firstName' } class=\"formError\" { /if } > <dt><label for=\"firstName\"> { lang } wcf.person.firstName { /lang } </label></dt> <dd> <input type=\"text\" id=\"firstName\" name=\"firstName\" value=\" { $firstName } \" required autofocus maxlength=\"255\" class=\"long\"> { if $errorField == 'firstName' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } wcf.acp.person.firstName.error. { $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> <dl { if $errorField == 'lastName' } class=\"formError\" { /if } > <dt><label for=\"lastName\"> { lang } wcf.person.lastName { /lang } </label></dt> <dd> <input type=\"text\" id=\"lastName\" name=\"lastName\" value=\" { $lastName } \" required maxlength=\"255\" class=\"long\"> { if $errorField == 'lastName' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } wcf.acp.person.lastName.error. { $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> { event name = 'dataFields' } </div> { event name = 'sections' } <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> { @ SECURITY_TOKEN_INPUT_TAG } </div> </form> { include file = 'footer' } Updating the template is easy as the complete form is replace by a single line of code: acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { @ $form -> getHtml () } { include file = 'footer' } PersonEditForm also becomes much simpler: only the edited Person object must be read: files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\system\\exception\\IllegalLinkException ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> formObject = new Person ( intval ( $_REQUEST [ 'id' ])); if ( ! $this -> formObject -> personID ) { throw new IllegalLinkException (); } } } } Most of the work is done in PersonAddForm : files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\TextFormField ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractFormBuilderForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * @inheritDoc */ public $formAction = 'create' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectActionClass = PersonAction :: class ; /** * @inheritDoc */ protected function createForm () { parent :: createForm (); $dataContainer = FormContainer :: create ( 'data' ) -> appendChildren ([ TextFormField :: create ( 'firstName' ) -> label ( 'wcf.person.firstName' ) -> required () -> maximumLength ( 255 ), TextFormField :: create ( 'lastName' ) -> label ( 'wcf.person.lastName' ) -> required () -> maximumLength ( 255 ) ]); $this -> form -> appendChild ( $dataContainer ); } } But, as you can see, the number of lines almost decreased by half. All changes are due to extending AbstractFormBuilderForm : $formAction is added and set to create as the form is used to create a new person. In the edit form, $formAction has not to be set explicitly as it is done automatically if a $formObject is set. $objectActionClass is set to PersonAction::class and is the class name of the used AbstractForm::$objectAction object to create and update the Person object. AbstractFormBuilderForm::createForm() is overridden and the form contents are added: a form container representing the div.section element from the old version and the two form fields with the same ids and labels as before. The contents of the old validate() method is put into two method calls: required() to ensure that the form is filled out and maximumLength(255) to ensure that the names are not longer than 255 characters.","title":"Migrating from WSC 3.1 - Form Builder"},{"location":"migration/wsc31/form-builder/#migrating-from-wsc-31-form-builder","text":"","title":"Migrating from WSC 3.1 - Form Builder"},{"location":"migration/wsc31/form-builder/#example-two-text-form-fields","text":"As the first example, the pre-WoltLab Suite Core 5.2 versions of the forms to add and edit persons from the first part of the tutorial series will be updated to the new form builder API. This form is the perfect first examples as it is very simple with only two text fields whose only restriction is that they have to be filled out and that their values may not be longer than 255 characters each. As a reminder, here are the two relevant PHP files and the relevant template file: files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractForm ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\WCF ; use wcf\\util\\StringUtil ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * first name of the person * @var string */ public $firstName = '' ; /** * last name of the person * @var string */ public $lastName = '' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'action' => 'add' , 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]); } /** * @inheritDoc */ public function readFormParameters () { parent :: readFormParameters (); if ( isset ( $_POST [ 'firstName' ])) $this -> firstName = StringUtil :: trim ( $_POST [ 'firstName' ]); if ( isset ( $_POST [ 'lastName' ])) $this -> lastName = StringUtil :: trim ( $_POST [ 'lastName' ]); } /** * @inheritDoc */ public function save () { parent :: save (); $this -> objectAction = new PersonAction ([], 'create' , [ 'data' => array_merge ( $this -> additionalFields , [ 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]) ]); $this -> objectAction -> executeAction (); $this -> saved (); // reset values $this -> firstName = '' ; $this -> lastName = '' ; // show success message WCF :: getTPL () -> assign ( 'success' , true ); } /** * @inheritDoc */ public function validate () { parent :: validate (); // validate first name if ( empty ( $this -> firstName )) { throw new UserInputException ( 'firstName' ); } if ( mb_strlen ( $this -> firstName ) > 255 ) { throw new UserInputException ( 'firstName' , 'tooLong' ); } // validate last name if ( empty ( $this -> lastName )) { throw new UserInputException ( 'lastName' ); } if ( mb_strlen ( $this -> lastName ) > 255 ) { throw new UserInputException ( 'lastName' , 'tooLong' ); } } } files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractForm ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\WCF ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * edited person object * @var Person */ public $person = null ; /** * id of the edited person * @var integer */ public $personID = 0 ; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'action' => 'edit' , 'person' => $this -> person ]); } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( empty ( $_POST )) { $this -> firstName = $this -> person -> firstName ; $this -> lastName = $this -> person -> lastName ; } } /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) $this -> personID = intval ( $_REQUEST [ 'id' ]); $this -> person = new Person ( $this -> personID ); if ( ! $this -> person -> personID ) { throw new IllegalLinkException (); } } /** * @inheritDoc */ public function save () { AbstractForm :: save (); $this -> objectAction = new PersonAction ([ $this -> person ], 'update' , [ 'data' => array_merge ( $this -> additionalFields , [ 'firstName' => $this -> firstName , 'lastName' => $this -> lastName ]) ]); $this -> objectAction -> executeAction (); $this -> saved (); // show success message WCF :: getTPL () -> assign ( 'success' , true ); } } acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { include file = 'formError' } { if $success | isset } <p class=\"success\"> { lang } wcf.global.success. { $action }{ /lang } </p> { /if } <form method=\"post\" action=\" { if $action == 'add' }{ link controller = 'PersonAdd' }{ /link }{ else }{ link controller = 'PersonEdit' object = $person }{ /link }{ /if } \"> <div class=\"section\"> <dl { if $errorField == 'firstName' } class=\"formError\" { /if } > <dt><label for=\"firstName\"> { lang } wcf.person.firstName { /lang } </label></dt> <dd> <input type=\"text\" id=\"firstName\" name=\"firstName\" value=\" { $firstName } \" required autofocus maxlength=\"255\" class=\"long\"> { if $errorField == 'firstName' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } wcf.acp.person.firstName.error. { $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> <dl { if $errorField == 'lastName' } class=\"formError\" { /if } > <dt><label for=\"lastName\"> { lang } wcf.person.lastName { /lang } </label></dt> <dd> <input type=\"text\" id=\"lastName\" name=\"lastName\" value=\" { $lastName } \" required maxlength=\"255\" class=\"long\"> { if $errorField == 'lastName' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } wcf.acp.person.lastName.error. { $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> { event name = 'dataFields' } </div> { event name = 'sections' } <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> { @ SECURITY_TOKEN_INPUT_TAG } </div> </form> { include file = 'footer' } Updating the template is easy as the complete form is replace by a single line of code: acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { @ $form -> getHtml () } { include file = 'footer' } PersonEditForm also becomes much simpler: only the edited Person object must be read: files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\system\\exception\\IllegalLinkException ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> formObject = new Person ( intval ( $_REQUEST [ 'id' ])); if ( ! $this -> formObject -> personID ) { throw new IllegalLinkException (); } } } } Most of the work is done in PersonAddForm : files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\TextFormField ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractFormBuilderForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * @inheritDoc */ public $formAction = 'create' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectActionClass = PersonAction :: class ; /** * @inheritDoc */ protected function createForm () { parent :: createForm (); $dataContainer = FormContainer :: create ( 'data' ) -> appendChildren ([ TextFormField :: create ( 'firstName' ) -> label ( 'wcf.person.firstName' ) -> required () -> maximumLength ( 255 ), TextFormField :: create ( 'lastName' ) -> label ( 'wcf.person.lastName' ) -> required () -> maximumLength ( 255 ) ]); $this -> form -> appendChild ( $dataContainer ); } } But, as you can see, the number of lines almost decreased by half. All changes are due to extending AbstractFormBuilderForm : $formAction is added and set to create as the form is used to create a new person. In the edit form, $formAction has not to be set explicitly as it is done automatically if a $formObject is set. $objectActionClass is set to PersonAction::class and is the class name of the used AbstractForm::$objectAction object to create and update the Person object. AbstractFormBuilderForm::createForm() is overridden and the form contents are added: a form container representing the div.section element from the old version and the two form fields with the same ids and labels as before. The contents of the old validate() method is put into two method calls: required() to ensure that the form is filled out and maximumLength(255) to ensure that the names are not longer than 255 characters.","title":"Example: Two Text Form Fields"},{"location":"migration/wsc31/like/","text":"Migrating from WSC 3.1 - Like System # Introduction # With version 5.2 of WoltLab Suite Core the like system was completely replaced by the new reactions system. This makes it necessary to make some adjustments to existing code so that your plugin integrates completely into the new system. However, we have kept these adjustments as small as possible so that it is possible to use the reaction system with slight restrictions even without adjustments. Limitations if no adjustments are made to the existing code # If no adjustments are made to the existing code, the following functions are not available: * Notifications about reactions/likes * Recent Activity Events for reactions/likes Migration # Notifications # Mark notification as compatible # Since there are no more likes with the new version, it makes no sense to send notifications about it. Instead of notifications about likes, notifications about reactions are now sent. However, this only changes the notification text and not the notification itself. To update the notification, we first add the interface \\wcf\\data\\reaction\\object\\IReactionObject to the \\wcf\\data\\like\\object\\ILikeObject object (e.g. in WoltLab Suite Forum we added the interface to the class \\wbb\\data\\post\\LikeablePost ). After that the object is marked as \"compatible with WoltLab Suite Core 5.2\" and notifications about reactions are sent again. Language Variables # Next, to display all reactions for the current notification in the notification text, we include the trait \\wcf\\system\\user\\notification\\event\\TReactionUserNotificationEvent in the user notification event class (typically named like *LikeUserNotificationEvent ). These trait provides a new function that reads out and groups the reactions. The result of this function must now only be passed to the language variable. The name \"reactions\" is typically used as the variable name for the language variable. As a final step, we only need to change the language variables themselves. To ensure a consistent usability, the same formulations should be used as in the WoltLab Suite Core. English # {prefix}.like.title 1 Reaction to a {objectName} {prefix}.like.title.stacked 1 {#$count} users reacted to your {objectName} {prefix}.like.message 1 {@$author->getAnchorTag()} reacted to your {objectName} ({implode from=$reactions key=reactionID item=count}{@$__wcf->getReactionHandler()->getReactionTypeByID($reactionID)->renderIcon()}\u00d7{#$count}{/implode}). {prefix}.like.message.stacked 1 {if $count < 4}{@$authors[0]->getAnchorTag()}{if $count == 2} and {else}, {/if}{@$authors[1]->getAnchorTag()}{if $count == 3} and {@$authors[2]->getAnchorTag()}{/if}{else}{@$authors[0]->getAnchorTag()} and {#$others} others{/if} reacted to your {objectName} ({implode from=$reactions key=reactionID item=count}{@$__wcf->getReactionHandler()->getReactionTypeByID($reactionID)->renderIcon()}\u00d7{#$count}{/implode}). wcf.user.notification.{objectTypeName}.like.notification.like 1 Notify me when someone reacted to my {objectName} German # {prefix}.like.title 1 Reaktion auf einen {objectName} {prefix}.like.title.stacked 1 {#$count} Benutzern haben auf {if LANGUAGE_USE_INFORMAL_VARIANT}dein(en){else}Ihr(en){/if} {objectName} reagiert {prefix}.like.message 1 {@$author->getAnchorTag()} hat auf {if LANGUAGE_USE_INFORMAL_VARIANT}dein(en){else}Ihr(en){/if} {objectName} reagiert ({implode from=$reactions key=reactionID item=count}{@$__wcf->getReactionHandler()->getReactionTypeByID($reactionID)->renderIcon()}\u00d7{#$count}{/implode}). {prefix}.like.message.stacked 1 {if $count < 4}{@$authors[0]->getAnchorTag()}{if $count == 2} und {else}, {/if}{@$authors[1]->getAnchorTag()}{if $count == 3} und {@$authors[2]->getAnchorTag()}{/if}{else}{@$authors[0]->getAnchorTag()} und {#$others} weitere{/if} haben auf {if LANGUAGE_USE_INFORMAL_VARIANT}dein(en){else}Ihr(en){/if} {objectName} reagiert ({implode from=$reactions key=reactionID item=count}{@$__wcf->getReactionHandler()->getReactionTypeByID($reactionID)->renderIcon()}\u00d7{#$count}{/implode}). wcf.user.notification.{object_type_name}.like.notification.like 1 Jemandem hat auf {if LANGUAGE_USE_INFORMAL_VARIANT}dein(en){else}Ihr(en){/if} {objectName} reagiert Recent Activity # To adjust entries in the Recent Activity, only three small steps are necessary. First we pass the concrete reaction to the language variable, so that we can use the reaction object there. To do this, we add the following variable to the text of the \\wcf\\system\\user\\activity\\event\\IUserActivityEvent object: $event->reactionType . Typically we name the variable reactionType . In the second step, we mark the event as compatible. Therefore we set the parameter supportsReactions in the objectType.xml to 1 . So for example the entry looks like this: objectType.xml 1 2 3 4 5 6 <type> <name> com.woltlab.example.likeableObject.recentActivityEvent </name> <definitionname> com.woltlab.wcf.user.recentActivityEvent </definitionname> <classname> wcf\\system\\user\\activity\\event\\LikeableObjectUserActivityEvent </classname> <supportsReactions> 1 </supportsReactions> </type> Finally we modify our language variable. To ensure a consistent usability, the same formulations should be used as in the WoltLab Suite Core. English # wcf.user.recentActivity.{object_type_name}.recentActivityEvent 1 Reaction ({objectName}) Your language variable for the recent activity text 1 Reacted with <span title=\"{$reactionType->getTitle()}\" class=\"jsTooltip\">{@$reactionType->renderIcon()}</span> to the {objectName}. German # wcf.user.recentActivity.{objectTypeName}.recentActivityEvent 1 Reaktion ({objectName}) Your language variable for the recent activity text 1 Hat mit <span title=\"{$reactionType->getTitle()}\" class=\"jsTooltip\">{@$reactionType->renderIcon()}</span> auf {objectName} reagiert. Comments # If comments send notifications, they must also be updated. The language variables are changed in the same way as described in the section Notifications / Language . After that comment must be marked as compatible. Therefore we set the parameter supportsReactions in the objectType.xml to 1 . So for example the entry looks like this: objectType.xml 1 2 3 4 5 6 7 <type> <name> com.woltlab.wcf.objectComment.response.like.notification </name> <definitionname> com.woltlab.wcf.notification.objectType </definitionname> <classname> wcf\\system\\user\\notification\\object\\type\\LikeUserNotificationObjectType </classname> <category> com.woltlab.example </category> <supportsReactions> 1 </supportsReactions> </type> Forward Compatibility # So that these changes also work in older versions of WoltLab Suite Core, the used classes and traits were backported with WoltLab Suite Core 3.0.22 and WoltLab Suite Core 3.1.10.","title":"Migrating from WSC 3.1 - Like System"},{"location":"migration/wsc31/like/#migrating-from-wsc-31-like-system","text":"","title":"Migrating from WSC 3.1 - Like System"},{"location":"migration/wsc31/like/#introduction","text":"With version 5.2 of WoltLab Suite Core the like system was completely replaced by the new reactions system. This makes it necessary to make some adjustments to existing code so that your plugin integrates completely into the new system. However, we have kept these adjustments as small as possible so that it is possible to use the reaction system with slight restrictions even without adjustments.","title":"Introduction"},{"location":"migration/wsc31/like/#limitations-if-no-adjustments-are-made-to-the-existing-code","text":"If no adjustments are made to the existing code, the following functions are not available: * Notifications about reactions/likes * Recent Activity Events for reactions/likes","title":"Limitations if no adjustments are made to the existing code"},{"location":"migration/wsc31/like/#migration","text":"","title":"Migration"},{"location":"migration/wsc31/like/#notifications","text":"","title":"Notifications"},{"location":"migration/wsc31/like/#mark-notification-as-compatible","text":"Since there are no more likes with the new version, it makes no sense to send notifications about it. Instead of notifications about likes, notifications about reactions are now sent. However, this only changes the notification text and not the notification itself. To update the notification, we first add the interface \\wcf\\data\\reaction\\object\\IReactionObject to the \\wcf\\data\\like\\object\\ILikeObject object (e.g. in WoltLab Suite Forum we added the interface to the class \\wbb\\data\\post\\LikeablePost ). After that the object is marked as \"compatible with WoltLab Suite Core 5.2\" and notifications about reactions are sent again.","title":"Mark notification as compatible"},{"location":"migration/wsc31/like/#language-variables","text":"Next, to display all reactions for the current notification in the notification text, we include the trait \\wcf\\system\\user\\notification\\event\\TReactionUserNotificationEvent in the user notification event class (typically named like *LikeUserNotificationEvent ). These trait provides a new function that reads out and groups the reactions. The result of this function must now only be passed to the language variable. The name \"reactions\" is typically used as the variable name for the language variable. As a final step, we only need to change the language variables themselves. To ensure a consistent usability, the same formulations should be used as in the WoltLab Suite Core.","title":"Language Variables"},{"location":"migration/wsc31/like/#recent-activity","text":"To adjust entries in the Recent Activity, only three small steps are necessary. First we pass the concrete reaction to the language variable, so that we can use the reaction object there. To do this, we add the following variable to the text of the \\wcf\\system\\user\\activity\\event\\IUserActivityEvent object: $event->reactionType . Typically we name the variable reactionType . In the second step, we mark the event as compatible. Therefore we set the parameter supportsReactions in the objectType.xml to 1 . So for example the entry looks like this: objectType.xml 1 2 3 4 5 6 <type> <name> com.woltlab.example.likeableObject.recentActivityEvent </name> <definitionname> com.woltlab.wcf.user.recentActivityEvent </definitionname> <classname> wcf\\system\\user\\activity\\event\\LikeableObjectUserActivityEvent </classname> <supportsReactions> 1 </supportsReactions> </type> Finally we modify our language variable. To ensure a consistent usability, the same formulations should be used as in the WoltLab Suite Core.","title":"Recent Activity"},{"location":"migration/wsc31/like/#english_1","text":"wcf.user.recentActivity.{object_type_name}.recentActivityEvent 1 Reaction ({objectName}) Your language variable for the recent activity text 1 Reacted with <span title=\"{$reactionType->getTitle()}\" class=\"jsTooltip\">{@$reactionType->renderIcon()}</span> to the {objectName}.","title":"English"},{"location":"migration/wsc31/like/#german_1","text":"wcf.user.recentActivity.{objectTypeName}.recentActivityEvent 1 Reaktion ({objectName}) Your language variable for the recent activity text 1 Hat mit <span title=\"{$reactionType->getTitle()}\" class=\"jsTooltip\">{@$reactionType->renderIcon()}</span> auf {objectName} reagiert.","title":"German"},{"location":"migration/wsc31/like/#comments","text":"If comments send notifications, they must also be updated. The language variables are changed in the same way as described in the section Notifications / Language . After that comment must be marked as compatible. Therefore we set the parameter supportsReactions in the objectType.xml to 1 . So for example the entry looks like this: objectType.xml 1 2 3 4 5 6 7 <type> <name> com.woltlab.wcf.objectComment.response.like.notification </name> <definitionname> com.woltlab.wcf.notification.objectType </definitionname> <classname> wcf\\system\\user\\notification\\object\\type\\LikeUserNotificationObjectType </classname> <category> com.woltlab.example </category> <supportsReactions> 1 </supportsReactions> </type>","title":"Comments"},{"location":"migration/wsc31/like/#forward-compatibility","text":"So that these changes also work in older versions of WoltLab Suite Core, the used classes and traits were backported with WoltLab Suite Core 3.0.22 and WoltLab Suite Core 3.1.10.","title":"Forward Compatibility"},{"location":"migration/wsc31/php/","text":"Migrating from WSC 3.1 - PHP # Form Builder # WoltLab Suite Core 5.2 introduces a new, simpler and quicker way of creating forms: form builder . You can find examples of how to migrate existing forms to form builder here . In the near future, to ensure backwards compatibility within WoltLab packages, we will only use form builder for new forms or for major rewrites of existing forms that would break backwards compatibility anyway. Like System # WoltLab Suite Core 5.2 replaced the like system with the reaction system. You can find the migration guide here . User Content Providers # User content providers help the WoltLab Suite to find user generated content. They provide a class with which you can find content from a particular user and delete objects. PHP Class # First, we create the PHP class that provides our interface to provide the data. The class must implement interface wcf\\system\\user\\content\\provider\\IUserContentProvider in any case. Mostly we process data which is based on wcf\\data\\DatabaseObject . In this case, the WoltLab Suite provides an abstract class wcf\\system\\user\\content\\provider\\AbstractDatabaseUserContentProvider that can be used to automatically generates the standardized classes to generate the list and deletes objects via the DatabaseObjectAction. For example, if we would create a content provider for comments, the class would look like this: files/lib/system/user/content/provider/CommentUserContentProvider.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\user\\content\\provider ; use wcf\\data\\comment\\Comment ; /** * User content provider for comments. * * @author Joshua Ruesweg * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\User\\Content\\Provider * @since 5.2 */ class CommentUserContentProvider extends AbstractDatabaseUserContentProvider { /** * @inheritdoc */ public static function getDatabaseObjectClass () { return Comment :: class ; } } Object Type # Now the appropriate object type must be created for the class. This object type must be from the definition com.woltlab.wcf.content.userContentProvider and include the previous created class as FQN in the parameter classname . Also the following parameters can be used in the object type: nicevalue # Optional The nice value is used to determine the order in which the remove content worker are execute the provider. Content provider with lower nice values are executed first. hidden # Optional Specifies whether or not this content provider can be actively selected in the Content Remove Worker. If it cannot be selected, it will not be executed automatically! requiredobjecttype # Optional The specified list of comma-separated object types are automatically removed during content removal when this object type is being removed. Attention : The order of removal is undefined by default, specify a nicevalue if the order is important. PHP Database API # WoltLab Suite 5.2 introduces a new way to update the database scheme: database PHP API .","title":"PHP API"},{"location":"migration/wsc31/php/#migrating-from-wsc-31-php","text":"","title":"Migrating from WSC 3.1 - PHP"},{"location":"migration/wsc31/php/#form-builder","text":"WoltLab Suite Core 5.2 introduces a new, simpler and quicker way of creating forms: form builder . You can find examples of how to migrate existing forms to form builder here . In the near future, to ensure backwards compatibility within WoltLab packages, we will only use form builder for new forms or for major rewrites of existing forms that would break backwards compatibility anyway.","title":"Form Builder"},{"location":"migration/wsc31/php/#like-system","text":"WoltLab Suite Core 5.2 replaced the like system with the reaction system. You can find the migration guide here .","title":"Like System"},{"location":"migration/wsc31/php/#user-content-providers","text":"User content providers help the WoltLab Suite to find user generated content. They provide a class with which you can find content from a particular user and delete objects.","title":"User Content Providers"},{"location":"migration/wsc31/php/#php-class","text":"First, we create the PHP class that provides our interface to provide the data. The class must implement interface wcf\\system\\user\\content\\provider\\IUserContentProvider in any case. Mostly we process data which is based on wcf\\data\\DatabaseObject . In this case, the WoltLab Suite provides an abstract class wcf\\system\\user\\content\\provider\\AbstractDatabaseUserContentProvider that can be used to automatically generates the standardized classes to generate the list and deletes objects via the DatabaseObjectAction. For example, if we would create a content provider for comments, the class would look like this: files/lib/system/user/content/provider/CommentUserContentProvider.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\user\\content\\provider ; use wcf\\data\\comment\\Comment ; /** * User content provider for comments. * * @author Joshua Ruesweg * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\User\\Content\\Provider * @since 5.2 */ class CommentUserContentProvider extends AbstractDatabaseUserContentProvider { /** * @inheritdoc */ public static function getDatabaseObjectClass () { return Comment :: class ; } }","title":"PHP Class"},{"location":"migration/wsc31/php/#object-type","text":"Now the appropriate object type must be created for the class. This object type must be from the definition com.woltlab.wcf.content.userContentProvider and include the previous created class as FQN in the parameter classname . Also the following parameters can be used in the object type:","title":"Object Type"},{"location":"migration/wsc31/php/#nicevalue","text":"Optional The nice value is used to determine the order in which the remove content worker are execute the provider. Content provider with lower nice values are executed first.","title":"nicevalue"},{"location":"migration/wsc31/php/#hidden","text":"Optional Specifies whether or not this content provider can be actively selected in the Content Remove Worker. If it cannot be selected, it will not be executed automatically!","title":"hidden"},{"location":"migration/wsc31/php/#requiredobjecttype","text":"Optional The specified list of comma-separated object types are automatically removed during content removal when this object type is being removed. Attention : The order of removal is undefined by default, specify a nicevalue if the order is important.","title":"requiredobjecttype"},{"location":"migration/wsc31/php/#php-database-api","text":"WoltLab Suite 5.2 introduces a new way to update the database scheme: database PHP API .","title":"PHP Database API"},{"location":"migration/wsc52/libraries/","text":"Migrating from WSC 5.2 - Third Party Libraries # SCSS Compiler # WoltLab Suite Core 5.3 upgrades the bundled SCSS compiler from leafo/scssphp 0.7.x to scssphp/scssphp 1.1.x. With the updated composer package name the SCSS compiler also received updated namespaces. WoltLab Suite Core adds a compatibility layer that maps the old namespace to the new namespace. The classes themselves appear to be drop-in compatible. Exceptions cannot be mapped using this compatibility layer, any catch blocks catching a specific Exception within the Leafo namespace will need to be adjusted. More details can be found in the Pull Request WoltLab/WCF#3415 . Guzzle # WoltLab Suite Core 5.3 ships with a bundled version of Guzzle 6 . Going forward using Guzzle is the recommended way to perform HTTP requests. The \\wcf\\util\\HTTPRequest class should no longer be used and transparently uses Guzzle under the hood. Use \\wcf\\system\\io\\HttpFactory to retrieve a correctly configured GuzzleHttp\\ClientInterface . Please note that it is recommended to explicitely specify a sink when making requests, due to a PHP / Guzzle bug. Have a look at the implementation in WoltLab/WCF for an example.","title":"Third Party Libraries"},{"location":"migration/wsc52/libraries/#migrating-from-wsc-52-third-party-libraries","text":"","title":"Migrating from WSC 5.2 - Third Party Libraries"},{"location":"migration/wsc52/libraries/#scss-compiler","text":"WoltLab Suite Core 5.3 upgrades the bundled SCSS compiler from leafo/scssphp 0.7.x to scssphp/scssphp 1.1.x. With the updated composer package name the SCSS compiler also received updated namespaces. WoltLab Suite Core adds a compatibility layer that maps the old namespace to the new namespace. The classes themselves appear to be drop-in compatible. Exceptions cannot be mapped using this compatibility layer, any catch blocks catching a specific Exception within the Leafo namespace will need to be adjusted. More details can be found in the Pull Request WoltLab/WCF#3415 .","title":"SCSS Compiler"},{"location":"migration/wsc52/libraries/#guzzle","text":"WoltLab Suite Core 5.3 ships with a bundled version of Guzzle 6 . Going forward using Guzzle is the recommended way to perform HTTP requests. The \\wcf\\util\\HTTPRequest class should no longer be used and transparently uses Guzzle under the hood. Use \\wcf\\system\\io\\HttpFactory to retrieve a correctly configured GuzzleHttp\\ClientInterface . Please note that it is recommended to explicitely specify a sink when making requests, due to a PHP / Guzzle bug. Have a look at the implementation in WoltLab/WCF for an example.","title":"Guzzle"},{"location":"migration/wsc52/php/","text":"Migrating from WSC 5.2 - PHP # Comments # The ICommentManager::isContentAuthor(Comment|CommentResponse): bool method was added. A default implementation that always returns false is available when inheriting from AbstractCommentManager . It is strongly recommended to implement isContentAuthor within your custom comment manager. An example implementation can be found in ArticleCommentManager . Event Listeners # The AbstractEventListener class was added. AbstractEventListener contains an implementation of execute() that will dispatch the event handling to dedicated methods based on the $eventName and, in case of the event object being an AbstractDatabaseObjectAction , the action name. Find the details of the dispatch behavior within the class comment of AbstractEventListener . Email Activation # Starting with WoltLab Suite 5.3 the user activation status is independent of the email activation status. A user can be activated even though their email address has not been confirmed, preventing emails being sent to these users. Going forward the new User::isEmailConfirmed() method should be used to check whether sending automated emails to this user is acceptable. If you need to check the user's activation status you should use the new method User::pendingActivation() instead of relying on activationCode . To check, which type of activation is missing, you can use the new methods User::requiresEmailActivation() and User::requiresAdminActivation() . *AddForm # WoltLab Suite 5.3 provides a new framework to allow the administrator to easily edit newly created objects by adding an edit link to the success message. To support this edit link two small changes are required within your *AddForm . Update the template. Replace: 1 2 3 4 5 { include file = 'formError' } { if $success | isset } <p class=\"success\"> { lang } wcf.global.success. { $action }{ /lang } </p> { /if } With: 1 { include file = 'formNotice' } Expose objectEditLink to the template. Example ( $object being the newly created object): 1 2 3 4 WCF :: getTPL () -> assign ([ 'success' => true , 'objectEditLink' => LinkHandler :: getInstance () -> getControllerLink ( ObjectEditForm :: class , [ 'id' => $object -> objectID ]), ]); User Generated Links # It is recommended by search engines to mark up links within user generated content using the rel=\"ugc\" attribute to indicate that they might be less trustworthy or spammy. WoltLab Suite 5.3 will automatically sets that attribute on external links during message output processing. Set the new HtmlOutputProcessor::$enableUgc property to false if the type of message is not user-generated content, but restricted to a set of trustworthy users. An example of such a type of message would be official news articles. If you manually generate links based off user input you need to specify the attribute yourself. The $isUgc attribute was added to StringUtil::getAnchorTag(string, string, bool, bool): string , allowing you to easily generate a correct anchor tag. If you need to specify additional HTML attributes for the anchor tag you can use the new StringUtil::getAnchorTagAttributes(string, bool): string method to generate the anchor attributes that are dependent on the target URL. Specifically the attributes returned are the class=\"externalURL\" attribute, the rel=\"\u2026\" attribute and the target=\"\u2026\" attribute. Within the template the {anchorAttributes} template plugin is newly available. Resource Management When Scaling Images # It was discovered that the code holds references to scaled image resources for an unnecessarily long time, taking up memory. This becomes especially apparent when multiple images are scaled within a loop, reusing the same variable name for consecutive images. Unless the destination variable is explicitely cleared before processing the next image up to two images will be stored in memory concurrently. This possibly causes the request to exceed the memory limit or ImageMagick's internal resource limits, even if sufficient resources would have been available to scale the current image. Starting with WoltLab Suite 5.3 it is recommended to clear image handles as early as possible. The usual pattern of creating a thumbnail for an existing image would then look like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php foreach ([ 200 , 500 ] as $size ) { $adapter = ImageHandler :: getInstance () -> getAdapter (); $adapter -> loadFile ( $src ); $thumbnail = $adapter -> createThumbnail ( $size , $size , true ); $adapter -> writeImage ( $thumbnail , $destination ); // New: Clear thumbnail as soon as possible to free up the memory. $thumbnail = null ; } Refer to WoltLab/WCF#3505 for additional details. Toggle for Accelerated Mobile Pages (AMP) # Controllers delivering AMP versions of pages have to check for the new option MODULE_AMP and the templates of the non-AMP versions have to also check if the option is enabled before outputting the <link rel=\"amphtml\" /> element.","title":"PHP API"},{"location":"migration/wsc52/php/#migrating-from-wsc-52-php","text":"","title":"Migrating from WSC 5.2 - PHP"},{"location":"migration/wsc52/php/#comments","text":"The ICommentManager::isContentAuthor(Comment|CommentResponse): bool method was added. A default implementation that always returns false is available when inheriting from AbstractCommentManager . It is strongly recommended to implement isContentAuthor within your custom comment manager. An example implementation can be found in ArticleCommentManager .","title":"Comments"},{"location":"migration/wsc52/php/#event-listeners","text":"The AbstractEventListener class was added. AbstractEventListener contains an implementation of execute() that will dispatch the event handling to dedicated methods based on the $eventName and, in case of the event object being an AbstractDatabaseObjectAction , the action name. Find the details of the dispatch behavior within the class comment of AbstractEventListener .","title":"Event Listeners"},{"location":"migration/wsc52/php/#email-activation","text":"Starting with WoltLab Suite 5.3 the user activation status is independent of the email activation status. A user can be activated even though their email address has not been confirmed, preventing emails being sent to these users. Going forward the new User::isEmailConfirmed() method should be used to check whether sending automated emails to this user is acceptable. If you need to check the user's activation status you should use the new method User::pendingActivation() instead of relying on activationCode . To check, which type of activation is missing, you can use the new methods User::requiresEmailActivation() and User::requiresAdminActivation() .","title":"Email Activation"},{"location":"migration/wsc52/php/#addform","text":"WoltLab Suite 5.3 provides a new framework to allow the administrator to easily edit newly created objects by adding an edit link to the success message. To support this edit link two small changes are required within your *AddForm . Update the template. Replace: 1 2 3 4 5 { include file = 'formError' } { if $success | isset } <p class=\"success\"> { lang } wcf.global.success. { $action }{ /lang } </p> { /if } With: 1 { include file = 'formNotice' } Expose objectEditLink to the template. Example ( $object being the newly created object): 1 2 3 4 WCF :: getTPL () -> assign ([ 'success' => true , 'objectEditLink' => LinkHandler :: getInstance () -> getControllerLink ( ObjectEditForm :: class , [ 'id' => $object -> objectID ]), ]);","title":"*AddForm"},{"location":"migration/wsc52/php/#user-generated-links","text":"It is recommended by search engines to mark up links within user generated content using the rel=\"ugc\" attribute to indicate that they might be less trustworthy or spammy. WoltLab Suite 5.3 will automatically sets that attribute on external links during message output processing. Set the new HtmlOutputProcessor::$enableUgc property to false if the type of message is not user-generated content, but restricted to a set of trustworthy users. An example of such a type of message would be official news articles. If you manually generate links based off user input you need to specify the attribute yourself. The $isUgc attribute was added to StringUtil::getAnchorTag(string, string, bool, bool): string , allowing you to easily generate a correct anchor tag. If you need to specify additional HTML attributes for the anchor tag you can use the new StringUtil::getAnchorTagAttributes(string, bool): string method to generate the anchor attributes that are dependent on the target URL. Specifically the attributes returned are the class=\"externalURL\" attribute, the rel=\"\u2026\" attribute and the target=\"\u2026\" attribute. Within the template the {anchorAttributes} template plugin is newly available.","title":"User Generated Links"},{"location":"migration/wsc52/php/#resource-management-when-scaling-images","text":"It was discovered that the code holds references to scaled image resources for an unnecessarily long time, taking up memory. This becomes especially apparent when multiple images are scaled within a loop, reusing the same variable name for consecutive images. Unless the destination variable is explicitely cleared before processing the next image up to two images will be stored in memory concurrently. This possibly causes the request to exceed the memory limit or ImageMagick's internal resource limits, even if sufficient resources would have been available to scale the current image. Starting with WoltLab Suite 5.3 it is recommended to clear image handles as early as possible. The usual pattern of creating a thumbnail for an existing image would then look like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php foreach ([ 200 , 500 ] as $size ) { $adapter = ImageHandler :: getInstance () -> getAdapter (); $adapter -> loadFile ( $src ); $thumbnail = $adapter -> createThumbnail ( $size , $size , true ); $adapter -> writeImage ( $thumbnail , $destination ); // New: Clear thumbnail as soon as possible to free up the memory. $thumbnail = null ; } Refer to WoltLab/WCF#3505 for additional details.","title":"Resource Management When Scaling Images"},{"location":"migration/wsc52/php/#toggle-for-accelerated-mobile-pages-amp","text":"Controllers delivering AMP versions of pages have to check for the new option MODULE_AMP and the templates of the non-AMP versions have to also check if the option is enabled before outputting the <link rel=\"amphtml\" /> element.","title":"Toggle for Accelerated Mobile Pages (AMP)"},{"location":"migration/wsc52/templates/","text":"Migrating from WSC 5.2 - Templates and Languages # {jslang} # Starting with WoltLab Suite 5.3 the {jslang} template plugin is available. {jslang} works like {lang} , with the difference that the result is automatically encoded for use within a single quoted JavaScript string. Before: 1 2 3 4 5 6 7 8 9 <script> require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{lang}app.foo.bar{/lang}' , } ); // \u2026 } ); </script> After: 1 2 3 4 5 6 7 8 9 <script> require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' , } ); // \u2026 } ); </script> Template Plugins # The {anchor} , {plural} , and {user} template plugins have been added. Notification Language Items # In addition to using the new template plugins mentioned above, language items for notifications have been further simplified. As the whole notification is clickable now, all a elements have been replaced with strong elements in notification messages. The template code to output reactions has been simplified by introducing helper methods: 1 2 3 4 5 6 7 8 9 { * old * } { implode from = $reactions key = reactionID item = count }{ @ $__wcf -> getReactionHandler ()-> getReactionTypeByID ( $reactionID )-> renderIcon () } \u00d7 { # $count }{ /implode } { * new * } { @ $__wcf -> getReactionHandler ()-> renderInlineList ( $reactions ) } { * old * } <span title=\" { $like -> getReactionType ()-> getTitle () } \" class=\"jsTooltip\"> { @ $like -> getReactionType ()-> renderIcon () } </span> { * new * } { @ $like -> render () } Similarly, showing labels is now also easier due to the new render method: 1 2 3 4 { * old * } <span class=\"label badge { if $label -> getClassNames () } { $label -> getClassNames () }{ /if } \"> { $label -> getTitle () } </span> { * new * } { @ $label -> render () } The commonly used template code 1 { if $count < 4 }{ @ $authors [ 0 ]-> getAnchorTag () }{ if $count != 1 }{ if $count == 2 && ! $guestTimesTriggered } and { else } , { /if }{ @ $authors [ 1 ]-> getAnchorTag () }{ if $count == 3 }{ if ! $guestTimesTriggered } and { else } , { /if } { @ $authors [ 2 ]-> getAnchorTag () }{ /if }{ /if }{ if $guestTimesTriggered } and { if $guestTimesTriggered == 1 } a guest { else } guests { /if }{ /if }{ else }{ @ $authors [ 0 ]-> getAnchorTag () }{ if $guestTimesTriggered } , { else } and { /if } { # $others } other users { if $guestTimesTriggered } and { if $guestTimesTriggered == 1 } a guest { else } guests { /if }{ /if }{ /if } in stacked notification messages can be replaced with a new language item: 1 { @ 'wcf.user.notification.stacked.authorList' | language } Popovers # Popovers provide additional information of the linked object when a user hovers over a link. We unified the approach for such links: The relevant DBO class implements wcf\\data\\IPopoverObject . The relevant DBO action class implements wcf\\data\\IPopoverAction and the getPopover() method returns an array with popover content. Globally available, WoltLabSuite/Core/Controller/Popover is initialized with the relevant data. Links are created with the anchor template plugin with an additional class attribute whose value is the return value of IPopoverObject::getPopoverLinkClass() . Example: files/lib/data/foo/Foo.class.php 1 2 3 4 5 class Foo extends DatabaseObject implements IPopoverObject { public function getPopoverLinkClass () { return 'fooLink' ; } } files/lib/data/foo/FooAction.class.php 1 2 3 4 5 6 7 8 9 10 11 class FooAction extends AbstractDatabaseObjectAction implements IPopoverAction { public function validateGetPopover () { // \u2026 } public function getPopover () { return [ 'template' => '\u2026' , ]; } } 1 2 3 4 5 6 7 require ([ 'WoltLabSuite/Core/Controller/Popover' ], function ( ControllerPopover ) { ControllerPopover . init ({ className : 'fooLink' , dboAction : 'wcf\\\\data\\\\foo\\\\FooAction' , identifier : 'com.woltlab.wcf.foo' }); }); 1 { anchor object = $foo class = 'fooLink' }","title":"Templates and Languages"},{"location":"migration/wsc52/templates/#migrating-from-wsc-52-templates-and-languages","text":"","title":"Migrating from WSC 5.2 - Templates and Languages"},{"location":"migration/wsc52/templates/#jslang","text":"Starting with WoltLab Suite 5.3 the {jslang} template plugin is available. {jslang} works like {lang} , with the difference that the result is automatically encoded for use within a single quoted JavaScript string. Before: 1 2 3 4 5 6 7 8 9 <script> require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{lang}app.foo.bar{/lang}' , } ); // \u2026 } ); </script> After: 1 2 3 4 5 6 7 8 9 <script> require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' , } ); // \u2026 } ); </script>","title":"{jslang}"},{"location":"migration/wsc52/templates/#template-plugins","text":"The {anchor} , {plural} , and {user} template plugins have been added.","title":"Template Plugins"},{"location":"migration/wsc52/templates/#notification-language-items","text":"In addition to using the new template plugins mentioned above, language items for notifications have been further simplified. As the whole notification is clickable now, all a elements have been replaced with strong elements in notification messages. The template code to output reactions has been simplified by introducing helper methods: 1 2 3 4 5 6 7 8 9 { * old * } { implode from = $reactions key = reactionID item = count }{ @ $__wcf -> getReactionHandler ()-> getReactionTypeByID ( $reactionID )-> renderIcon () } \u00d7 { # $count }{ /implode } { * new * } { @ $__wcf -> getReactionHandler ()-> renderInlineList ( $reactions ) } { * old * } <span title=\" { $like -> getReactionType ()-> getTitle () } \" class=\"jsTooltip\"> { @ $like -> getReactionType ()-> renderIcon () } </span> { * new * } { @ $like -> render () } Similarly, showing labels is now also easier due to the new render method: 1 2 3 4 { * old * } <span class=\"label badge { if $label -> getClassNames () } { $label -> getClassNames () }{ /if } \"> { $label -> getTitle () } </span> { * new * } { @ $label -> render () } The commonly used template code 1 { if $count < 4 }{ @ $authors [ 0 ]-> getAnchorTag () }{ if $count != 1 }{ if $count == 2 && ! $guestTimesTriggered } and { else } , { /if }{ @ $authors [ 1 ]-> getAnchorTag () }{ if $count == 3 }{ if ! $guestTimesTriggered } and { else } , { /if } { @ $authors [ 2 ]-> getAnchorTag () }{ /if }{ /if }{ if $guestTimesTriggered } and { if $guestTimesTriggered == 1 } a guest { else } guests { /if }{ /if }{ else }{ @ $authors [ 0 ]-> getAnchorTag () }{ if $guestTimesTriggered } , { else } and { /if } { # $others } other users { if $guestTimesTriggered } and { if $guestTimesTriggered == 1 } a guest { else } guests { /if }{ /if }{ /if } in stacked notification messages can be replaced with a new language item: 1 { @ 'wcf.user.notification.stacked.authorList' | language }","title":"Notification Language Items"},{"location":"migration/wsc52/templates/#popovers","text":"Popovers provide additional information of the linked object when a user hovers over a link. We unified the approach for such links: The relevant DBO class implements wcf\\data\\IPopoverObject . The relevant DBO action class implements wcf\\data\\IPopoverAction and the getPopover() method returns an array with popover content. Globally available, WoltLabSuite/Core/Controller/Popover is initialized with the relevant data. Links are created with the anchor template plugin with an additional class attribute whose value is the return value of IPopoverObject::getPopoverLinkClass() . Example: files/lib/data/foo/Foo.class.php 1 2 3 4 5 class Foo extends DatabaseObject implements IPopoverObject { public function getPopoverLinkClass () { return 'fooLink' ; } } files/lib/data/foo/FooAction.class.php 1 2 3 4 5 6 7 8 9 10 11 class FooAction extends AbstractDatabaseObjectAction implements IPopoverAction { public function validateGetPopover () { // \u2026 } public function getPopover () { return [ 'template' => '\u2026' , ]; } } 1 2 3 4 5 6 7 require ([ 'WoltLabSuite/Core/Controller/Popover' ], function ( ControllerPopover ) { ControllerPopover . init ({ className : 'fooLink' , dboAction : 'wcf\\\\data\\\\foo\\\\FooAction' , identifier : 'com.woltlab.wcf.foo' }); }); 1 { anchor object = $foo class = 'fooLink' }","title":"Popovers"},{"location":"migration/wsc53/javascript/","text":"Migrating from WSC 5.3 - TypeScript and JavaScript # TypeScript # WoltLab Suite 5.4 introduces TypeScript support. Learn about consuming WoltLab Suite\u2019s types in the TypeScript section of the JavaScript API documentation. The JavaScript API documentation will be updated to properly take into account the changes that came with the new TypeScript support in the future. Existing AMD based modules have been migrated to TypeScript, but will expose the existing and known API. It is recommended that you migrate your custom packages to make use of TypeScript. It will make consuming newly written modules that properly leverage TypeScript\u2019s features much more pleasant and will also ease using existing modules due to proper autocompletion and type checking. Replacements for Deprecated Components # The helper functions in wcf.globalHelper.js should not be used anymore but replaced by their native counterpart: Function Native Replacement elCreate(tag) document.createElement(tag) elRemove(el) el.remove() elShow(el) DomUtil.show(el) elHide(el) DomUtil.hide(el) elIsHidden(el) DomUtil.isHidden(el) elToggle(el) DomUtil.toggle(el) elAttr(el, \"attr\") el.attr or el.getAttribute(\"attr\") elData(el, \"data\") el.dataset.data elDataBool(element, \"data\") Core.stringToBool(el.dataset.data) elById(id) document.getElementById(id) elBySel(sel) document.querySelector(sel) elBySel(sel, el) el.querySelector(sel) elBySelAll(sel) document.querySelectorAll(sel) elBySelAll(sel, el) el.querySelectorAll(sel) elBySelAll(sel, el, callback) el.querySelectorAll(sel).forEach((el) => callback(el)); elClosest(el, sel) el.closest(sel) elByClass(class) document.getElementsByClassName(class) elByClass(class, el) el.getElementsByClassName(class) elByTag(tag) document.getElementsByTagName(tag) elByTag(tag, el) el.getElementsByTagName(tag) elInnerError(el, message, isHtml) DomUtil.innerError(el, message, isHtml) Additionally, the following modules should also be replaced by their native counterpart: Module Native Replacement WoltLabSuite/Core/Dictionary Map WoltLabSuite/Core/List Set WoltLabSuite/Core/ObjectMap WeakMap For event listeners on click events, WCF_CLICK_EVENT is deprecated and should no longer be used. Instead, use click directly: 1 2 3 4 5 // before element . addEventListener ( WCF_CLICK_EVENT , this . _click . bind ( this )); // after element . addEventListener ( 'click' , ( ev ) => this . _click ( ev )); WCF.Action.Delete and WCF.Action.Toggle # WCF.Action.Delete and WCF.Action.Toggle were used for buttons to delete or enable/disable objects via JavaScript. In each template, WCF.Action.Delete or WCF.Action.Toggle instances had to be manually created for each object listing. With version 5.4 of WoltLab Suite, we have added a CSS selector-based global TypeScript module that only requires specific CSS classes to be added to the HTML structure for these buttons to work. Additionally, we have added a new {objectAction} template plugin, which generates these buttons reducing the amount of boilerplate template code. The required base HTML structure is as follows: A .jsObjectActionContainer element with a data-object-action-class-name attribute that contains the name of PHP class that executes the actions. .jsObjectActionObject elements within .jsObjectActionContainer that represent the objects for which actions can be executed. Each .jsObjectActionObject element must have a data-object-id attribute with the id of the object. .jsObjectAction elements within .jsObjectActionObject for each action with a data-object-action attribute with the name of the action. These elements can be generated with the {objectAction} template plugin for the delete and toggle action. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <table class=\"table jsObjectActionContainer\" { * * } data-object-action-class-name=\"wcf\\data\\foo\\FooAction\"> <thead> <tr> { * \u2026 * } </tr> </thead> <tbody> { foreach from = $objects item = foo } <tr class=\"jsObjectActionObject\" data-object-id=\" { @ $foo -> getObjectID () } \"> <td class=\"columnIcon\"> { objectAction action = \"toggle\" isDisabled = $foo -> isDisabled } { objectAction action = \"delete\" objectTitle = $foo -> getTitle () } { * \u2026 * } </td> { * \u2026 * } </tr> { /foreach } </tbody> </table> Please refer to the documentation in ObjectActionFunctionTemplatePlugin for details and examples on how to use this template plugin. The relevant TypeScript module registering the event listeners on the object action buttons is Ui/Object/Action . When an action button is clicked, an AJAX request is sent using the PHP class name and action name. After the successful execution of the action, the page is either reloaded if the action button has a data-object-action-success=\"reload\" attribute or an event using the EventHandler module is fired using WoltLabSuite/Core/Ui/Object/Action as the identifier and the object action name. Ui/Object/Action/Delete and Ui/Object/Action/Toggle listen to these events and update the user interface depending on the execute action by removing the object or updating the toggle button, respectively. Converting from WCF.Action.* to the new approach requires minimal changes per template, as shown in the relevant pull request #4080 . WCF.Table.EmptyTableHandler # When all objects in a table or list are deleted via their delete button or clipboard actions, an empty table or list can remain. Previously, WCF.Table.EmptyTableHandler had to be explicitly used in each template for these tables and lists to reload the page. As a TypeScript-based replacement for WCF.Table.EmptyTableHandler that is only initialized once globally, WoltLabSuite/Core/Ui/Empty was added. To use this new module, you only have to add the CSS class jsReloadPageWhenEmpty to the relevant HTML element. Once this HTML element no longer has child elements, the page is reloaded. To also cover scenarios in which there are fixed child elements that should not be considered when determining if there are no child elements, the data-reload-page-when-empty=\"ignore\" can be set for these elements. Examples: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <table class=\"table\"> <thead> <tr> { * \u2026 * } </tr> </thead> <tbody class=\"jsReloadPageWhenEmpty\"> { foreach from = $objects item = object } <tr> { * \u2026 * } </tr> { /foreach } </tbody> </table> 1 2 3 4 5 6 7 8 9 10 11 12 13 <div class=\"section tabularBox messageGroupList\"> <ol class=\"tabularList jsReloadPageWhenEmpty\"> <li class=\"tabularListRow tabularListRowHead\" data-reload-page-when-empty=\"ignore\"> { * \u2026 * } </li> { foreach from = $objects item = object } <li> { * \u2026 * } </li> { /foreach } </ol> </div>","title":"TypeScript and JavaScript"},{"location":"migration/wsc53/javascript/#migrating-from-wsc-53-typescript-and-javascript","text":"","title":"Migrating from WSC 5.3 - TypeScript and JavaScript"},{"location":"migration/wsc53/javascript/#typescript","text":"WoltLab Suite 5.4 introduces TypeScript support. Learn about consuming WoltLab Suite\u2019s types in the TypeScript section of the JavaScript API documentation. The JavaScript API documentation will be updated to properly take into account the changes that came with the new TypeScript support in the future. Existing AMD based modules have been migrated to TypeScript, but will expose the existing and known API. It is recommended that you migrate your custom packages to make use of TypeScript. It will make consuming newly written modules that properly leverage TypeScript\u2019s features much more pleasant and will also ease using existing modules due to proper autocompletion and type checking.","title":"TypeScript"},{"location":"migration/wsc53/javascript/#replacements-for-deprecated-components","text":"The helper functions in wcf.globalHelper.js should not be used anymore but replaced by their native counterpart: Function Native Replacement elCreate(tag) document.createElement(tag) elRemove(el) el.remove() elShow(el) DomUtil.show(el) elHide(el) DomUtil.hide(el) elIsHidden(el) DomUtil.isHidden(el) elToggle(el) DomUtil.toggle(el) elAttr(el, \"attr\") el.attr or el.getAttribute(\"attr\") elData(el, \"data\") el.dataset.data elDataBool(element, \"data\") Core.stringToBool(el.dataset.data) elById(id) document.getElementById(id) elBySel(sel) document.querySelector(sel) elBySel(sel, el) el.querySelector(sel) elBySelAll(sel) document.querySelectorAll(sel) elBySelAll(sel, el) el.querySelectorAll(sel) elBySelAll(sel, el, callback) el.querySelectorAll(sel).forEach((el) => callback(el)); elClosest(el, sel) el.closest(sel) elByClass(class) document.getElementsByClassName(class) elByClass(class, el) el.getElementsByClassName(class) elByTag(tag) document.getElementsByTagName(tag) elByTag(tag, el) el.getElementsByTagName(tag) elInnerError(el, message, isHtml) DomUtil.innerError(el, message, isHtml) Additionally, the following modules should also be replaced by their native counterpart: Module Native Replacement WoltLabSuite/Core/Dictionary Map WoltLabSuite/Core/List Set WoltLabSuite/Core/ObjectMap WeakMap For event listeners on click events, WCF_CLICK_EVENT is deprecated and should no longer be used. Instead, use click directly: 1 2 3 4 5 // before element . addEventListener ( WCF_CLICK_EVENT , this . _click . bind ( this )); // after element . addEventListener ( 'click' , ( ev ) => this . _click ( ev ));","title":"Replacements for Deprecated Components"},{"location":"migration/wsc53/javascript/#wcfactiondelete-and-wcfactiontoggle","text":"WCF.Action.Delete and WCF.Action.Toggle were used for buttons to delete or enable/disable objects via JavaScript. In each template, WCF.Action.Delete or WCF.Action.Toggle instances had to be manually created for each object listing. With version 5.4 of WoltLab Suite, we have added a CSS selector-based global TypeScript module that only requires specific CSS classes to be added to the HTML structure for these buttons to work. Additionally, we have added a new {objectAction} template plugin, which generates these buttons reducing the amount of boilerplate template code. The required base HTML structure is as follows: A .jsObjectActionContainer element with a data-object-action-class-name attribute that contains the name of PHP class that executes the actions. .jsObjectActionObject elements within .jsObjectActionContainer that represent the objects for which actions can be executed. Each .jsObjectActionObject element must have a data-object-id attribute with the id of the object. .jsObjectAction elements within .jsObjectActionObject for each action with a data-object-action attribute with the name of the action. These elements can be generated with the {objectAction} template plugin for the delete and toggle action. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <table class=\"table jsObjectActionContainer\" { * * } data-object-action-class-name=\"wcf\\data\\foo\\FooAction\"> <thead> <tr> { * \u2026 * } </tr> </thead> <tbody> { foreach from = $objects item = foo } <tr class=\"jsObjectActionObject\" data-object-id=\" { @ $foo -> getObjectID () } \"> <td class=\"columnIcon\"> { objectAction action = \"toggle\" isDisabled = $foo -> isDisabled } { objectAction action = \"delete\" objectTitle = $foo -> getTitle () } { * \u2026 * } </td> { * \u2026 * } </tr> { /foreach } </tbody> </table> Please refer to the documentation in ObjectActionFunctionTemplatePlugin for details and examples on how to use this template plugin. The relevant TypeScript module registering the event listeners on the object action buttons is Ui/Object/Action . When an action button is clicked, an AJAX request is sent using the PHP class name and action name. After the successful execution of the action, the page is either reloaded if the action button has a data-object-action-success=\"reload\" attribute or an event using the EventHandler module is fired using WoltLabSuite/Core/Ui/Object/Action as the identifier and the object action name. Ui/Object/Action/Delete and Ui/Object/Action/Toggle listen to these events and update the user interface depending on the execute action by removing the object or updating the toggle button, respectively. Converting from WCF.Action.* to the new approach requires minimal changes per template, as shown in the relevant pull request #4080 .","title":"WCF.Action.Delete and WCF.Action.Toggle"},{"location":"migration/wsc53/javascript/#wcftableemptytablehandler","text":"When all objects in a table or list are deleted via their delete button or clipboard actions, an empty table or list can remain. Previously, WCF.Table.EmptyTableHandler had to be explicitly used in each template for these tables and lists to reload the page. As a TypeScript-based replacement for WCF.Table.EmptyTableHandler that is only initialized once globally, WoltLabSuite/Core/Ui/Empty was added. To use this new module, you only have to add the CSS class jsReloadPageWhenEmpty to the relevant HTML element. Once this HTML element no longer has child elements, the page is reloaded. To also cover scenarios in which there are fixed child elements that should not be considered when determining if there are no child elements, the data-reload-page-when-empty=\"ignore\" can be set for these elements. Examples: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <table class=\"table\"> <thead> <tr> { * \u2026 * } </tr> </thead> <tbody class=\"jsReloadPageWhenEmpty\"> { foreach from = $objects item = object } <tr> { * \u2026 * } </tr> { /foreach } </tbody> </table> 1 2 3 4 5 6 7 8 9 10 11 12 13 <div class=\"section tabularBox messageGroupList\"> <ol class=\"tabularList jsReloadPageWhenEmpty\"> <li class=\"tabularListRow tabularListRowHead\" data-reload-page-when-empty=\"ignore\"> { * \u2026 * } </li> { foreach from = $objects item = object } <li> { * \u2026 * } </li> { /foreach } </ol> </div>","title":"WCF.Table.EmptyTableHandler"},{"location":"migration/wsc53/libraries/","text":"Migrating from WSC 5.3 - Third Party Libraries # Guzzle # The bundled Guzzle version was updated to Guzzle 7. No breaking changes are expected for simple uses. A detailed Guzzle migration guide can be found in the Guzzle documentation. The explicit sink that was recommended in the migration guide for WSC 5.2 can now be removed, as the Guzzle issue #2735 was fixed in Guzzle 7. Emogrifier / CSS Inliner # The Emogrifier library was updated from version 2.2 to 5.0. This update comes with a breaking change, as the Emogrifier class was removed. With the updated Emogrifier library, the CssInliner class must be used instead. No compatibility layer was added for the Emogrifier class, as the Emogrifier library's purpose was to be used within the email subsystem of WoltLab Suite. In case you use Emogrifier directly within your own code, you will need to adjust the usage. Refer to the Emogrifier CHANGELOG and WoltLab/WCF #3738 if you need help making the necessary adjustments. If you only use Emogrifier indirectly by sending HTML mail via the email subsystem then you might notice unexpected visual changes due to the improved CSS support. Double check your CSS declarations and particularly the specificity of your selectors in these cases. scssphp # scssphp was updated from version 1.1 to 1.4. If you interact with scssphp only by deploying .scss files, then you should not experience any breaking changes, except when the improved SCSS compatibility interprets your SCSS code differently. If you happen to directly use scssphp in your PHP code, you should be aware that scssphp deprecated the use of output formatters in favor of a simple output style enum. Refer to WoltLab/WCF #3851 and the scssphp releases for details. Constant Time Encoder # WoltLab Suite 5.4 ships the paragonie/constant_time_encoding library . It is recommended to use this library to perform encoding and decoding of secrets to prevent leaks via cache timing attacks. Refer to the library author\u2019s blog post for more background detail. For the common case of encoding the bytes taken from a CSPRNG in hexadecimal form, the required change would look like the following: Previously: 1 2 <? php $encoded = hex2bin ( random_bytes ( 16 )); Now: 1 2 3 4 5 6 7 8 <? php use ParagonIE\\ConstantTime\\Hex ; // For security reasons you should add the backslash // to ensure you refer to the `random_bytes` function // within the global namespace and not a function // defined in the current namespace. $encoded = Hex :: encode ( \\random_bytes ( 16 )); Please refer to the documentation and source code of the paragonie/constant_time_encoding library to learn how to use the library with different encodings (e.g. base64).","title":"Third Party Libraries"},{"location":"migration/wsc53/libraries/#migrating-from-wsc-53-third-party-libraries","text":"","title":"Migrating from WSC 5.3 - Third Party Libraries"},{"location":"migration/wsc53/libraries/#guzzle","text":"The bundled Guzzle version was updated to Guzzle 7. No breaking changes are expected for simple uses. A detailed Guzzle migration guide can be found in the Guzzle documentation. The explicit sink that was recommended in the migration guide for WSC 5.2 can now be removed, as the Guzzle issue #2735 was fixed in Guzzle 7.","title":"Guzzle"},{"location":"migration/wsc53/libraries/#emogrifier-css-inliner","text":"The Emogrifier library was updated from version 2.2 to 5.0. This update comes with a breaking change, as the Emogrifier class was removed. With the updated Emogrifier library, the CssInliner class must be used instead. No compatibility layer was added for the Emogrifier class, as the Emogrifier library's purpose was to be used within the email subsystem of WoltLab Suite. In case you use Emogrifier directly within your own code, you will need to adjust the usage. Refer to the Emogrifier CHANGELOG and WoltLab/WCF #3738 if you need help making the necessary adjustments. If you only use Emogrifier indirectly by sending HTML mail via the email subsystem then you might notice unexpected visual changes due to the improved CSS support. Double check your CSS declarations and particularly the specificity of your selectors in these cases.","title":"Emogrifier / CSS Inliner"},{"location":"migration/wsc53/libraries/#scssphp","text":"scssphp was updated from version 1.1 to 1.4. If you interact with scssphp only by deploying .scss files, then you should not experience any breaking changes, except when the improved SCSS compatibility interprets your SCSS code differently. If you happen to directly use scssphp in your PHP code, you should be aware that scssphp deprecated the use of output formatters in favor of a simple output style enum. Refer to WoltLab/WCF #3851 and the scssphp releases for details.","title":"scssphp"},{"location":"migration/wsc53/libraries/#constant-time-encoder","text":"WoltLab Suite 5.4 ships the paragonie/constant_time_encoding library . It is recommended to use this library to perform encoding and decoding of secrets to prevent leaks via cache timing attacks. Refer to the library author\u2019s blog post for more background detail. For the common case of encoding the bytes taken from a CSPRNG in hexadecimal form, the required change would look like the following: Previously: 1 2 <? php $encoded = hex2bin ( random_bytes ( 16 )); Now: 1 2 3 4 5 6 7 8 <? php use ParagonIE\\ConstantTime\\Hex ; // For security reasons you should add the backslash // to ensure you refer to the `random_bytes` function // within the global namespace and not a function // defined in the current namespace. $encoded = Hex :: encode ( \\random_bytes ( 16 )); Please refer to the documentation and source code of the paragonie/constant_time_encoding library to learn how to use the library with different encodings (e.g. base64).","title":"Constant Time Encoder"},{"location":"migration/wsc53/php/","text":"Migrating from WSC 5.3 - PHP # Minimum requirements # The minimum requirements have been increased to the following: PHP: 7.2.24 MySQL: 5.7.31 or 8.0.19 MariaDB: 10.1.44 Most notably PHP 7.2 contains usable support for scalar types by the addition of nullable types in PHP 7.1 and parameter type widening in PHP 7.2. It is recommended to make use of scalar types and other newly introduced features whereever possible. Please refer to the PHP documentation for details. Flood Control # To prevent users from creating massive amounts of contents in short periods of time, i.e., spam, existing systems already use flood control mechanisms to limit the amount of contents created within a certain period of time. With WoltLab Suite 5.4, we have added a general API that manages such rate limiting. Leveraging this API is easily done. Register an object type for the definition com.woltlab.wcf.floodControl : com.example.foo.myContent . Whenever the active user creates content of this type, call 1 FloodControl :: getInstance () -> registerContent ( 'com.example.foo.myContent' ); You should only call this method if the user creates the content themselves. If the content is automatically created by the system, for example when copying / duplicating existing content, no activity should be registered. To check the last time when the active user created content of the relevant type, use 1 FloodControl :: getInstance () -> getLastTime ( 'com.example.foo.myContent' ); If you want to limit the number of content items created within a certain period of time, for example within one day, use 1 2 3 4 5 $data = FloodControl :: getInstance () -> countContent ( 'com.example.foo.myContent' , new \\DateInterval ( 'P1D' )); // number of content items created within the last day $count = $data [ 'count' ]; // timestamp when the earliest content item was created within the last day $earliestTime = $data [ 'earliestTime' ]; The method also returns earliestTime so that you can tell the user in the error message when they are able again to create new content of the relevant type. Flood control entries are only stored for 31 days and older entries are cleaned up daily. The previously mentioned methods of FloodControl use the active user and the current timestamp as reference point. FloodControl also provides methods to register content or check flood control for other registered users or for guests via their IP address. For further details on these methods, please refer to the documentation in the FloodControl class . Do not interact directly with the flood control database table but only via the FloodControl class! DatabasePackageInstallationPlugin # DatabasePackageInstallationPlugin is a new idempotent package installation plugin (thus it is available in the sync function in the devtools) to update the database schema using the PHP-based database API. DatabasePackageInstallationPlugin is similar to ScriptPackageInstallationPlugin by requiring a PHP script that is included during the execution of the script. The script is expected to return an array of DatabaseTable objects representing the schema changes so that in contrast to using ScriptPackageInstallationPlugin , no DatabaseTableChangeProcessor object has to be created. The PHP file must be located in the acp/database/ directory for the devtools sync function to recognize the file. PHP Database API # The PHP API to add and change database tables during package installations and updates in the wcf\\system\\database\\table namespace now also supports renaming existing table columns with the new IDatabaseTableColumn::renameTo() method: 1 2 3 4 5 PartialDatabaseTable :: create ( 'wcf1_test' ) -> columns ([ NotNullInt10DatabaseTableColumn :: create ( 'oldName' ) -> renameTo ( 'newName' ) ]); Like with every change to existing database tables, packages can only rename columns that they installed. Captcha # The reCAPTCHA v1 implementation was completely removed. This includes the \\wcf\\system\\recaptcha\\RecaptchaHandler class (not to be confused with the one in the captcha namespace). The reCAPTCHA v1 endpoints have already been turned off by Google and always return a HTTP 404. Thus the implementation was completely non-functional even before this change. See WoltLab/WCF#3781 for details. Search # The generic implementation in the AbstractSearchEngine::parseSearchQuery() method was dangerous, because it did not have knowledge about the search engine\u2019s specifics. The implementation was completely removed: AbstractSearchEngine::parseSearchQuery() now always throws a \\BadMethodCallException . If you implemented a custom search engine and relied on this method, you can inline the previous implementation to preserve existing behavior. You should take the time to verify the rewritten queries against the manual of the search engine to make sure it cannot generate malformed queries or security issues. See WoltLab/WCF#3815 for details. Styles # The StyleCompiler class is marked final now. The internal SCSS compiler object being stored in the $compiler property was a design issue that leaked compiler state across multiple compiled styles, possibly causing misgenerated stylesheets. As the removal of the $compiler property effectively broke compatibility within the StyleCompiler and as the StyleCompiler never was meant to be extended, it was marked final. See WoltLab/WCF#3929 for details. Tags # Use of the wcf1_tag_to_object.languageID column is deprecated. The languageID column is redundant, because its value can be derived from the tagID . With WoltLab Suite 5.4, it will no longer be part of any indices, allowing more efficient index usage in the general case. If you need to filter the contents of wcf1_tag_to_object by language, you should perform an INNER JOIN wcf1_tag tag ON tag.tagID = tag_to_object.tagID and filter on wcf1_tag.languageID . See WoltLab/WCF#3904 for details. Avatars # The ISafeFormatAvatar interface was added to properly support fallback image types for use in emails. If your custom IUserAvatar implementation supports image types without broad support (i.e. anything other than PNG, JPEG, and GIF), then you should implement the ISafeFormatAvatar interface to return a fallback PNG, JPEG, or GIF image. See WoltLab/WCF#4001 for details. lineBreakSeparatedText Option Type # Currently, several of the (user group) options installed by our packages use the textarea option type and split its value by linebreaks to get a list of items, for example for allowed file extensions. To improve the user interface when setting up the value of such options, we have added the lineBreakSeparatedText option type as a drop-in replacement where the individual items are explicitly represented as distinct items in the user interface. Ignoring of Users # WoltLab Suite 5.4 distinguishes between blocking direct contact only and hiding all contents when ignoring users. To allow for detecting the difference, the UserProfile::getIgnoredUsers() and UserProfile::isIgnoredUser() methods received a new $type parameter. Pass either UserIgnore::TYPE_BLOCK_DIRECT_CONTACT or UserIgnore::TYPE_HIDE_MESSAGES depending on whether the check refers to a non-directed usage or content. See WoltLab/WCF#4064 and WoltLab/WCF#3981 for details. Database::prepare() # Database::prepare(string $statement, int $limit = 0, int $offset = 0): PreparedStatement works the same way as Database::prepareStatement() but additionally also replaces all occurences of app1_ with app{WCF_N}_ for all installed apps. This new method makes it superfluous to use WCF_N when building queries.","title":"PHP API"},{"location":"migration/wsc53/php/#migrating-from-wsc-53-php","text":"","title":"Migrating from WSC 5.3 - PHP"},{"location":"migration/wsc53/php/#minimum-requirements","text":"The minimum requirements have been increased to the following: PHP: 7.2.24 MySQL: 5.7.31 or 8.0.19 MariaDB: 10.1.44 Most notably PHP 7.2 contains usable support for scalar types by the addition of nullable types in PHP 7.1 and parameter type widening in PHP 7.2. It is recommended to make use of scalar types and other newly introduced features whereever possible. Please refer to the PHP documentation for details.","title":"Minimum requirements"},{"location":"migration/wsc53/php/#flood-control","text":"To prevent users from creating massive amounts of contents in short periods of time, i.e., spam, existing systems already use flood control mechanisms to limit the amount of contents created within a certain period of time. With WoltLab Suite 5.4, we have added a general API that manages such rate limiting. Leveraging this API is easily done. Register an object type for the definition com.woltlab.wcf.floodControl : com.example.foo.myContent . Whenever the active user creates content of this type, call 1 FloodControl :: getInstance () -> registerContent ( 'com.example.foo.myContent' ); You should only call this method if the user creates the content themselves. If the content is automatically created by the system, for example when copying / duplicating existing content, no activity should be registered. To check the last time when the active user created content of the relevant type, use 1 FloodControl :: getInstance () -> getLastTime ( 'com.example.foo.myContent' ); If you want to limit the number of content items created within a certain period of time, for example within one day, use 1 2 3 4 5 $data = FloodControl :: getInstance () -> countContent ( 'com.example.foo.myContent' , new \\DateInterval ( 'P1D' )); // number of content items created within the last day $count = $data [ 'count' ]; // timestamp when the earliest content item was created within the last day $earliestTime = $data [ 'earliestTime' ]; The method also returns earliestTime so that you can tell the user in the error message when they are able again to create new content of the relevant type. Flood control entries are only stored for 31 days and older entries are cleaned up daily. The previously mentioned methods of FloodControl use the active user and the current timestamp as reference point. FloodControl also provides methods to register content or check flood control for other registered users or for guests via their IP address. For further details on these methods, please refer to the documentation in the FloodControl class . Do not interact directly with the flood control database table but only via the FloodControl class!","title":"Flood Control"},{"location":"migration/wsc53/php/#databasepackageinstallationplugin","text":"DatabasePackageInstallationPlugin is a new idempotent package installation plugin (thus it is available in the sync function in the devtools) to update the database schema using the PHP-based database API. DatabasePackageInstallationPlugin is similar to ScriptPackageInstallationPlugin by requiring a PHP script that is included during the execution of the script. The script is expected to return an array of DatabaseTable objects representing the schema changes so that in contrast to using ScriptPackageInstallationPlugin , no DatabaseTableChangeProcessor object has to be created. The PHP file must be located in the acp/database/ directory for the devtools sync function to recognize the file.","title":"DatabasePackageInstallationPlugin"},{"location":"migration/wsc53/php/#php-database-api","text":"The PHP API to add and change database tables during package installations and updates in the wcf\\system\\database\\table namespace now also supports renaming existing table columns with the new IDatabaseTableColumn::renameTo() method: 1 2 3 4 5 PartialDatabaseTable :: create ( 'wcf1_test' ) -> columns ([ NotNullInt10DatabaseTableColumn :: create ( 'oldName' ) -> renameTo ( 'newName' ) ]); Like with every change to existing database tables, packages can only rename columns that they installed.","title":"PHP Database API"},{"location":"migration/wsc53/php/#captcha","text":"The reCAPTCHA v1 implementation was completely removed. This includes the \\wcf\\system\\recaptcha\\RecaptchaHandler class (not to be confused with the one in the captcha namespace). The reCAPTCHA v1 endpoints have already been turned off by Google and always return a HTTP 404. Thus the implementation was completely non-functional even before this change. See WoltLab/WCF#3781 for details.","title":"Captcha"},{"location":"migration/wsc53/php/#search","text":"The generic implementation in the AbstractSearchEngine::parseSearchQuery() method was dangerous, because it did not have knowledge about the search engine\u2019s specifics. The implementation was completely removed: AbstractSearchEngine::parseSearchQuery() now always throws a \\BadMethodCallException . If you implemented a custom search engine and relied on this method, you can inline the previous implementation to preserve existing behavior. You should take the time to verify the rewritten queries against the manual of the search engine to make sure it cannot generate malformed queries or security issues. See WoltLab/WCF#3815 for details.","title":"Search"},{"location":"migration/wsc53/php/#styles","text":"The StyleCompiler class is marked final now. The internal SCSS compiler object being stored in the $compiler property was a design issue that leaked compiler state across multiple compiled styles, possibly causing misgenerated stylesheets. As the removal of the $compiler property effectively broke compatibility within the StyleCompiler and as the StyleCompiler never was meant to be extended, it was marked final. See WoltLab/WCF#3929 for details.","title":"Styles"},{"location":"migration/wsc53/php/#tags","text":"Use of the wcf1_tag_to_object.languageID column is deprecated. The languageID column is redundant, because its value can be derived from the tagID . With WoltLab Suite 5.4, it will no longer be part of any indices, allowing more efficient index usage in the general case. If you need to filter the contents of wcf1_tag_to_object by language, you should perform an INNER JOIN wcf1_tag tag ON tag.tagID = tag_to_object.tagID and filter on wcf1_tag.languageID . See WoltLab/WCF#3904 for details.","title":"Tags"},{"location":"migration/wsc53/php/#avatars","text":"The ISafeFormatAvatar interface was added to properly support fallback image types for use in emails. If your custom IUserAvatar implementation supports image types without broad support (i.e. anything other than PNG, JPEG, and GIF), then you should implement the ISafeFormatAvatar interface to return a fallback PNG, JPEG, or GIF image. See WoltLab/WCF#4001 for details.","title":"Avatars"},{"location":"migration/wsc53/php/#linebreakseparatedtext-option-type","text":"Currently, several of the (user group) options installed by our packages use the textarea option type and split its value by linebreaks to get a list of items, for example for allowed file extensions. To improve the user interface when setting up the value of such options, we have added the lineBreakSeparatedText option type as a drop-in replacement where the individual items are explicitly represented as distinct items in the user interface.","title":"lineBreakSeparatedText Option Type"},{"location":"migration/wsc53/php/#ignoring-of-users","text":"WoltLab Suite 5.4 distinguishes between blocking direct contact only and hiding all contents when ignoring users. To allow for detecting the difference, the UserProfile::getIgnoredUsers() and UserProfile::isIgnoredUser() methods received a new $type parameter. Pass either UserIgnore::TYPE_BLOCK_DIRECT_CONTACT or UserIgnore::TYPE_HIDE_MESSAGES depending on whether the check refers to a non-directed usage or content. See WoltLab/WCF#4064 and WoltLab/WCF#3981 for details.","title":"Ignoring of Users"},{"location":"migration/wsc53/php/#databaseprepare","text":"Database::prepare(string $statement, int $limit = 0, int $offset = 0): PreparedStatement works the same way as Database::prepareStatement() but additionally also replaces all occurences of app1_ with app{WCF_N}_ for all installed apps. This new method makes it superfluous to use WCF_N when building queries.","title":"Database::prepare()"},{"location":"migration/wsc53/session/","text":"Migrating from WSC 5.3 - Session Handling and Authentication # WoltLab Suite 5.4 includes a completely refactored session handling. As long as you only interact with sessions via WCF::getSession() , especially when you perform read-only accesses, you should not notice any breaking changes. You might appreciate some of the new session methods if you process security sensitive data. Summary and Concepts # Most of the changes revolve around the removal of the legacy persistent login functionality and the assumption that every user has a single session only. Both aspects are related to each other. Legacy Persistent Login # The legacy persistent login was rather an automated login. Upon bootstrapping a session, it was checked whether the user had a cookie pair storing the user\u2019s userID and (a single BCrypt hash of) the user\u2019s password. If such a cookie pair exists and the BCrypt hash within the cookie matches the user\u2019s password hash when hashed again, the session would immediately changeUser() to the respective user. This legacy persistent login was completely removed. Instead, any sessions that belong to an authenticated user will automatically be long-lived. These long-lived sessions expire no sooner than 14 days after the last activity, ensuring that the user continously stays logged in, provided that they visit the page at least once per fortnight. Multiple Sessions # To allow for a proper separation of these long-lived user sessions, WoltLab Suite now allows for multiple sessions per user. These sessions are completely unrelated to each other. Specifically, they do not share session variables and they expire independently. As the existing wcf1_session table is also used for the online lists and location tracking, it will be maintained on a best effort basis. It no longer stores any private session data. The actual sessions storing security sensitive information are in an unrelated location. They must only be accessed via the PHP API exposed by the SessionHandler . Merged ACP and Frontend Sessions # WoltLab Suite 5.4 shares a single session across both the frontend, as well as the ACP. When a user logs in to the frontend, they will also be logged into the ACP and vice versa. Actual access to the ACP is controlled via the new reauthentication mechanism . The session variable store is scoped: Session variables set within the frontend are not available within the ACP and vice versa. Improved Authentication and Reauthentication # WoltLab Suite 5.4 ships with multi-factor authentication support and a generic re-authentication implementation that can be used to verify the account owner\u2019s presence. Additions and Changes # Password Hashing # WoltLab Suite 5.4 includes a new object-oriented password hashing framework that is modeled after PHP\u2019s password_* API. Check PasswordAlgorithmManager and IPasswordAlgorithm for details. The new default password hash is a standard BCrypt hash. All newly generated hashes in wcf1_user.password will now include a type prefix, instead of just passwords imported from other systems. Session Storage # The wcf1_session table will no longer be used for session storage. Instead, it is maintained for compatibility with existing online lists. The actual session storage is considered an implementation detail and you must not directly interact with the session tables. Future versions might support alternative session backends, such as Redis. Do not interact directly with the session database tables but only via the SessionHandler class! Reauthentication # For security sensitive processing, you might want to ensure that the account owner is actually present instead of a third party accessing a session that was accidentally left logged in. WoltLab Suite 5.4 ships with a generic reauthentication framework. To request reauthentication within your controller you need to: Use the wcf\\system\\user\\authentication\\TReauthenticationCheck trait. Call: 1 2 3 $this -> requestReauthentication ( LinkHandler :: getInstance () -> getControllerLink ( static :: class , [ /* additional parameters */ ])); requestReauthentication() will check if the user has recently authenticated themselves. If they did, the request proceeds as usual. Otherwise, they will be asked to reauthenticate themselves. After the successful authentication, they will be redirected to the URL that was passed as the first parameter (the current controller within the example). Details can be found in WoltLab/WCF#3775 . Multi-factor Authentication # To implement multi-factor authentication securely, WoltLab Suite 5.4 implements the concept of a \u201cpending user change\u201d. The user will not be logged in (i.e. WCF::getUser()->userID returns null ) until they authenticate themselves with their second factor. Requesting multi-factor authentication is done on an opt-in basis for compatibility reasons. If you perform authentication yourself and do not trust the authentication source to perform multi-factor authentication itself, you will need to adjust your logic to request multi-factor authentication from WoltLab Suite: Previously: 1 WCF :: getSession () -> changeUser ( $targetUser ); Now: 1 2 3 4 5 6 7 8 9 10 $isPending = WCF :: getSession () -> changeUserAfterMultifactorAuthentication ( $targetUser ); if ( $isPending ) { // Redirect to the authentication form. The user will not be logged in. // Note: Do not use `getControllerLink` to support both the frontend as well as the ACP. HeaderUtil :: redirect ( LinkHandler :: getInstance () -> getLink ( 'MultifactorAuthentication' , [ 'url' => /* Return To */ , ])); exit ; } // Proceed as usual. The user will be logged in. Adding Multi-factor Methods # Adding your own multi-factor method requires the implementation of a single object type: objectType.xml 1 2 3 4 5 6 7 <type> <name> com.example.multifactor.foobar </name> <definitionname> com.woltlab.wcf.multifactor </definitionname> <icon> <!-- Font Awesome 4 Icon Name goes here. --> </icon> <priority> <!-- Determines the sort order, higher priority will be preferred for authentication. --> </priority> <classname> wcf\\system\\user\\multifactor\\FoobarMultifactorMethod </classname> </type> The given classname must implement the IMultifactorMethod interface. As a self-contained example, you can find the initial implementation of the email multi-factor method in WoltLab/WCF#3729 . Please check the version history of the PHP class to make sure you do not miss important changes that were added later. Multi-factor authentication is security sensitive. Make sure to carefully read the remarks in IMultifactorMethod for possible issues. Also make sure to carefully test your implementation against all sorts of incorrect input and consider attack vectors such as race conditions. It is strongly recommended to generously check the current state by leveraging assertions and exceptions. Enforcing Multi-factor Authentication # To enforce Multi-factor Authentication within your controller you need to: Use the wcf\\system\\user\\multifactor\\TMultifactorRequirementEnforcer trait. Call: $this->enforceMultifactorAuthentication(); enforceMultifactorAuthentication() will check if the user is in a group that requires multi-factor authentication, but does not yet have multi-factor authentication enabled. If they did, the request proceeds as usual. Otherwise, a NamedUserException is thrown. Deprecations and Removals # SessionHandler # Most of the changes with regard to the new session handling happened in SessionHandler . Most notably, SessionHandler now is marked final to ensure proper encapsulation of data. A number of methods in SessionHandler are now deprecated and result in a noop. This change mostly affects methods that have been used to bootstrap the session, such as setHasValidCookie() . Additionally, accessing the following keys on the session is deprecated. They directly map to an existing method in another class and any uses can easily be updated: - ipAddress - userAgent - requestURI - requestMethod - lastActivityTime Refer to the implementation for details. ACP Sessions # The database tables related to ACP sessions have been removed. The PHP classes have been preserved due to being used within the class hierarchy of the legacy sessions. Cookies # The _userID , _password , _cookieHash and _cookieHash_acp cookies will no longer be created nor consumed. Virtual Sessions # The virtual session logic existed to support multiple devices per single session in wcf1_session . Virtual sessions are no longer required with the refactored session handling. Anything related to virtual sessions has been completely removed as they are considered an implementation detail. This removal includes PHP classes and database tables. Security Token Constants # The security token constants are deprecated. Instead, the methods of SessionHandler should be used (e.g. ->getSecurityToken() ). Within templates, you should migrate to the {csrfToken} tag in place of {@SECURITY_TOKEN_INPUT_TAG} . The {csrfToken} tag is a drop-in replacement and was backported to WoltLab Suite 5.2+, allowing you to maintain compatibility across a broad range of versions. PasswordUtil and Double BCrypt Hashes # Most of the methods in PasswordUtil are deprecated in favor of the new password hashing framework.","title":"Session Handling and Authentication"},{"location":"migration/wsc53/session/#migrating-from-wsc-53-session-handling-and-authentication","text":"WoltLab Suite 5.4 includes a completely refactored session handling. As long as you only interact with sessions via WCF::getSession() , especially when you perform read-only accesses, you should not notice any breaking changes. You might appreciate some of the new session methods if you process security sensitive data.","title":"Migrating from WSC 5.3 - Session Handling and Authentication"},{"location":"migration/wsc53/session/#summary-and-concepts","text":"Most of the changes revolve around the removal of the legacy persistent login functionality and the assumption that every user has a single session only. Both aspects are related to each other.","title":"Summary and Concepts"},{"location":"migration/wsc53/session/#legacy-persistent-login","text":"The legacy persistent login was rather an automated login. Upon bootstrapping a session, it was checked whether the user had a cookie pair storing the user\u2019s userID and (a single BCrypt hash of) the user\u2019s password. If such a cookie pair exists and the BCrypt hash within the cookie matches the user\u2019s password hash when hashed again, the session would immediately changeUser() to the respective user. This legacy persistent login was completely removed. Instead, any sessions that belong to an authenticated user will automatically be long-lived. These long-lived sessions expire no sooner than 14 days after the last activity, ensuring that the user continously stays logged in, provided that they visit the page at least once per fortnight.","title":"Legacy Persistent Login"},{"location":"migration/wsc53/session/#multiple-sessions","text":"To allow for a proper separation of these long-lived user sessions, WoltLab Suite now allows for multiple sessions per user. These sessions are completely unrelated to each other. Specifically, they do not share session variables and they expire independently. As the existing wcf1_session table is also used for the online lists and location tracking, it will be maintained on a best effort basis. It no longer stores any private session data. The actual sessions storing security sensitive information are in an unrelated location. They must only be accessed via the PHP API exposed by the SessionHandler .","title":"Multiple Sessions"},{"location":"migration/wsc53/session/#merged-acp-and-frontend-sessions","text":"WoltLab Suite 5.4 shares a single session across both the frontend, as well as the ACP. When a user logs in to the frontend, they will also be logged into the ACP and vice versa. Actual access to the ACP is controlled via the new reauthentication mechanism . The session variable store is scoped: Session variables set within the frontend are not available within the ACP and vice versa.","title":"Merged ACP and Frontend Sessions"},{"location":"migration/wsc53/session/#improved-authentication-and-reauthentication","text":"WoltLab Suite 5.4 ships with multi-factor authentication support and a generic re-authentication implementation that can be used to verify the account owner\u2019s presence.","title":"Improved Authentication and Reauthentication"},{"location":"migration/wsc53/session/#additions-and-changes","text":"","title":"Additions and Changes"},{"location":"migration/wsc53/session/#password-hashing","text":"WoltLab Suite 5.4 includes a new object-oriented password hashing framework that is modeled after PHP\u2019s password_* API. Check PasswordAlgorithmManager and IPasswordAlgorithm for details. The new default password hash is a standard BCrypt hash. All newly generated hashes in wcf1_user.password will now include a type prefix, instead of just passwords imported from other systems.","title":"Password Hashing"},{"location":"migration/wsc53/session/#session-storage","text":"The wcf1_session table will no longer be used for session storage. Instead, it is maintained for compatibility with existing online lists. The actual session storage is considered an implementation detail and you must not directly interact with the session tables. Future versions might support alternative session backends, such as Redis. Do not interact directly with the session database tables but only via the SessionHandler class!","title":"Session Storage"},{"location":"migration/wsc53/session/#reauthentication","text":"For security sensitive processing, you might want to ensure that the account owner is actually present instead of a third party accessing a session that was accidentally left logged in. WoltLab Suite 5.4 ships with a generic reauthentication framework. To request reauthentication within your controller you need to: Use the wcf\\system\\user\\authentication\\TReauthenticationCheck trait. Call: 1 2 3 $this -> requestReauthentication ( LinkHandler :: getInstance () -> getControllerLink ( static :: class , [ /* additional parameters */ ])); requestReauthentication() will check if the user has recently authenticated themselves. If they did, the request proceeds as usual. Otherwise, they will be asked to reauthenticate themselves. After the successful authentication, they will be redirected to the URL that was passed as the first parameter (the current controller within the example). Details can be found in WoltLab/WCF#3775 .","title":"Reauthentication"},{"location":"migration/wsc53/session/#multi-factor-authentication","text":"To implement multi-factor authentication securely, WoltLab Suite 5.4 implements the concept of a \u201cpending user change\u201d. The user will not be logged in (i.e. WCF::getUser()->userID returns null ) until they authenticate themselves with their second factor. Requesting multi-factor authentication is done on an opt-in basis for compatibility reasons. If you perform authentication yourself and do not trust the authentication source to perform multi-factor authentication itself, you will need to adjust your logic to request multi-factor authentication from WoltLab Suite: Previously: 1 WCF :: getSession () -> changeUser ( $targetUser ); Now: 1 2 3 4 5 6 7 8 9 10 $isPending = WCF :: getSession () -> changeUserAfterMultifactorAuthentication ( $targetUser ); if ( $isPending ) { // Redirect to the authentication form. The user will not be logged in. // Note: Do not use `getControllerLink` to support both the frontend as well as the ACP. HeaderUtil :: redirect ( LinkHandler :: getInstance () -> getLink ( 'MultifactorAuthentication' , [ 'url' => /* Return To */ , ])); exit ; } // Proceed as usual. The user will be logged in.","title":"Multi-factor Authentication"},{"location":"migration/wsc53/session/#adding-multi-factor-methods","text":"Adding your own multi-factor method requires the implementation of a single object type: objectType.xml 1 2 3 4 5 6 7 <type> <name> com.example.multifactor.foobar </name> <definitionname> com.woltlab.wcf.multifactor </definitionname> <icon> <!-- Font Awesome 4 Icon Name goes here. --> </icon> <priority> <!-- Determines the sort order, higher priority will be preferred for authentication. --> </priority> <classname> wcf\\system\\user\\multifactor\\FoobarMultifactorMethod </classname> </type> The given classname must implement the IMultifactorMethod interface. As a self-contained example, you can find the initial implementation of the email multi-factor method in WoltLab/WCF#3729 . Please check the version history of the PHP class to make sure you do not miss important changes that were added later. Multi-factor authentication is security sensitive. Make sure to carefully read the remarks in IMultifactorMethod for possible issues. Also make sure to carefully test your implementation against all sorts of incorrect input and consider attack vectors such as race conditions. It is strongly recommended to generously check the current state by leveraging assertions and exceptions.","title":"Adding Multi-factor Methods"},{"location":"migration/wsc53/session/#enforcing-multi-factor-authentication","text":"To enforce Multi-factor Authentication within your controller you need to: Use the wcf\\system\\user\\multifactor\\TMultifactorRequirementEnforcer trait. Call: $this->enforceMultifactorAuthentication(); enforceMultifactorAuthentication() will check if the user is in a group that requires multi-factor authentication, but does not yet have multi-factor authentication enabled. If they did, the request proceeds as usual. Otherwise, a NamedUserException is thrown.","title":"Enforcing Multi-factor Authentication"},{"location":"migration/wsc53/session/#deprecations-and-removals","text":"","title":"Deprecations and Removals"},{"location":"migration/wsc53/session/#sessionhandler","text":"Most of the changes with regard to the new session handling happened in SessionHandler . Most notably, SessionHandler now is marked final to ensure proper encapsulation of data. A number of methods in SessionHandler are now deprecated and result in a noop. This change mostly affects methods that have been used to bootstrap the session, such as setHasValidCookie() . Additionally, accessing the following keys on the session is deprecated. They directly map to an existing method in another class and any uses can easily be updated: - ipAddress - userAgent - requestURI - requestMethod - lastActivityTime Refer to the implementation for details.","title":"SessionHandler"},{"location":"migration/wsc53/session/#acp-sessions","text":"The database tables related to ACP sessions have been removed. The PHP classes have been preserved due to being used within the class hierarchy of the legacy sessions.","title":"ACP Sessions"},{"location":"migration/wsc53/session/#cookies","text":"The _userID , _password , _cookieHash and _cookieHash_acp cookies will no longer be created nor consumed.","title":"Cookies"},{"location":"migration/wsc53/session/#virtual-sessions","text":"The virtual session logic existed to support multiple devices per single session in wcf1_session . Virtual sessions are no longer required with the refactored session handling. Anything related to virtual sessions has been completely removed as they are considered an implementation detail. This removal includes PHP classes and database tables.","title":"Virtual Sessions"},{"location":"migration/wsc53/session/#security-token-constants","text":"The security token constants are deprecated. Instead, the methods of SessionHandler should be used (e.g. ->getSecurityToken() ). Within templates, you should migrate to the {csrfToken} tag in place of {@SECURITY_TOKEN_INPUT_TAG} . The {csrfToken} tag is a drop-in replacement and was backported to WoltLab Suite 5.2+, allowing you to maintain compatibility across a broad range of versions.","title":"Security Token Constants"},{"location":"migration/wsc53/session/#passwordutil-and-double-bcrypt-hashes","text":"Most of the methods in PasswordUtil are deprecated in favor of the new password hashing framework.","title":"PasswordUtil and Double BCrypt Hashes"},{"location":"migration/wsc53/templates/","text":"Migrating from WSC 5.3 - Templates and Languages # {csrfToken} # Going forward, any uses of the SECURITY_TOKEN_* constants should be avoided. To reference the CSRF token (\u201cSecurity Token\u201d) within templates, the {csrfToken} template plugin was added. Before: 1 2 { @ SECURITY_TOKEN_INPUT_TAG } { link controller = \"Foo\" } t= { @ SECURITY_TOKEN }{ /link } After: 1 2 3 { csrfToken } { link controller = \"Foo\" } t= { csrfToken type = url }{ /link } { * The use of the CSRF token in URLs is discouraged. Modifications should happen by means of a POST request. * } The {csrfToken} plugin was backported to WoltLab Suite 5.2 and higher, allowing compatibility with a large range of WoltLab Suite branches. See WoltLab/WCF#3612 for details. RSS Feed Links # Prior to version 5.4 of WoltLab Suite, all RSS feed links contained the access token for logged-in users so that the feed shows all contents the specific user has access to. With version 5.4, links with the CSS class rssFeed will open a dialog when clicked that offers the feed link with the access token for personal use and an anonymous feed link that can be shared with others. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 { * before * } <li> <a rel=\"alternate\" { * * } href=\" { if $__wcf -> getUser ()-> userID }{ link controller = 'ArticleFeed' } at= { @ $__wcf -> getUser ()-> userID } - { @ $__wcf -> getUser ()-> accessToken }{ /link }{ else }{ link controller = 'ArticleFeed' }{ /link }{ /if } \" { * * } title=\" { lang } wcf.global.button.rss { /lang } \" { * * } class=\"jsTooltip\" { * * } > <span class=\"icon icon16 fa-rss\"></span> <span class=\"invisible\"> { lang } wcf.global.button.rss { /lang } </span> </a> </li> { * after * } <li> <a rel=\"alternate\" { * * } href=\" { if $__wcf -> getUser ()-> userID }{ link controller = 'ArticleFeed' } at= { @ $__wcf -> getUser ()-> userID } - { @ $__wcf -> getUser ()-> accessToken }{ /link }{ else }{ link controller = 'ArticleFeed' }{ /link }{ /if } \" { * * } title=\" { lang } wcf.global.button.rss { /lang } \" { * * } class=\"rssFeed jsTooltip\" { * * } > <span class=\"icon icon16 fa-rss\"></span> <span class=\"invisible\"> { lang } wcf.global.button.rss { /lang } </span> </a> </li>","title":"Templates"},{"location":"migration/wsc53/templates/#migrating-from-wsc-53-templates-and-languages","text":"","title":"Migrating from WSC 5.3 - Templates and Languages"},{"location":"migration/wsc53/templates/#csrftoken","text":"Going forward, any uses of the SECURITY_TOKEN_* constants should be avoided. To reference the CSRF token (\u201cSecurity Token\u201d) within templates, the {csrfToken} template plugin was added. Before: 1 2 { @ SECURITY_TOKEN_INPUT_TAG } { link controller = \"Foo\" } t= { @ SECURITY_TOKEN }{ /link } After: 1 2 3 { csrfToken } { link controller = \"Foo\" } t= { csrfToken type = url }{ /link } { * The use of the CSRF token in URLs is discouraged. Modifications should happen by means of a POST request. * } The {csrfToken} plugin was backported to WoltLab Suite 5.2 and higher, allowing compatibility with a large range of WoltLab Suite branches. See WoltLab/WCF#3612 for details.","title":"{csrfToken}"},{"location":"migration/wsc53/templates/#rss-feed-links","text":"Prior to version 5.4 of WoltLab Suite, all RSS feed links contained the access token for logged-in users so that the feed shows all contents the specific user has access to. With version 5.4, links with the CSS class rssFeed will open a dialog when clicked that offers the feed link with the access token for personal use and an anonymous feed link that can be shared with others. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 { * before * } <li> <a rel=\"alternate\" { * * } href=\" { if $__wcf -> getUser ()-> userID }{ link controller = 'ArticleFeed' } at= { @ $__wcf -> getUser ()-> userID } - { @ $__wcf -> getUser ()-> accessToken }{ /link }{ else }{ link controller = 'ArticleFeed' }{ /link }{ /if } \" { * * } title=\" { lang } wcf.global.button.rss { /lang } \" { * * } class=\"jsTooltip\" { * * } > <span class=\"icon icon16 fa-rss\"></span> <span class=\"invisible\"> { lang } wcf.global.button.rss { /lang } </span> </a> </li> { * after * } <li> <a rel=\"alternate\" { * * } href=\" { if $__wcf -> getUser ()-> userID }{ link controller = 'ArticleFeed' } at= { @ $__wcf -> getUser ()-> userID } - { @ $__wcf -> getUser ()-> accessToken }{ /link }{ else }{ link controller = 'ArticleFeed' }{ /link }{ /if } \" { * * } title=\" { lang } wcf.global.button.rss { /lang } \" { * * } class=\"rssFeed jsTooltip\" { * * } > <span class=\"icon icon16 fa-rss\"></span> <span class=\"invisible\"> { lang } wcf.global.button.rss { /lang } </span> </a> </li>","title":"RSS Feed Links"},{"location":"migration/wsc54/deprecations_removals/","text":"Migrating from WSC 5.4 - Deprecations and Removals # With version 5.5, we have deprecated certain components and removed several other components that have been deprecated for many years. Deprecations # PHP # Classes # filebase\\system\\file\\FileDataHandler (use filebase\\system\\cache\\runtime\\FileRuntimeCache ) wcf\\action\\AbstractAjaxAction (use PSR-7 responses, WoltLab/WCF#4437 ) wcf\\data\\IExtendedMessageQuickReplyAction ( WoltLab/WCF#4575 ) wcf\\form\\SearchForm (see WoltLab/WCF#4605 ) wcf\\page\\AbstractSecurePage ( WoltLab/WCF#4515 ) wcf\\page\\SearchResultPage (see WoltLab/WCF#4605 ) wcf\\system\\database\\table\\column\\TUnsupportedDefaultValue (do not implement IDefaultValueDatabaseTableColumn , see WoltLab/WCF#4733 ) wcf\\system\\exception\\ILoggingAwareException ( WoltLab/WCF#4547 ) wcf\\system\\io\\FTP (directly use the FTP extension) wcf\\system\\search\\AbstractSearchableObjectType (use AbstractSearchProvider instead, see WoltLab/WCF#4605 ) wcf\\system\\search\\elasticsearch\\ElasticsearchException wcf\\system\\search\\ISearchableObjectType (use ISearchProvider instead, see WoltLab/WCF#4605 ) wcf\\util\\PasswordUtil Methods # wcf\\action\\MessageQuoteAction::markForRemoval() ( WoltLab/WCF#4452 ) wcf\\data\\user\\avatar\\UserAvatarAction::fetchRemoteAvatar() ( WoltLab/WCF#4744 ) wcf\\data\\user\\notification\\UserNotificationAction::getOutstandingNotifications() ( WoltLab/WCF#4603 ) wcf\\data\\moderation\\queue\\ModerationQueueAction::getOutstandingQueues() ( WoltLab/WCF#4603 ) wcf\\system\\message\\QuickReplyManager::setTmpHash() ( WoltLab/WCF#4575 ) wcf\\system\\request\\Request::isExecuted() ( WoltLab/WCF#4485 ) wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::query() wcf\\system\\session\\Session::getDeviceIcon() ( WoltLab/WCF#4525 ) wcf\\system\\user\\authentication\\password\\algorithm\\TPhpass::hash() ( WoltLab/WCF#4602 ) wcf\\system\\user\\authentication\\password\\algorithm\\TPhpass::needsRehash() ( WoltLab/WCF#4602 ) wcf\\system\\WCF::getAnchor() ( WoltLab/WCF#4580 ) wcf\\util\\MathUtil::getRandomValue() ( WoltLab/WCF#4280 ) wcf\\util\\StringUtil::encodeJSON() ( WoltLab/WCF#4645 ) wcf\\util\\StringUtil::endsWith() ( WoltLab/WCF#4509 ) wcf\\util\\StringUtil::getHash() ( WoltLab/WCF#4279 ) wcf\\util\\StringUtil::split() ( WoltLab/WCF#4513 ) wcf\\util\\StringUtil::startsWith() ( WoltLab/WCF#4509 ) wcf\\util\\UserUtil::isAvailableEmail() ( WoltLab/WCF#4602 ) wcf\\util\\UserUtil::isAvailableUsername() ( WoltLab/WCF#4602 ) Properties # wcf\\acp\\page\\PackagePage::$compatibleVersions ( WoltLab/WCF#4371 ) wcf\\system\\io\\GZipFile::$gzopen64 ( WoltLab/WCF#4381 ) Constants # wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::DELETE wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::GET wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::POST wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::PUT wcf\\system\\visitTracker\\VisitTracker::DEFAULT_LIFETIME ( WoltLab/WCF#4757 ) Functions # The global escapeString helper ( WoltLab/WCF#4506 ) Options # HTTP_SEND_X_FRAME_OPTIONS ( WoltLab/WCF#4474 ) ELASTICSEARCH_ALLOW_LEADING_WILDCARD WBB_MODULE_IGNORE_BOARDS (The option will be always on with WoltLab Suite Forum 5.5 and will be removed with a future version.) ENABLE_DESKTOP_NOTIFICATIONS ( WoltLab/WCF#4806 ) JavaScript # WCF.Message.Quote.Manager.markQuotesForRemoval() ( WoltLab/WCF#4452 ) WCF.Search.Message.KeywordList ( WoltLab/WCF#4402 ) SECURITY_TOKEN (use Core.getXsrfToken() , WoltLab/WCF#4523 ) WCF.Dropdown.Interactive.Handler ( WoltLab/WCF#4603 ) WCF.Dropdown.Interactive.Instance ( WoltLab/WCF#4603 ) WCF.User.Panel.Abstract ( WoltLab/WCF#4603 ) Database Tables # wcf1_package_compatibility ( WoltLab/WCF#4371 ) wcf1_package_update_compatibility ( WoltLab/WCF#4385 ) wcf1_package_update_optional ( WoltLab/WCF#4432 ) Templates # Template Plugins # |encodeJSON ( WoltLab/WCF#4645 ) {fetch} ( WoltLab/WCF#4891 ) Template Events # pageNavbarTop::navigationIcons search::queryOptions search::authorOptions search::periodOptions search::displayOptions search::generalFields Miscellaneous # The global option to set a specific style with a request parameter ( $_REQUEST['styleID'] ) is deprecated ( WoltLab/WCF@0c0111e946 ) Removals # PHP # Classes # gallery\\util\\ExifUtil wbb\\action\\BoardQuickSearchAction wbb\\data\\thread\\NewsList wbb\\data\\thread\\News wcf\\action\\PollAction ( WoltLab/WCF#4662 ) wcf\\form\\RecaptchaForm ( WoltLab/WCF#4289 ) wcf\\system\\background\\job\\ElasticSearchIndexBackgroundJob wcf\\system\\cache\\builder\\TemplateListenerCacheBuilder ( WoltLab/WCF#4297 ) wcf\\system\\log\\modification\\ModificationLogHandler ( WoltLab/WCF#4340 ) wcf\\system\\recaptcha\\RecaptchaHandlerV2 ( WoltLab/WCF#4289 ) wcf\\system\\search\\SearchKeywordManager ( WoltLab/WCF#4313 ) The SCSS compiler\u2019s Leafo class aliases ( WoltLab/WCF#4343 , Migration Guide from 5.2 to 5.3 ) Methods # wbb\\data\\board\\BoardCache::getLabelGroups() wbb\\data\\post\\PostAction::jumpToExtended() (this method always threw a BadMethodCallException ) wbb\\data\\thread\\ThreadAction::countReplies() wbb\\data\\thread\\ThreadAction::validateCountReplies() wcf\\acp\\form\\UserGroupOptionForm::verifyPermissions() ( WoltLab/WCF#4312 ) wcf\\data\\conversation\\message\\ConversationMessageAction::jumpToExtended() ( WoltLab/com.woltlab.wcf.conversation#162 ) wcf\\data\\moderation\\queue\\ModerationQueueEditor::markAsDone() ( WoltLab/WCF#4317 ) wcf\\data\\tag\\TagCloudTag::getSize() ( WoltLab/WCF#4325 ) wcf\\data\\tag\\TagCloudTag::setSize() ( WoltLab/WCF#4325 ) wcf\\data\\user\\User::getSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::getSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::saveSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::validateGetSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::validateSaveSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\avatar\\DefaultAvatar::canCrop() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\DefaultAvatar::getCropImageTag() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\UserAvatar::canCrop() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\UserAvatar::getCropImageTag() ( WoltLab/WCF#4310 ) wcf\\system\\bbcode\\BBCodeHandler::setAllowedBBCodes() ( WoltLab/WCF#4319 ) wcf\\system\\bbcode\\BBCodeParser::validateBBCodes() ( WoltLab/WCF#4319 ) wcf\\system\\breadcrumb\\Breadcrumbs::add() ( WoltLab/WCF#4298 ) wcf\\system\\breadcrumb\\Breadcrumbs::remove() ( WoltLab/WCF#4298 ) wcf\\system\\breadcrumb\\Breadcrumbs::replace() ( WoltLab/WCF#4298 ) wcf\\system\\form\\builder\\IFormNode::create() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateAttribute() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateClass() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateId() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\IAttributeFormField::validateFieldAttribute() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\dependency\\IFormFieldDependency::create() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\validation\\IFormFieldValidator::validateId() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\message\\embedded\\object\\MessageEmbeddedObjectManager::parseTemporaryMessage() ( WoltLab/WCF#4299 ) wcf\\system\\package\\PackageArchive::getPhpRequirements() ( WoltLab/WCF#4311 ) wcf\\system\\search\\ISearchIndexManager::add() (Removal from Interface, see WoltLab/WCF#4508 ) wcf\\system\\search\\ISearchIndexManager::update() (Removal from Interface, see WoltLab/WCF#4508 ) wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::_add() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::_delete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::add() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::bulkAdd() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::bulkDelete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::delete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::update() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::add() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::update() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchEngine::parseSearchQuery() Properties # wcf\\data\\category\\Category::$permissions ( WoltLab/WCF#4303 ) wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::$bulkTypeName Constants # wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::HEAD wcf\\system\\tagging\\TagCloud::MAX_FONT_SIZE ( WoltLab/WCF#4325 ) wcf\\system\\tagging\\TagCloud::MIN_FONT_SIZE ( WoltLab/WCF#4325 ) Options # ENABLE_CENSORSHIP (always call Censorship::test() , see WoltLab/WCF#4567 ) MODULE_SYSTEM_RECAPTCHA ( WoltLab/WCF#4305 ) PROFILE_MAIL_USE_CAPTCHA ( WoltLab/WCF#4399 ) The may value for MAIL_SMTP_STARTTLS ( WoltLab/WCF#4398 ) SEARCH_USE_CAPTCHA (see WoltLab/WCF#4605 ) Files # acp/dereferrer.php JavaScript # Blog.Entry.QuoteHandler (use WoltLabSuite/Blog/Ui/Entry/Quote ) Calendar.Event.QuoteHandler (use WoltLabSuite/Calendar/Ui/Event/Quote ) WBB.Board.IgnoreBoards (use WoltLabSuite/Forum/Ui/Board/Ignore ) WBB.Board.MarkAllAsRead (use WoltLabSuite/Forum/Ui/Board/MarkAllAsRead ) WBB.Board.MarkAsRead (use WoltLabSuite/Forum/Ui/Board/MarkAsRead ) WBB.Post.QuoteHandler (use WoltLabSuite/Forum/Ui/Post/Quote ) WBB.Thread.LastPageHandler (use WoltLabSuite/Forum/Ui/Thread/LastPageHandler ) WBB.Thread.MarkAsRead (use WoltLabSuite/Forum/Ui/Thread/MarkAsRead ) WBB.Thread.SimilarThreads (use WoltLabSuite/Forum/Ui/Thread/SimilarThreads ) WBB.Thread.WatchedThreadList (use WoltLabSuite/Forum/Controller/Thread/WatchedList ) WCF.ACP.Style.ImageUpload ( WoltLab/WCF#4323 ) WCF.ColorPicker (see migration guide for WCF.ColorPicker ) WCF.Conversation.Message.QuoteHandler (use WoltLabSuite/Core/Conversation/Ui/Message/Quote , see WoltLab/com.woltlab.wcf.conversation#155 ) WCF.Like.js ( WoltLab/WCF#4300 ) WCF.Message.UserMention ( WoltLab/WCF#4324 ) WCF.Poll.Manager ( WoltLab/WCF#4662 ) WCF.UserPanel ( WoltLab/WCF#4316 ) WCF.User.Panel.Moderation ( WoltLab/WCF#4603 ) WCF.User.Panel.Notification ( WoltLab/WCF#4603 ) WCF.User.Panel.UserMenu ( WoltLab/WCF#4603 ) Phrases # wbb.search.boards.all wcf.global.form.error.greaterThan.javaScript ( WoltLab/WCF#4306 ) wcf.global.form.error.lessThan.javaScript ( WoltLab/WCF#4306 ) wcf.search.type.keywords wcf.acp.option.search_use_captcha wcf.search.query.description wcf.search.results.change wcf.search.results.description wcf.search.general wcf.search.query wcf.search.error.noMatches wcf.search.error.user.noMatches Templates # Templates # searchResult Template Events # search::tabMenuTabs search::sections tagSearch::tabMenuTabs tagSearch::sections Miscellaneous # Object specific VisitTracker lifetimes ( WoltLab/WCF#4757 )","title":"Deprecations and Removals"},{"location":"migration/wsc54/deprecations_removals/#migrating-from-wsc-54-deprecations-and-removals","text":"With version 5.5, we have deprecated certain components and removed several other components that have been deprecated for many years.","title":"Migrating from WSC 5.4 - Deprecations and Removals"},{"location":"migration/wsc54/deprecations_removals/#deprecations","text":"","title":"Deprecations"},{"location":"migration/wsc54/deprecations_removals/#php","text":"","title":"PHP"},{"location":"migration/wsc54/deprecations_removals/#classes","text":"filebase\\system\\file\\FileDataHandler (use filebase\\system\\cache\\runtime\\FileRuntimeCache ) wcf\\action\\AbstractAjaxAction (use PSR-7 responses, WoltLab/WCF#4437 ) wcf\\data\\IExtendedMessageQuickReplyAction ( WoltLab/WCF#4575 ) wcf\\form\\SearchForm (see WoltLab/WCF#4605 ) wcf\\page\\AbstractSecurePage ( WoltLab/WCF#4515 ) wcf\\page\\SearchResultPage (see WoltLab/WCF#4605 ) wcf\\system\\database\\table\\column\\TUnsupportedDefaultValue (do not implement IDefaultValueDatabaseTableColumn , see WoltLab/WCF#4733 ) wcf\\system\\exception\\ILoggingAwareException ( WoltLab/WCF#4547 ) wcf\\system\\io\\FTP (directly use the FTP extension) wcf\\system\\search\\AbstractSearchableObjectType (use AbstractSearchProvider instead, see WoltLab/WCF#4605 ) wcf\\system\\search\\elasticsearch\\ElasticsearchException wcf\\system\\search\\ISearchableObjectType (use ISearchProvider instead, see WoltLab/WCF#4605 ) wcf\\util\\PasswordUtil","title":"Classes"},{"location":"migration/wsc54/deprecations_removals/#methods","text":"wcf\\action\\MessageQuoteAction::markForRemoval() ( WoltLab/WCF#4452 ) wcf\\data\\user\\avatar\\UserAvatarAction::fetchRemoteAvatar() ( WoltLab/WCF#4744 ) wcf\\data\\user\\notification\\UserNotificationAction::getOutstandingNotifications() ( WoltLab/WCF#4603 ) wcf\\data\\moderation\\queue\\ModerationQueueAction::getOutstandingQueues() ( WoltLab/WCF#4603 ) wcf\\system\\message\\QuickReplyManager::setTmpHash() ( WoltLab/WCF#4575 ) wcf\\system\\request\\Request::isExecuted() ( WoltLab/WCF#4485 ) wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::query() wcf\\system\\session\\Session::getDeviceIcon() ( WoltLab/WCF#4525 ) wcf\\system\\user\\authentication\\password\\algorithm\\TPhpass::hash() ( WoltLab/WCF#4602 ) wcf\\system\\user\\authentication\\password\\algorithm\\TPhpass::needsRehash() ( WoltLab/WCF#4602 ) wcf\\system\\WCF::getAnchor() ( WoltLab/WCF#4580 ) wcf\\util\\MathUtil::getRandomValue() ( WoltLab/WCF#4280 ) wcf\\util\\StringUtil::encodeJSON() ( WoltLab/WCF#4645 ) wcf\\util\\StringUtil::endsWith() ( WoltLab/WCF#4509 ) wcf\\util\\StringUtil::getHash() ( WoltLab/WCF#4279 ) wcf\\util\\StringUtil::split() ( WoltLab/WCF#4513 ) wcf\\util\\StringUtil::startsWith() ( WoltLab/WCF#4509 ) wcf\\util\\UserUtil::isAvailableEmail() ( WoltLab/WCF#4602 ) wcf\\util\\UserUtil::isAvailableUsername() ( WoltLab/WCF#4602 )","title":"Methods"},{"location":"migration/wsc54/deprecations_removals/#properties","text":"wcf\\acp\\page\\PackagePage::$compatibleVersions ( WoltLab/WCF#4371 ) wcf\\system\\io\\GZipFile::$gzopen64 ( WoltLab/WCF#4381 )","title":"Properties"},{"location":"migration/wsc54/deprecations_removals/#constants","text":"wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::DELETE wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::GET wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::POST wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::PUT wcf\\system\\visitTracker\\VisitTracker::DEFAULT_LIFETIME ( WoltLab/WCF#4757 )","title":"Constants"},{"location":"migration/wsc54/deprecations_removals/#functions","text":"The global escapeString helper ( WoltLab/WCF#4506 )","title":"Functions"},{"location":"migration/wsc54/deprecations_removals/#options","text":"HTTP_SEND_X_FRAME_OPTIONS ( WoltLab/WCF#4474 ) ELASTICSEARCH_ALLOW_LEADING_WILDCARD WBB_MODULE_IGNORE_BOARDS (The option will be always on with WoltLab Suite Forum 5.5 and will be removed with a future version.) ENABLE_DESKTOP_NOTIFICATIONS ( WoltLab/WCF#4806 )","title":"Options"},{"location":"migration/wsc54/deprecations_removals/#javascript","text":"WCF.Message.Quote.Manager.markQuotesForRemoval() ( WoltLab/WCF#4452 ) WCF.Search.Message.KeywordList ( WoltLab/WCF#4402 ) SECURITY_TOKEN (use Core.getXsrfToken() , WoltLab/WCF#4523 ) WCF.Dropdown.Interactive.Handler ( WoltLab/WCF#4603 ) WCF.Dropdown.Interactive.Instance ( WoltLab/WCF#4603 ) WCF.User.Panel.Abstract ( WoltLab/WCF#4603 )","title":"JavaScript"},{"location":"migration/wsc54/deprecations_removals/#database-tables","text":"wcf1_package_compatibility ( WoltLab/WCF#4371 ) wcf1_package_update_compatibility ( WoltLab/WCF#4385 ) wcf1_package_update_optional ( WoltLab/WCF#4432 )","title":"Database Tables"},{"location":"migration/wsc54/deprecations_removals/#templates","text":"","title":"Templates"},{"location":"migration/wsc54/deprecations_removals/#template-plugins","text":"|encodeJSON ( WoltLab/WCF#4645 ) {fetch} ( WoltLab/WCF#4891 )","title":"Template Plugins"},{"location":"migration/wsc54/deprecations_removals/#template-events","text":"pageNavbarTop::navigationIcons search::queryOptions search::authorOptions search::periodOptions search::displayOptions search::generalFields","title":"Template Events"},{"location":"migration/wsc54/deprecations_removals/#miscellaneous","text":"The global option to set a specific style with a request parameter ( $_REQUEST['styleID'] ) is deprecated ( WoltLab/WCF@0c0111e946 )","title":"Miscellaneous"},{"location":"migration/wsc54/deprecations_removals/#removals","text":"","title":"Removals"},{"location":"migration/wsc54/deprecations_removals/#php_1","text":"","title":"PHP"},{"location":"migration/wsc54/deprecations_removals/#classes_1","text":"gallery\\util\\ExifUtil wbb\\action\\BoardQuickSearchAction wbb\\data\\thread\\NewsList wbb\\data\\thread\\News wcf\\action\\PollAction ( WoltLab/WCF#4662 ) wcf\\form\\RecaptchaForm ( WoltLab/WCF#4289 ) wcf\\system\\background\\job\\ElasticSearchIndexBackgroundJob wcf\\system\\cache\\builder\\TemplateListenerCacheBuilder ( WoltLab/WCF#4297 ) wcf\\system\\log\\modification\\ModificationLogHandler ( WoltLab/WCF#4340 ) wcf\\system\\recaptcha\\RecaptchaHandlerV2 ( WoltLab/WCF#4289 ) wcf\\system\\search\\SearchKeywordManager ( WoltLab/WCF#4313 ) The SCSS compiler\u2019s Leafo class aliases ( WoltLab/WCF#4343 , Migration Guide from 5.2 to 5.3 )","title":"Classes"},{"location":"migration/wsc54/deprecations_removals/#methods_1","text":"wbb\\data\\board\\BoardCache::getLabelGroups() wbb\\data\\post\\PostAction::jumpToExtended() (this method always threw a BadMethodCallException ) wbb\\data\\thread\\ThreadAction::countReplies() wbb\\data\\thread\\ThreadAction::validateCountReplies() wcf\\acp\\form\\UserGroupOptionForm::verifyPermissions() ( WoltLab/WCF#4312 ) wcf\\data\\conversation\\message\\ConversationMessageAction::jumpToExtended() ( WoltLab/com.woltlab.wcf.conversation#162 ) wcf\\data\\moderation\\queue\\ModerationQueueEditor::markAsDone() ( WoltLab/WCF#4317 ) wcf\\data\\tag\\TagCloudTag::getSize() ( WoltLab/WCF#4325 ) wcf\\data\\tag\\TagCloudTag::setSize() ( WoltLab/WCF#4325 ) wcf\\data\\user\\User::getSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::getSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::saveSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::validateGetSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\UserAction::validateSaveSocialNetworkPrivacySettings() ( WoltLab/WCF#4308 ) wcf\\data\\user\\avatar\\DefaultAvatar::canCrop() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\DefaultAvatar::getCropImageTag() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\UserAvatar::canCrop() ( WoltLab/WCF#4310 ) wcf\\data\\user\\avatar\\UserAvatar::getCropImageTag() ( WoltLab/WCF#4310 ) wcf\\system\\bbcode\\BBCodeHandler::setAllowedBBCodes() ( WoltLab/WCF#4319 ) wcf\\system\\bbcode\\BBCodeParser::validateBBCodes() ( WoltLab/WCF#4319 ) wcf\\system\\breadcrumb\\Breadcrumbs::add() ( WoltLab/WCF#4298 ) wcf\\system\\breadcrumb\\Breadcrumbs::remove() ( WoltLab/WCF#4298 ) wcf\\system\\breadcrumb\\Breadcrumbs::replace() ( WoltLab/WCF#4298 ) wcf\\system\\form\\builder\\IFormNode::create() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateAttribute() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateClass() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\IFormNode::validateId() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\IAttributeFormField::validateFieldAttribute() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\dependency\\IFormFieldDependency::create() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\form\\builder\\field\\validation\\IFormFieldValidator::validateId() (Removal from Interface, see WoltLab/WCF#4468 ) wcf\\system\\message\\embedded\\object\\MessageEmbeddedObjectManager::parseTemporaryMessage() ( WoltLab/WCF#4299 ) wcf\\system\\package\\PackageArchive::getPhpRequirements() ( WoltLab/WCF#4311 ) wcf\\system\\search\\ISearchIndexManager::add() (Removal from Interface, see WoltLab/WCF#4508 ) wcf\\system\\search\\ISearchIndexManager::update() (Removal from Interface, see WoltLab/WCF#4508 ) wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::_add() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::_delete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::add() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::bulkAdd() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::bulkDelete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::delete() wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::update() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::add() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::update() wcf\\system\\search\\elasticsearch\\ElasticsearchSearchEngine::parseSearchQuery()","title":"Methods"},{"location":"migration/wsc54/deprecations_removals/#properties_1","text":"wcf\\data\\category\\Category::$permissions ( WoltLab/WCF#4303 ) wcf\\system\\search\\elasticsearch\\ElasticsearchSearchIndexManager::$bulkTypeName","title":"Properties"},{"location":"migration/wsc54/deprecations_removals/#constants_1","text":"wcf\\system\\search\\elasticsearch\\ElasticsearchHandler::HEAD wcf\\system\\tagging\\TagCloud::MAX_FONT_SIZE ( WoltLab/WCF#4325 ) wcf\\system\\tagging\\TagCloud::MIN_FONT_SIZE ( WoltLab/WCF#4325 )","title":"Constants"},{"location":"migration/wsc54/deprecations_removals/#options_1","text":"ENABLE_CENSORSHIP (always call Censorship::test() , see WoltLab/WCF#4567 ) MODULE_SYSTEM_RECAPTCHA ( WoltLab/WCF#4305 ) PROFILE_MAIL_USE_CAPTCHA ( WoltLab/WCF#4399 ) The may value for MAIL_SMTP_STARTTLS ( WoltLab/WCF#4398 ) SEARCH_USE_CAPTCHA (see WoltLab/WCF#4605 )","title":"Options"},{"location":"migration/wsc54/deprecations_removals/#files","text":"acp/dereferrer.php","title":"Files"},{"location":"migration/wsc54/deprecations_removals/#javascript_1","text":"Blog.Entry.QuoteHandler (use WoltLabSuite/Blog/Ui/Entry/Quote ) Calendar.Event.QuoteHandler (use WoltLabSuite/Calendar/Ui/Event/Quote ) WBB.Board.IgnoreBoards (use WoltLabSuite/Forum/Ui/Board/Ignore ) WBB.Board.MarkAllAsRead (use WoltLabSuite/Forum/Ui/Board/MarkAllAsRead ) WBB.Board.MarkAsRead (use WoltLabSuite/Forum/Ui/Board/MarkAsRead ) WBB.Post.QuoteHandler (use WoltLabSuite/Forum/Ui/Post/Quote ) WBB.Thread.LastPageHandler (use WoltLabSuite/Forum/Ui/Thread/LastPageHandler ) WBB.Thread.MarkAsRead (use WoltLabSuite/Forum/Ui/Thread/MarkAsRead ) WBB.Thread.SimilarThreads (use WoltLabSuite/Forum/Ui/Thread/SimilarThreads ) WBB.Thread.WatchedThreadList (use WoltLabSuite/Forum/Controller/Thread/WatchedList ) WCF.ACP.Style.ImageUpload ( WoltLab/WCF#4323 ) WCF.ColorPicker (see migration guide for WCF.ColorPicker ) WCF.Conversation.Message.QuoteHandler (use WoltLabSuite/Core/Conversation/Ui/Message/Quote , see WoltLab/com.woltlab.wcf.conversation#155 ) WCF.Like.js ( WoltLab/WCF#4300 ) WCF.Message.UserMention ( WoltLab/WCF#4324 ) WCF.Poll.Manager ( WoltLab/WCF#4662 ) WCF.UserPanel ( WoltLab/WCF#4316 ) WCF.User.Panel.Moderation ( WoltLab/WCF#4603 ) WCF.User.Panel.Notification ( WoltLab/WCF#4603 ) WCF.User.Panel.UserMenu ( WoltLab/WCF#4603 )","title":"JavaScript"},{"location":"migration/wsc54/deprecations_removals/#phrases","text":"wbb.search.boards.all wcf.global.form.error.greaterThan.javaScript ( WoltLab/WCF#4306 ) wcf.global.form.error.lessThan.javaScript ( WoltLab/WCF#4306 ) wcf.search.type.keywords wcf.acp.option.search_use_captcha wcf.search.query.description wcf.search.results.change wcf.search.results.description wcf.search.general wcf.search.query wcf.search.error.noMatches wcf.search.error.user.noMatches","title":"Phrases"},{"location":"migration/wsc54/deprecations_removals/#templates_1","text":"","title":"Templates"},{"location":"migration/wsc54/deprecations_removals/#templates_2","text":"searchResult","title":"Templates"},{"location":"migration/wsc54/deprecations_removals/#template-events_1","text":"search::tabMenuTabs search::sections tagSearch::tabMenuTabs tagSearch::sections","title":"Template Events"},{"location":"migration/wsc54/deprecations_removals/#miscellaneous_1","text":"Object specific VisitTracker lifetimes ( WoltLab/WCF#4757 )","title":"Miscellaneous"},{"location":"migration/wsc54/forum_subscriptions/","text":"Migrating from WSC 5.4 - WoltLab Suite Forum # Subscriptions # With WoltLab Suite Forum 5.5 we have introduced a new system for subscribing to threads and boards, which also offers the possibility to ignore threads and boards. You can learn more about this feature in our blog . The new system uses a separate mechanism to track the subscribed forums as well as the subscribed threads. The previously used object type com.woltlab.wcf.user.objectWatch is now discontinued, because the object watch system turned out to be too limited for the complex logic behind thread and forum subscriptions. Subscribe to Threads # Previously: 1 2 3 4 5 6 7 $action = new UserObjectWatchAction ([], 'subscribe' , [ 'data' => [ 'objectID' => $threadID , 'objectType' => 'com.woltlab.wbb.thread' , ] ]); $action -> executeAction (); Now: 1 2 3 4 ThreadStatusHandler :: saveSubscriptionStatus ( $threadID , ThreadStatusHandler :: SUBSCRIPTION_MODE_WATCHING ); Filter Ignored Threads # To filter ignored threads from a given ThreadList , you can use the method ThreadStatusHandler::addFilterForIgnoredThreads() to append the filter for ignored threads. The ViewableThreadList filters out ignored threads by default. Example: 1 2 3 4 5 6 7 8 9 $user = new User ( 123 ); $threadList = new ThreadList (); ThreadStatusHandler :: addFilterForIgnoredThreads ( $threadList , // This parameter specifies the target user. Defaults to the current user if the parameter // is omitted or `null`. $user ); $threadList -> readObjects (); Filter Ignored Users # Avoid issuing notifications to users that have ignored the target thread by filtering those out. 1 2 3 4 5 $userIDs = [ 1 , 2 , 3 ]; $users = ThreadStatusHandler :: filterIgnoredUserIDs ( $userIDs , $thread -> threadID ); Subscribe to Boards # Previously: 1 2 3 4 5 6 7 $action = new UserObjectWatchAction ([], 'subscribe' , [ 'data' => [ 'objectID' => $boardID , 'objectType' => 'com.woltlab.wbb.board' , ] ]); $action -> executeAction (); Now: 1 2 3 4 BoardStatusHandler :: saveSubscriptionStatus ( $boardID , ThreadStatusHandler :: SUBSCRIPTION_MODE_WATCHING ); Filter Ignored Boards # Similar to ignored threads you will also have to avoid issuing notifications for boards that a user has ignored. 1 2 3 4 5 $userIDs = [ 1 , 2 , 3 ]; $users = BoardStatusHandler :: filterIgnoredUserIDs ( $userIDs , $board -> boardID );","title":"Migrating from WSC 5.4 - WoltLab Suite Forum"},{"location":"migration/wsc54/forum_subscriptions/#migrating-from-wsc-54-woltlab-suite-forum","text":"","title":"Migrating from WSC 5.4 - WoltLab Suite Forum"},{"location":"migration/wsc54/forum_subscriptions/#subscriptions","text":"With WoltLab Suite Forum 5.5 we have introduced a new system for subscribing to threads and boards, which also offers the possibility to ignore threads and boards. You can learn more about this feature in our blog . The new system uses a separate mechanism to track the subscribed forums as well as the subscribed threads. The previously used object type com.woltlab.wcf.user.objectWatch is now discontinued, because the object watch system turned out to be too limited for the complex logic behind thread and forum subscriptions.","title":"Subscriptions"},{"location":"migration/wsc54/forum_subscriptions/#subscribe-to-threads","text":"Previously: 1 2 3 4 5 6 7 $action = new UserObjectWatchAction ([], 'subscribe' , [ 'data' => [ 'objectID' => $threadID , 'objectType' => 'com.woltlab.wbb.thread' , ] ]); $action -> executeAction (); Now: 1 2 3 4 ThreadStatusHandler :: saveSubscriptionStatus ( $threadID , ThreadStatusHandler :: SUBSCRIPTION_MODE_WATCHING );","title":"Subscribe to Threads"},{"location":"migration/wsc54/forum_subscriptions/#filter-ignored-threads","text":"To filter ignored threads from a given ThreadList , you can use the method ThreadStatusHandler::addFilterForIgnoredThreads() to append the filter for ignored threads. The ViewableThreadList filters out ignored threads by default. Example: 1 2 3 4 5 6 7 8 9 $user = new User ( 123 ); $threadList = new ThreadList (); ThreadStatusHandler :: addFilterForIgnoredThreads ( $threadList , // This parameter specifies the target user. Defaults to the current user if the parameter // is omitted or `null`. $user ); $threadList -> readObjects ();","title":"Filter Ignored Threads"},{"location":"migration/wsc54/forum_subscriptions/#filter-ignored-users","text":"Avoid issuing notifications to users that have ignored the target thread by filtering those out. 1 2 3 4 5 $userIDs = [ 1 , 2 , 3 ]; $users = ThreadStatusHandler :: filterIgnoredUserIDs ( $userIDs , $thread -> threadID );","title":"Filter Ignored Users"},{"location":"migration/wsc54/forum_subscriptions/#subscribe-to-boards","text":"Previously: 1 2 3 4 5 6 7 $action = new UserObjectWatchAction ([], 'subscribe' , [ 'data' => [ 'objectID' => $boardID , 'objectType' => 'com.woltlab.wbb.board' , ] ]); $action -> executeAction (); Now: 1 2 3 4 BoardStatusHandler :: saveSubscriptionStatus ( $boardID , ThreadStatusHandler :: SUBSCRIPTION_MODE_WATCHING );","title":"Subscribe to Boards"},{"location":"migration/wsc54/forum_subscriptions/#filter-ignored-boards","text":"Similar to ignored threads you will also have to avoid issuing notifications for boards that a user has ignored. 1 2 3 4 5 $userIDs = [ 1 , 2 , 3 ]; $users = BoardStatusHandler :: filterIgnoredUserIDs ( $userIDs , $board -> boardID );","title":"Filter Ignored Boards"},{"location":"migration/wsc54/javascript/","text":"Migrating from WSC 5.4 - TypeScript and JavaScript # Ajax.dboAction() # We have introduced a new Promise based API for the interaction with wcf\\data\\DatabaseObjectAction . It provides full IDE autocompletion support and transparent error handling, but is designed to be used with DatabaseObjectAction only. See the documentation for the new API and WoltLab/WCF#4585 for details. WCF.ColorPicker # We have replaced the old jQuery-based color picker WCF.ColorPicker with a more lightweight replacement WoltLabSuite/Core/Ui/Color/Picker , which uses the build-in input[type=color] field. To support transparency, which input[type=color] does not, we also added a slider to set the alpha value. WCF.ColorPicker has been adjusted to internally use WoltLabSuite/Core/Ui/Color/Picker and it has been deprecated. Be aware that the new color picker requires the following new phrases to be available in the TypeScript/JavaScript code: wcf.style.colorPicker.alpha , wcf.style.colorPicker.color , wcf.style.colorPicker.error.invalidColor , wcf.style.colorPicker.hexAlpha , wcf.style.colorPicker.new . See WoltLab/WCF#4353 for details. CodeMirror # The bundled version of CodeMirror was updated and should be loaded using the AMD loader going forward. See the third party libraries migration guide for details. New User Menu # The legacy implementation WCF.User.Panel.Abstract was based on jQuery and has now been retired in favor of a new lightweight implementation that provides a clean interface and improved accessibility. You are strongly encouraged to migrate your existing implementation to integrate with existing menus. Please use WoltLabSuite/Core/Ui/User/Menu/Data/ModerationQueue.ts as a template for your own implementation, it contains only strictly the code you will need. It makes use of the new Ajax.dboAction() (see above) for improved readability and flexibility. You must update your trigger button to include the role , tabindex and ARIA attributes! Please take a look at the links in pageHeaderUser.tpl to see these four attributes in action. See WoltLab/WCF#4603 for details.","title":"TypeScript and JavaScript"},{"location":"migration/wsc54/javascript/#migrating-from-wsc-54-typescript-and-javascript","text":"","title":"Migrating from WSC 5.4 - TypeScript and JavaScript"},{"location":"migration/wsc54/javascript/#ajaxdboaction","text":"We have introduced a new Promise based API for the interaction with wcf\\data\\DatabaseObjectAction . It provides full IDE autocompletion support and transparent error handling, but is designed to be used with DatabaseObjectAction only. See the documentation for the new API and WoltLab/WCF#4585 for details.","title":"Ajax.dboAction()"},{"location":"migration/wsc54/javascript/#wcfcolorpicker","text":"We have replaced the old jQuery-based color picker WCF.ColorPicker with a more lightweight replacement WoltLabSuite/Core/Ui/Color/Picker , which uses the build-in input[type=color] field. To support transparency, which input[type=color] does not, we also added a slider to set the alpha value. WCF.ColorPicker has been adjusted to internally use WoltLabSuite/Core/Ui/Color/Picker and it has been deprecated. Be aware that the new color picker requires the following new phrases to be available in the TypeScript/JavaScript code: wcf.style.colorPicker.alpha , wcf.style.colorPicker.color , wcf.style.colorPicker.error.invalidColor , wcf.style.colorPicker.hexAlpha , wcf.style.colorPicker.new . See WoltLab/WCF#4353 for details.","title":"WCF.ColorPicker"},{"location":"migration/wsc54/javascript/#codemirror","text":"The bundled version of CodeMirror was updated and should be loaded using the AMD loader going forward. See the third party libraries migration guide for details.","title":"CodeMirror"},{"location":"migration/wsc54/javascript/#new-user-menu","text":"The legacy implementation WCF.User.Panel.Abstract was based on jQuery and has now been retired in favor of a new lightweight implementation that provides a clean interface and improved accessibility. You are strongly encouraged to migrate your existing implementation to integrate with existing menus. Please use WoltLabSuite/Core/Ui/User/Menu/Data/ModerationQueue.ts as a template for your own implementation, it contains only strictly the code you will need. It makes use of the new Ajax.dboAction() (see above) for improved readability and flexibility. You must update your trigger button to include the role , tabindex and ARIA attributes! Please take a look at the links in pageHeaderUser.tpl to see these four attributes in action. See WoltLab/WCF#4603 for details.","title":"New User Menu"},{"location":"migration/wsc54/libraries/","text":"Migrating from WSC 5.4 - Third Party Libraries # Symfony PHP Polyfills # WoltLab Suite 5.5 ships with Symfony's PHP 7.3, 7.4, and 8.0 polyfills. These polyfills allow you to reliably use some of the PHP functions only available in PHP versions that are newer than the current minimum of PHP 7.2. Notable mentions are str_starts_with , str_ends_with , array_key_first , and array_key_last . Refer to the documentation within the symfony/polyfill repository for details. scssphp # scssphp was updated from version 1.4 to 1.10. If you interact with scssphp only by deploying .scss files, then you should not experience any breaking changes, except when the improved SCSS compatibility interprets your SCSS code differently. If you happen to directly use scssphp in your PHP code, you should be aware that scssphp deprecated the use of the compile() method, non-UTF-8 processing and also adjusted the handling of pure PHP values for variable handling. Refer to WoltLab/WCF#4345 and the scssphp releases for details. Emogrifier / CSS Inliner # The Emogrifier library was updated from version 5.0 to 6.0. CodeMirror # CodeMirror, the code editor we use for editing templates and SCSS, for example, has been updated to version 5.61.1 and we now also deliver all supported languages/modes. To properly support all languages/modes, CodeMirror is now loaded via the AMD module loader, which requires the original structure of the CodeMirror package, i.e. codemirror.js being in a lib folder. To preserve backward-compatibility, we also keep copies of codemirror.js and codemirror.css in version 5.61.1 directly in js/3rdParty/codemirror . These files are, however, considered deprecated and you should migrate to using require() (see codemirror ACP template). See WoltLab/WCF#4277 for details. Zend/ProgressBar # The old bundled version of Zend/ProgressBar was replaced by a current version of laminas-progressbar. Due to laminas-zendframework-bridge this update is a drop-in replacement. Existing code should continue to work as-is. It is recommended to cleanly migrate to laminas-progressbar to allow for a future removal of the bridge. Updating the use imports should be sufficient to switch to the laminas-progressbar. See WoltLab/WCF#4460 for details.","title":"Third Party Libraries"},{"location":"migration/wsc54/libraries/#migrating-from-wsc-54-third-party-libraries","text":"","title":"Migrating from WSC 5.4 - Third Party Libraries"},{"location":"migration/wsc54/libraries/#symfony-php-polyfills","text":"WoltLab Suite 5.5 ships with Symfony's PHP 7.3, 7.4, and 8.0 polyfills. These polyfills allow you to reliably use some of the PHP functions only available in PHP versions that are newer than the current minimum of PHP 7.2. Notable mentions are str_starts_with , str_ends_with , array_key_first , and array_key_last . Refer to the documentation within the symfony/polyfill repository for details.","title":"Symfony PHP Polyfills"},{"location":"migration/wsc54/libraries/#scssphp","text":"scssphp was updated from version 1.4 to 1.10. If you interact with scssphp only by deploying .scss files, then you should not experience any breaking changes, except when the improved SCSS compatibility interprets your SCSS code differently. If you happen to directly use scssphp in your PHP code, you should be aware that scssphp deprecated the use of the compile() method, non-UTF-8 processing and also adjusted the handling of pure PHP values for variable handling. Refer to WoltLab/WCF#4345 and the scssphp releases for details.","title":"scssphp"},{"location":"migration/wsc54/libraries/#emogrifier-css-inliner","text":"The Emogrifier library was updated from version 5.0 to 6.0.","title":"Emogrifier / CSS Inliner"},{"location":"migration/wsc54/libraries/#codemirror","text":"CodeMirror, the code editor we use for editing templates and SCSS, for example, has been updated to version 5.61.1 and we now also deliver all supported languages/modes. To properly support all languages/modes, CodeMirror is now loaded via the AMD module loader, which requires the original structure of the CodeMirror package, i.e. codemirror.js being in a lib folder. To preserve backward-compatibility, we also keep copies of codemirror.js and codemirror.css in version 5.61.1 directly in js/3rdParty/codemirror . These files are, however, considered deprecated and you should migrate to using require() (see codemirror ACP template). See WoltLab/WCF#4277 for details.","title":"CodeMirror"},{"location":"migration/wsc54/libraries/#zendprogressbar","text":"The old bundled version of Zend/ProgressBar was replaced by a current version of laminas-progressbar. Due to laminas-zendframework-bridge this update is a drop-in replacement. Existing code should continue to work as-is. It is recommended to cleanly migrate to laminas-progressbar to allow for a future removal of the bridge. Updating the use imports should be sufficient to switch to the laminas-progressbar. See WoltLab/WCF#4460 for details.","title":"Zend/ProgressBar"},{"location":"migration/wsc54/php/","text":"Migrating from WSC 5.4 - PHP # Initial PSR-7 support # WoltLab Suite will incrementally add support for object oriented request/response handling based off the PSR-7 and PSR-15 standards in the upcoming versions. WoltLab Suite 5.5 adds initial support by allowing to define the response using objects implementing the PSR-7 ResponseInterface . If a controller returns such a response object from its __run() method, this response will automatically emitted to the client. Any PSR-7 implementation is supported, but WoltLab Suite 5.5 ships with laminas-diactoros as the recommended \u201cbatteries included\u201d implementation of PSR-7. Support for PSR-7 requests and PSR-15 middlewares is expected to follow in future versions. See WoltLab/WCF#4437 for details. Recommended changes for WoltLab Suite 5.5 # With the current support in WoltLab Suite 5.5 it is recommended to migrate the *Action classes to make use of PSR-7 responses. Control and data flow is typically fairly simple in *Action classes with most requests ending up in either a redirect or a JSON response, commonly followed by a call to exit; . Experimental support for *Page and *Form is available. It is recommended to wait for a future version before migrating these types of controllers. Migrating Redirects # Previously: lib/action/ExampleRedirectAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\action ; use wcf\\system\\request\\LinkHandler ; use wcf\\util\\HeaderUtil ; final class ExampleRedirectAction extends AbstractAction { public function execute () { parent :: execute (); // Redirect to the landing page. HeaderUtil :: redirect ( LinkHandler :: getInstance () -> getLink () ); exit ; } } Now: lib/action/ExampleRedirectAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php namespace wcf\\action ; use Laminas\\Diactoros\\Response\\RedirectResponse ; use wcf\\system\\request\\LinkHandler ; final class ExampleRedirectAction extends AbstractAction { public function execute () { parent :: execute (); // Redirect to the landing page. return new RedirectResponse ( LinkHandler :: getInstance () -> getLink () ); } } Migrating JSON responses # Previously: lib/action/ExampleJsonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\action ; use wcf\\util\\JSON ; final class ExampleJsonAction extends AbstractAction { public function execute () { parent :: execute (); \\header ( 'Content-type: application/json; charset=UTF-8' ); echo JSON :: encode ([ 'foo' => 'bar' , ]); exit ; } } Now: lib/action/ExampleJsonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php namespace wcf\\action ; use Laminas\\Diactoros\\Response\\JsonResponse ; final class ExampleJsonAction extends AbstractAction { public function execute () { parent :: execute (); return new JsonResponse ([ 'foo' => 'bar' , ]); } } Events # Historically, events were tightly coupled with a single class, with the event object being an object of this class, expecting the event listener to consume public properties and method of the event object. The $parameters array was introduced due to limitations of this pattern, avoiding moving all the values that might be of interest to the event listener into the state of the object. Events were still tightly coupled with the class that fired the event and using the opaque parameters array prevented IDEs from assisting with autocompletion and typing. WoltLab Suite 5.5 introduces the concept of dedicated, reusable event classes. Any newly introduced event will receive a dedicated class, implementing the wcf\\system\\event\\IEvent interface. These event classes may be fired from multiple locations, making them reusable to convey that a conceptual action happened, instead of a specific class doing something. An example for using the new event system could be a user logging in: Instead of listening on a the login form being submitted and the Facebook login action successfully running, an event UserLoggedIn might be fired whenever a user logs in, no matter how the login is performed. Additionally, these dedicated event classes will benefit from full IDE support. All the relevant values may be stored as real properties on the event object. Event classes should not have an Event suffix and should be stored in an event namespace in a matching location. Thus, the UserLoggedIn example might have a FQCN of \\wcf\\system\\user\\authentication\\event\\UserLoggedIn . Event listeners for events implementing IEvent need to follow PSR-14 , i.e. they need to be callable. In practice, this means that the event listener class needs to implement __invoke() . No interface has to be implemented in this case. Previously: 1 2 3 4 5 $parameters = [ 'value' => \\random_int ( 1 , 1024 ), ]; EventHandler :: getInstance () -> fireAction ( $this , 'valueAvailable' , $parameters ); lib/system/event/listener/ValueDumpListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php namespace wcf\\system\\event\\listener ; use wcf\\form\\ValueForm ; final class ValueDumpListener implements IParameterizedEventListener { /** * @inheritDoc * @param ValueForm $eventObj */ public function execute ( $eventObj , $className , $eventName , array & $parameters ) { var_dump ( $parameters [ 'value' ]); } } Now: 1 EventHandler::getInstance()->fire(new ValueAvailable(\\random_int(1, 1024))); lib/system/foo/event/ValueAvailable.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <? php namespace wcf\\system\\foo\\event ; use wcf\\system\\event\\IEvent ; final class ValueAvailable implements IEvent { /** * @var int */ private $value ; public function __construct ( int $value ) { $this -> value = $value ; } public function getValue () : int { return $this -> value ; } } lib/system/event/listener/ValueDumpListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\foo\\event\\ValueAvailable ; final class ValueDumpListener { public function __invoke ( ValueAvailable $event ) { var_dump ( $event -> getValue ()); } } See WoltLab/WCF#4000 and WoltLab/WCF#4265 for details. Authentication # The UserLoggedIn event was added. You should fire this event if you implement a custom login process (e.g. when adding additional external authentication providers). Example: 1 2 3 EventHandler :: getInstance () -> fire ( new UserLoggedIn ( $user ) ); See WoltLab/WCF#4356 for details. Embedded Objects in Comments # WoltLab/WCF#4275 added support for embedded objects like mentions for comments and comment responses. To properly render embedded objects whenever you are using comments in your packages, you have to use ViewableCommentList / ViewableCommentResponseList in these places or ViewableCommentRuntimeCache / ViewableCommentResponseRuntimeCache . While these runtime caches are only available since version 5.5, the viewable list classes have always been available so that changing CommentList to ViewableCommentList , for example, is a backwards-compatible change. Emails # Mailbox # The Mailbox and UserMailbox classes no longer store the passed Language and User objects, but the respective ID instead. This change reduces the size of the serialized email when stored in the background queue. If you inherit from the Mailbox or UserMailbox classes, you might experience issues if you directly access the $this->language or $this->user properties. Adjust your class to use composition instead of inheritance if possible. Use the getLanguage() or getUser() getters if using composition is not possible. See WoltLab/WCF#4389 for details. SMTP # The SmtpEmailTransport no longer supports a value of may for the $starttls property. Using the may value is unsafe as it allows for undetected MITM attacks. The use of encrypt is recommended, unless it is certain that the SMTP server does not support TLS. See WoltLab/WCF#4398 for details. Search # Search Form # After the overhaul of the search form, search providers are no longer bound to SearchForm and SearchResultPage . The interface ISearchObjectType and the abstract implementation AbstractSearchableObjectType have been replaced by ISearchProvider and AbstractSearchProvider . Please use ArticleSearch as a template for your own implementation See WoltLab/WCF#4605 for details. Exceptions # A new wcf\\system\\search\\exception\\SearchFailed exception was added. This exception should be thrown when executing the search query fails for (mostly) temporary reasons, such as a network partition to a remote service. It is not meant as a blanket exception to wrap everything. For example it must not be returned obvious programming errors, such as an access to an undefined variable ( ErrorException ). Catching the SearchFailed exception allows consuming code to gracefully handle search requests that are not essential for proceeding, without silencing other types of error. See WoltLab/WCF#4476 and WoltLab/WCF#4483 for details. Package Installation Plugins # Database # WoltLab Suite 5.5 changes the factory classes for common configurations of database columns within the PHP-based DDL API to contain a private constructor, preventing object creation. This change affects the following classes: DefaultFalseBooleanDatabaseTableColumn DefaultTrueBooleanDatabaseTableColumn NotNullInt10DatabaseTableColumn NotNullVarchar191DatabaseTableColumn NotNullVarchar255DatabaseTableColumn ObjectIdDatabaseTableColumn DatabaseTablePrimaryIndex The static create() method never returned an object of the factory class, but instead in object of the base type (e.g. IntDatabaseTableColumn for NotNullInt10DatabaseTableColumn ). Constructing an object of these factory classes is considered a bug, as the class name implies a specific column configuration, that might or might not hold if the object is modified afterwards. See WoltLab/WCF#4564 for details. WoltLab Suite 5.5 adds the IDefaultValueDatabaseTableColumn interface which is used to check whether specifying a default value is legal. For backwards compatibility this interface is implemented by AbstractDatabaseTableColumn . You should explicitly add this interface to custom table column type classes to avoid breakage if the interface is removed from AbstractDatabaseTableColumn in a future version. Likewise you should explicitly check for the interface before attempting to access the methods related to the default value of a column. See WoltLab/WCF#4733 for details. File Deletion # Three new package installation plugins have been added to delete ACP templates with acpTemplateDelete , files with fileDelete , and templates with templateDelete . Language # WoltLab/WCF#4261 has added support for deleting existing phrases with the language package installation plugin. The current structure of the language XML files language/en.xml 1 2 3 4 5 6 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </language> is deprecated and should be replaced with the new structure with an explicit <import> element like in the other package installation plugins: language/en.xml 1 2 3 4 5 6 7 8 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <import> <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </import> </language> Additionally, to now also support deleting phrases with this package installation plugin, support for a <delete> element has been added: language/en.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <import> <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </import> <delete> <item name= \"wcf.foo.barrr\" /> </delete> </language> Note that when deleting phrases, the category does not have to be specified because phrase identifiers are unique globally. Mixing the old structure and the new structure is not supported and will result in an error message during the import! Board and Thread Subscriptions # WoltLab Suite Forum 5.5 updates the subscription logic for boards and threads to properly support the ignoring of threads. See the dedicated migration guide for details. Miscellaneous Changes # View Counters # With WoltLab Suite 5.5 it is expected that view/download counters do not increase for disabled content. See WoltLab/WCF#4374 for details. Form Builder # ValueIntervalFormFieldDependency ColorFormField MultipleBoardSelectionFormField","title":"PHP API"},{"location":"migration/wsc54/php/#migrating-from-wsc-54-php","text":"","title":"Migrating from WSC 5.4 - PHP"},{"location":"migration/wsc54/php/#initial-psr-7-support","text":"WoltLab Suite will incrementally add support for object oriented request/response handling based off the PSR-7 and PSR-15 standards in the upcoming versions. WoltLab Suite 5.5 adds initial support by allowing to define the response using objects implementing the PSR-7 ResponseInterface . If a controller returns such a response object from its __run() method, this response will automatically emitted to the client. Any PSR-7 implementation is supported, but WoltLab Suite 5.5 ships with laminas-diactoros as the recommended \u201cbatteries included\u201d implementation of PSR-7. Support for PSR-7 requests and PSR-15 middlewares is expected to follow in future versions. See WoltLab/WCF#4437 for details.","title":"Initial PSR-7 support"},{"location":"migration/wsc54/php/#recommended-changes-for-woltlab-suite-55","text":"With the current support in WoltLab Suite 5.5 it is recommended to migrate the *Action classes to make use of PSR-7 responses. Control and data flow is typically fairly simple in *Action classes with most requests ending up in either a redirect or a JSON response, commonly followed by a call to exit; . Experimental support for *Page and *Form is available. It is recommended to wait for a future version before migrating these types of controllers.","title":"Recommended changes for WoltLab Suite 5.5"},{"location":"migration/wsc54/php/#migrating-redirects","text":"Previously: lib/action/ExampleRedirectAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\action ; use wcf\\system\\request\\LinkHandler ; use wcf\\util\\HeaderUtil ; final class ExampleRedirectAction extends AbstractAction { public function execute () { parent :: execute (); // Redirect to the landing page. HeaderUtil :: redirect ( LinkHandler :: getInstance () -> getLink () ); exit ; } } Now: lib/action/ExampleRedirectAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php namespace wcf\\action ; use Laminas\\Diactoros\\Response\\RedirectResponse ; use wcf\\system\\request\\LinkHandler ; final class ExampleRedirectAction extends AbstractAction { public function execute () { parent :: execute (); // Redirect to the landing page. return new RedirectResponse ( LinkHandler :: getInstance () -> getLink () ); } }","title":"Migrating Redirects"},{"location":"migration/wsc54/php/#migrating-json-responses","text":"Previously: lib/action/ExampleJsonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\action ; use wcf\\util\\JSON ; final class ExampleJsonAction extends AbstractAction { public function execute () { parent :: execute (); \\header ( 'Content-type: application/json; charset=UTF-8' ); echo JSON :: encode ([ 'foo' => 'bar' , ]); exit ; } } Now: lib/action/ExampleJsonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php namespace wcf\\action ; use Laminas\\Diactoros\\Response\\JsonResponse ; final class ExampleJsonAction extends AbstractAction { public function execute () { parent :: execute (); return new JsonResponse ([ 'foo' => 'bar' , ]); } }","title":"Migrating JSON responses"},{"location":"migration/wsc54/php/#events","text":"Historically, events were tightly coupled with a single class, with the event object being an object of this class, expecting the event listener to consume public properties and method of the event object. The $parameters array was introduced due to limitations of this pattern, avoiding moving all the values that might be of interest to the event listener into the state of the object. Events were still tightly coupled with the class that fired the event and using the opaque parameters array prevented IDEs from assisting with autocompletion and typing. WoltLab Suite 5.5 introduces the concept of dedicated, reusable event classes. Any newly introduced event will receive a dedicated class, implementing the wcf\\system\\event\\IEvent interface. These event classes may be fired from multiple locations, making them reusable to convey that a conceptual action happened, instead of a specific class doing something. An example for using the new event system could be a user logging in: Instead of listening on a the login form being submitted and the Facebook login action successfully running, an event UserLoggedIn might be fired whenever a user logs in, no matter how the login is performed. Additionally, these dedicated event classes will benefit from full IDE support. All the relevant values may be stored as real properties on the event object. Event classes should not have an Event suffix and should be stored in an event namespace in a matching location. Thus, the UserLoggedIn example might have a FQCN of \\wcf\\system\\user\\authentication\\event\\UserLoggedIn . Event listeners for events implementing IEvent need to follow PSR-14 , i.e. they need to be callable. In practice, this means that the event listener class needs to implement __invoke() . No interface has to be implemented in this case. Previously: 1 2 3 4 5 $parameters = [ 'value' => \\random_int ( 1 , 1024 ), ]; EventHandler :: getInstance () -> fireAction ( $this , 'valueAvailable' , $parameters ); lib/system/event/listener/ValueDumpListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php namespace wcf\\system\\event\\listener ; use wcf\\form\\ValueForm ; final class ValueDumpListener implements IParameterizedEventListener { /** * @inheritDoc * @param ValueForm $eventObj */ public function execute ( $eventObj , $className , $eventName , array & $parameters ) { var_dump ( $parameters [ 'value' ]); } } Now: 1 EventHandler::getInstance()->fire(new ValueAvailable(\\random_int(1, 1024))); lib/system/foo/event/ValueAvailable.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <? php namespace wcf\\system\\foo\\event ; use wcf\\system\\event\\IEvent ; final class ValueAvailable implements IEvent { /** * @var int */ private $value ; public function __construct ( int $value ) { $this -> value = $value ; } public function getValue () : int { return $this -> value ; } } lib/system/event/listener/ValueDumpListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\foo\\event\\ValueAvailable ; final class ValueDumpListener { public function __invoke ( ValueAvailable $event ) { var_dump ( $event -> getValue ()); } } See WoltLab/WCF#4000 and WoltLab/WCF#4265 for details.","title":"Events"},{"location":"migration/wsc54/php/#authentication","text":"The UserLoggedIn event was added. You should fire this event if you implement a custom login process (e.g. when adding additional external authentication providers). Example: 1 2 3 EventHandler :: getInstance () -> fire ( new UserLoggedIn ( $user ) ); See WoltLab/WCF#4356 for details.","title":"Authentication"},{"location":"migration/wsc54/php/#embedded-objects-in-comments","text":"WoltLab/WCF#4275 added support for embedded objects like mentions for comments and comment responses. To properly render embedded objects whenever you are using comments in your packages, you have to use ViewableCommentList / ViewableCommentResponseList in these places or ViewableCommentRuntimeCache / ViewableCommentResponseRuntimeCache . While these runtime caches are only available since version 5.5, the viewable list classes have always been available so that changing CommentList to ViewableCommentList , for example, is a backwards-compatible change.","title":"Embedded Objects in Comments"},{"location":"migration/wsc54/php/#emails","text":"","title":"Emails"},{"location":"migration/wsc54/php/#mailbox","text":"The Mailbox and UserMailbox classes no longer store the passed Language and User objects, but the respective ID instead. This change reduces the size of the serialized email when stored in the background queue. If you inherit from the Mailbox or UserMailbox classes, you might experience issues if you directly access the $this->language or $this->user properties. Adjust your class to use composition instead of inheritance if possible. Use the getLanguage() or getUser() getters if using composition is not possible. See WoltLab/WCF#4389 for details.","title":"Mailbox"},{"location":"migration/wsc54/php/#smtp","text":"The SmtpEmailTransport no longer supports a value of may for the $starttls property. Using the may value is unsafe as it allows for undetected MITM attacks. The use of encrypt is recommended, unless it is certain that the SMTP server does not support TLS. See WoltLab/WCF#4398 for details.","title":"SMTP"},{"location":"migration/wsc54/php/#search","text":"","title":"Search"},{"location":"migration/wsc54/php/#search-form","text":"After the overhaul of the search form, search providers are no longer bound to SearchForm and SearchResultPage . The interface ISearchObjectType and the abstract implementation AbstractSearchableObjectType have been replaced by ISearchProvider and AbstractSearchProvider . Please use ArticleSearch as a template for your own implementation See WoltLab/WCF#4605 for details.","title":"Search Form"},{"location":"migration/wsc54/php/#exceptions","text":"A new wcf\\system\\search\\exception\\SearchFailed exception was added. This exception should be thrown when executing the search query fails for (mostly) temporary reasons, such as a network partition to a remote service. It is not meant as a blanket exception to wrap everything. For example it must not be returned obvious programming errors, such as an access to an undefined variable ( ErrorException ). Catching the SearchFailed exception allows consuming code to gracefully handle search requests that are not essential for proceeding, without silencing other types of error. See WoltLab/WCF#4476 and WoltLab/WCF#4483 for details.","title":"Exceptions"},{"location":"migration/wsc54/php/#package-installation-plugins","text":"","title":"Package Installation Plugins"},{"location":"migration/wsc54/php/#database","text":"WoltLab Suite 5.5 changes the factory classes for common configurations of database columns within the PHP-based DDL API to contain a private constructor, preventing object creation. This change affects the following classes: DefaultFalseBooleanDatabaseTableColumn DefaultTrueBooleanDatabaseTableColumn NotNullInt10DatabaseTableColumn NotNullVarchar191DatabaseTableColumn NotNullVarchar255DatabaseTableColumn ObjectIdDatabaseTableColumn DatabaseTablePrimaryIndex The static create() method never returned an object of the factory class, but instead in object of the base type (e.g. IntDatabaseTableColumn for NotNullInt10DatabaseTableColumn ). Constructing an object of these factory classes is considered a bug, as the class name implies a specific column configuration, that might or might not hold if the object is modified afterwards. See WoltLab/WCF#4564 for details. WoltLab Suite 5.5 adds the IDefaultValueDatabaseTableColumn interface which is used to check whether specifying a default value is legal. For backwards compatibility this interface is implemented by AbstractDatabaseTableColumn . You should explicitly add this interface to custom table column type classes to avoid breakage if the interface is removed from AbstractDatabaseTableColumn in a future version. Likewise you should explicitly check for the interface before attempting to access the methods related to the default value of a column. See WoltLab/WCF#4733 for details.","title":"Database"},{"location":"migration/wsc54/php/#file-deletion","text":"Three new package installation plugins have been added to delete ACP templates with acpTemplateDelete , files with fileDelete , and templates with templateDelete .","title":"File Deletion"},{"location":"migration/wsc54/php/#language","text":"WoltLab/WCF#4261 has added support for deleting existing phrases with the language package installation plugin. The current structure of the language XML files language/en.xml 1 2 3 4 5 6 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </language> is deprecated and should be replaced with the new structure with an explicit <import> element like in the other package installation plugins: language/en.xml 1 2 3 4 5 6 7 8 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <import> <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </import> </language> Additionally, to now also support deleting phrases with this package installation plugin, support for a <delete> element has been added: language/en.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode= \"en\" languagename= \"English\" countrycode= \"gb\" > <import> <category name= \"wcf.foo\" > <item name= \"wcf.foo.bar\" > <![CDATA[Bar]]> </item> </category> </import> <delete> <item name= \"wcf.foo.barrr\" /> </delete> </language> Note that when deleting phrases, the category does not have to be specified because phrase identifiers are unique globally. Mixing the old structure and the new structure is not supported and will result in an error message during the import!","title":"Language"},{"location":"migration/wsc54/php/#board-and-thread-subscriptions","text":"WoltLab Suite Forum 5.5 updates the subscription logic for boards and threads to properly support the ignoring of threads. See the dedicated migration guide for details.","title":"Board and Thread Subscriptions"},{"location":"migration/wsc54/php/#miscellaneous-changes","text":"","title":"Miscellaneous Changes"},{"location":"migration/wsc54/php/#view-counters","text":"With WoltLab Suite 5.5 it is expected that view/download counters do not increase for disabled content. See WoltLab/WCF#4374 for details.","title":"View Counters"},{"location":"migration/wsc54/php/#form-builder","text":"ValueIntervalFormFieldDependency ColorFormField MultipleBoardSelectionFormField","title":"Form Builder"},{"location":"migration/wsc54/templates/","text":"Migrating from WSC 5.4 - Templates # Content Interaction Buttons # Content interactions buttons are a new way to display action buttons at the top of the page. They are intended to replace the icons in pageNavigationIcons for better accessibility while reducing the amount of buttons in contentHeaderNavigation . As a rule of thumb, there should be at most only one button in contentHeaderNavigation (primary action on this page) and three buttons in contentInteractionButtons (important actions on this page). Use contentInteractionDropdownItems for all other buttons. The template contentInteraction is included in the header and the corresponding placeholders are thus available on every page. See WoltLab/WCF#4315 for details. Phrase Modifier # The |language modifier was added to allow the piping of the phrase through other functions. This has some unwanted side effects when used with plain strings that should not support variable interpolation. Another difference to {lang} is the evaluation on runtime rather than at compile time, allowing the phrase to be taken from a variable instead. We introduces the new modifier |phrase as a thin wrapper around \\wcf\\system::WCF::getLanguage()->get() . Use |phrase instead of |language unless you want to explicitly allow template scripting on a variable's output. See WoltLab/WCF#4657 for details.","title":"Templates"},{"location":"migration/wsc54/templates/#migrating-from-wsc-54-templates","text":"","title":"Migrating from WSC 5.4 - Templates"},{"location":"migration/wsc54/templates/#content-interaction-buttons","text":"Content interactions buttons are a new way to display action buttons at the top of the page. They are intended to replace the icons in pageNavigationIcons for better accessibility while reducing the amount of buttons in contentHeaderNavigation . As a rule of thumb, there should be at most only one button in contentHeaderNavigation (primary action on this page) and three buttons in contentInteractionButtons (important actions on this page). Use contentInteractionDropdownItems for all other buttons. The template contentInteraction is included in the header and the corresponding placeholders are thus available on every page. See WoltLab/WCF#4315 for details.","title":"Content Interaction Buttons"},{"location":"migration/wsc54/templates/#phrase-modifier","text":"The |language modifier was added to allow the piping of the phrase through other functions. This has some unwanted side effects when used with plain strings that should not support variable interpolation. Another difference to {lang} is the evaluation on runtime rather than at compile time, allowing the phrase to be taken from a variable instead. We introduces the new modifier |phrase as a thin wrapper around \\wcf\\system::WCF::getLanguage()->get() . Use |phrase instead of |language unless you want to explicitly allow template scripting on a variable's output. See WoltLab/WCF#4657 for details.","title":"Phrase Modifier"},{"location":"package/database-php-api/","text":"Database PHP API # While the sql package installation plugin supports adding and removing tables, columns, and indices, it is not able to handle cases where the added table, column, or index already exist. We have added a new PHP-based API to manipulate the database scheme which can be used in combination with the script package installation plugin that skips parts that already exist: 1 2 3 4 5 6 7 8 9 10 $tables = [ // list of `DatabaseTable` objects ]; ( new DatabaseTableChangeProcessor ( /** @var ScriptPackageInstallationPlugin $this */ $this -> installation -> getPackage (), $tables , WCF :: getDB () -> getEditor ()) ) -> process (); All of the relevant components can be found in the wcf\\system\\database\\table namespace. With WoltLab Suite 5.4, you should use the new database package installation plugin for which you only have to return the array of affected database tables: 1 2 3 return [ // list of `DatabaseTable` objects ]; Database Tables # There are two classes representing database tables: DatabaseTable and PartialDatabaseTable . If a new table should be created, use DatabaseTable . In all other cases, PartialDatabaseTable should be used as it provides an additional save-guard against accidentally creating a new table by having a typo in the table name: If the tables does not already exist, a table represented by PartialDatabaseTable will cause an exception (while a DatabaseTable table will simply be created). To create a table, a DatabaseTable object with the table's name as to be created and table's columns, foreign keys and indices have to be specified: 1 2 3 4 5 6 7 8 9 10 DatabaseTable :: create ( 'foo1_bar' ) -> columns ([ // columns ]) -> foreignKeys ([ // foreign keys ]) -> indices ([ // indices ]) To update a table, the same code as above can be used, except for PartialDatabaseTable being used instead of DatabaseTable . To drop a table, only the drop() method has to be called: 1 2 PartialDatabaseTable :: create ( 'foo1_bar' ) -> drop () Columns # To represent a column of a database table, you have to create an instance of the relevant column class found in the wcf\\system\\database\\table\\column namespace. Such instances are created similarly to database table objects using the create() factory method and passing the column name as the parameter. Every column type supports the following methods: defaultValue($defaultValue) sets the default value of the column (default: none). drop() to drop the column. notNull($notNull = true) sets if the value of the column can be NULL (default: false ). Depending on the specific column class implementing additional interfaces, the following methods are also available: IAutoIncrementDatabaseTableColumn::autoIncrement($autoIncrement = true) sets if the value of the colum is auto-incremented. IDecimalsDatabaseTableColumn::decimals($decimals) sets the number of decimals the column supports. IEnumDatabaseTableColumn::enumValues(array $values) sets the predetermined set of valid values of the column. ILengthDatabaseTableColumn::length($length) sets the (maximum) length of the column. Additionally, there are some additionally classes of commonly used columns with specific properties: DefaultFalseBooleanDatabaseTableColumn (a tinyint column with length 1 , default value 0 and whose values cannot be null ) DefaultTrueBooleanDatabaseTableColumn (a tinyint column with length 0 , default value 0 and whose values cannot be null ) NotNullInt10DatabaseTableColumn (a int column with length 10 and whose values cannot be null ) NotNullVarchar191DatabaseTableColumn (a varchar column with length 191 and whose values cannot be null ) NotNullVarchar255DatabaseTableColumn (a varchar column with length 255 and whose values cannot be null ) ObjectIdDatabaseTableColumn (a int column with length 10 , whose values cannot be null , and whose values are auto-incremented) Examples: 1 2 3 4 5 6 7 DefaultFalseBooleanDatabaseTableColumn :: create ( 'isDisabled' ) NotNullInt10DatabaseTableColumn :: create ( 'fooTypeID' ) SmallintDatabaseTableColumn :: create ( 'bar' ) -> length ( 5 ) -> notNull () Foreign Keys # Foreign keys are represented by DatabaseTableForeignKey objects: 1 2 3 4 5 DatabaseTableForeignKey :: create () -> columns ([ 'fooID' ]) -> referencedTable ( 'wcf1_foo' ) -> referencedColumns ([ 'fooID' ]) -> onDelete ( 'CASCADE' ) The supported actions for onDelete() and onUpdate() are CASCADE , NO ACTION , and SET NULL . To drop a foreign key, all of the relevant data to create the foreign key has to be present and the drop() method has to be called. DatabaseTableForeignKey::create() also supports the foreign key name as a parameter. If it is not present, DatabaseTable::foreignKeys() will automatically set one based on the foreign key's data. Indices # Indices are represented by DatabaseTableIndex objects: 1 2 3 DatabaseTableIndex :: create () -> type ( DatabaseTableIndex :: UNIQUE_TYPE ) -> columns ([ 'fooID' ]) There are four different types: DatabaseTableIndex::DEFAULT_TYPE (default), DatabaseTableIndex::PRIMARY_TYPE , DatabaseTableIndex::UNIQUE_TYPE , and DatabaseTableIndex::FULLTEXT_TYPE . For primary keys, there is also the DatabaseTablePrimaryIndex class which automatically sets the type to DatabaseTableIndex::PRIMARY_TYPE . To drop a index, all of the relevant data to create the index has to be present and the drop() method has to be called. DatabaseTableIndex::create() also supports the index name as a parameter. If it is not present, DatabaseTable::indices() will automatically set one based on the index data.","title":"Database PHP API"},{"location":"package/database-php-api/#database-php-api","text":"While the sql package installation plugin supports adding and removing tables, columns, and indices, it is not able to handle cases where the added table, column, or index already exist. We have added a new PHP-based API to manipulate the database scheme which can be used in combination with the script package installation plugin that skips parts that already exist: 1 2 3 4 5 6 7 8 9 10 $tables = [ // list of `DatabaseTable` objects ]; ( new DatabaseTableChangeProcessor ( /** @var ScriptPackageInstallationPlugin $this */ $this -> installation -> getPackage (), $tables , WCF :: getDB () -> getEditor ()) ) -> process (); All of the relevant components can be found in the wcf\\system\\database\\table namespace. With WoltLab Suite 5.4, you should use the new database package installation plugin for which you only have to return the array of affected database tables: 1 2 3 return [ // list of `DatabaseTable` objects ];","title":"Database PHP API"},{"location":"package/database-php-api/#database-tables","text":"There are two classes representing database tables: DatabaseTable and PartialDatabaseTable . If a new table should be created, use DatabaseTable . In all other cases, PartialDatabaseTable should be used as it provides an additional save-guard against accidentally creating a new table by having a typo in the table name: If the tables does not already exist, a table represented by PartialDatabaseTable will cause an exception (while a DatabaseTable table will simply be created). To create a table, a DatabaseTable object with the table's name as to be created and table's columns, foreign keys and indices have to be specified: 1 2 3 4 5 6 7 8 9 10 DatabaseTable :: create ( 'foo1_bar' ) -> columns ([ // columns ]) -> foreignKeys ([ // foreign keys ]) -> indices ([ // indices ]) To update a table, the same code as above can be used, except for PartialDatabaseTable being used instead of DatabaseTable . To drop a table, only the drop() method has to be called: 1 2 PartialDatabaseTable :: create ( 'foo1_bar' ) -> drop ()","title":"Database Tables"},{"location":"package/database-php-api/#columns","text":"To represent a column of a database table, you have to create an instance of the relevant column class found in the wcf\\system\\database\\table\\column namespace. Such instances are created similarly to database table objects using the create() factory method and passing the column name as the parameter. Every column type supports the following methods: defaultValue($defaultValue) sets the default value of the column (default: none). drop() to drop the column. notNull($notNull = true) sets if the value of the column can be NULL (default: false ). Depending on the specific column class implementing additional interfaces, the following methods are also available: IAutoIncrementDatabaseTableColumn::autoIncrement($autoIncrement = true) sets if the value of the colum is auto-incremented. IDecimalsDatabaseTableColumn::decimals($decimals) sets the number of decimals the column supports. IEnumDatabaseTableColumn::enumValues(array $values) sets the predetermined set of valid values of the column. ILengthDatabaseTableColumn::length($length) sets the (maximum) length of the column. Additionally, there are some additionally classes of commonly used columns with specific properties: DefaultFalseBooleanDatabaseTableColumn (a tinyint column with length 1 , default value 0 and whose values cannot be null ) DefaultTrueBooleanDatabaseTableColumn (a tinyint column with length 0 , default value 0 and whose values cannot be null ) NotNullInt10DatabaseTableColumn (a int column with length 10 and whose values cannot be null ) NotNullVarchar191DatabaseTableColumn (a varchar column with length 191 and whose values cannot be null ) NotNullVarchar255DatabaseTableColumn (a varchar column with length 255 and whose values cannot be null ) ObjectIdDatabaseTableColumn (a int column with length 10 , whose values cannot be null , and whose values are auto-incremented) Examples: 1 2 3 4 5 6 7 DefaultFalseBooleanDatabaseTableColumn :: create ( 'isDisabled' ) NotNullInt10DatabaseTableColumn :: create ( 'fooTypeID' ) SmallintDatabaseTableColumn :: create ( 'bar' ) -> length ( 5 ) -> notNull ()","title":"Columns"},{"location":"package/database-php-api/#foreign-keys","text":"Foreign keys are represented by DatabaseTableForeignKey objects: 1 2 3 4 5 DatabaseTableForeignKey :: create () -> columns ([ 'fooID' ]) -> referencedTable ( 'wcf1_foo' ) -> referencedColumns ([ 'fooID' ]) -> onDelete ( 'CASCADE' ) The supported actions for onDelete() and onUpdate() are CASCADE , NO ACTION , and SET NULL . To drop a foreign key, all of the relevant data to create the foreign key has to be present and the drop() method has to be called. DatabaseTableForeignKey::create() also supports the foreign key name as a parameter. If it is not present, DatabaseTable::foreignKeys() will automatically set one based on the foreign key's data.","title":"Foreign Keys"},{"location":"package/database-php-api/#indices","text":"Indices are represented by DatabaseTableIndex objects: 1 2 3 DatabaseTableIndex :: create () -> type ( DatabaseTableIndex :: UNIQUE_TYPE ) -> columns ([ 'fooID' ]) There are four different types: DatabaseTableIndex::DEFAULT_TYPE (default), DatabaseTableIndex::PRIMARY_TYPE , DatabaseTableIndex::UNIQUE_TYPE , and DatabaseTableIndex::FULLTEXT_TYPE . For primary keys, there is also the DatabaseTablePrimaryIndex class which automatically sets the type to DatabaseTableIndex::PRIMARY_TYPE . To drop a index, all of the relevant data to create the index has to be present and the drop() method has to be called. DatabaseTableIndex::create() also supports the index name as a parameter. If it is not present, DatabaseTable::indices() will automatically set one based on the index data.","title":"Indices"},{"location":"package/package-xml/","text":"package.xml # The package.xml is the core component of every package. It provides the meta data (e.g. package name, description, author) and the instruction set for a new installation and/or updating from a previous version. Example # package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.example.package\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/package.xsd\" > <packageinformation> <packagename> Simple Package </packagename> <packagedescription> A simple package to demonstrate the package system of WoltLab Suite Core </packagedescription> <version> 1.0.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> YOUR NAME </author> <authorurl> http://www.example.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"template\" > templates.tar </instruction> </instructions> </package> Elements # <package> # The root node of every package.xml it contains the reference to the namespace and the location of the XML Schema Definition (XSD). The attribute name is the most important part, it holds the unique package identifier and is mandatory. It is based upon your domain name and the package name of your choice. For example WoltLab Suite Forum (formerly know an WoltLab Burning Board and usually abbreviated as wbb ) is created by WoltLab which owns the domain woltlab.com . The resulting package identifier is com.woltlab.wbb ( <tld>.<domain>.<packageName> ). <packageinformation> # Holds the entire meta data of the package. <packagename> # This is the actual package name displayed to the end user, this can be anything you want, try to keep it short. It supports the attribute languagecode which allows you to provide the package name in different languages, please be aware that if it is not present, en (English) is assumed: 1 2 3 4 <packageinformation> <packagename> Simple Package </packagename> <packagename languagecode= \"de\" > Einfaches Paket </packagename> </packageinformation> <packagedescription> # Brief summary of the package, use it to explain what it does since the package name might not always be clear enough. The attribute languagecode is available here too, please reference to <packagename> for details. <version> # The package's version number, this is a string consisting of three numbers separated with a dot and optionally followed by a keyword (must be followed with another number). The possible keywords are: Alpha/dev (both is regarded to be the same) Beta RC (release candidate) pl (patch level) Valid examples: 1.0.0 1.12.13 Alpha 19 7.0.0 pl 3 Invalid examples: 1.0.0 Beta (keyword Beta must be followed by a number) 2.0 RC 3 (version number must consists of 3 blocks of numbers) 1.2.3 dev 4.5 (4.5 is not an integer, 4 or 5 would be valid but not the fraction) <date> # Must be a valid ISO 8601 date, e.g. 2013-12-27 . <authorinformation> # Holds meta data regarding the package's author. <author> # Can be anything you want. <authorurl> # (optional) URL to the author's website. <requiredpackages> # A list of packages including their version required for this package to work. <requiredpackage> # Example: 1 <requiredpackage minversion= \"2.7.5\" file= \"requirements/com.example.foo.tar\" > com.example.foo </requiredpackage> The attribute minversion must be a valid version number as described in <version> . The file attribute is optional and specifies the location of the required package's archive relative to the package.xml . <optionalpackage> # A list of optional packages which can be selected by the user at the very end of the installation process. <optionalpackage> # Example: 1 <optionalpackage file= \"optionals/com.example.bar.tar\" > com.example.bar </optionalpackage> The file attribute specifies the location of the optional package's archive relative to the package.xml . <excludedpackages> # List of packages which conflict with this package. It is not possible to install it if any of the specified packages is installed. In return you cannot install an excluded package if this package is installed. <excludedpackage> # Example: 1 <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> The attribute version must be a valid version number as described in the \\<version> section. In the example above it will be impossible to install this package in WoltLab Suite Core 6.0.0 Alpha 1 or higher. <compatibility> # Available since WoltLab Suite 3.1 With the release of WoltLab Suite 5.2 the API versions were abolished. Instead of using API versions packages should exclude version 6.0.0 Alpha 1 of com.woltlab.wcf going forward. WoltLab Suite 3.1 introduced a new versioning system that focused around the API compatibility and is intended to replace the <excludedpackage> instruction for the Core for most plugins. The <compatibility> -tag holds a list of compatible API versions, and while only a single version is available at the time of writing, future versions will add more versions with backwards-compatibility in mind. Example: 1 2 3 <compatibility> <api version= \"2018\" /> </compatibility> Existing API versions # WoltLab Suite Core API-Version Backwards-Compatible to API-Version 3.1 2018 n/a <instructions> # List of instructions to be executed upon install or update. The order is important, the topmost <instruction> will be executed first. <instructions type=\"install\"> # List of instructions for a new installation of this package. <instructions type=\"update\" fromversion=\"\u2026\"> # The attribute fromversion must be a valid version number as described in the \\<version> section and specifies a possible update from that very version to the package's version. The installation process will pick exactly one update instruction, ignoring everything else. Please read the explanation below! Example: Installed version: 1.0.0 Package version: 1.0.2 1 2 3 4 5 6 <instructions type= \"update\" fromversion= \"1.0.0\" > <!-- \u2026 --> </instructions> <instructions type= \"update\" fromversion= \"1.0.1\" > <!-- \u2026 --> </instructions> In this example WoltLab Suite Core will pick the first update block since it allows an update from 1.0.0 -> 1.0.2 . The other block is not considered, since the currently installed version is 1.0.0 . After applying the update block ( fromversion=\"1.0.0\" ), the version now reads 1.0.2 . <instruction> # Example: 1 <instruction type= \"objectTypeDefinition\" > objectTypeDefinition.xml </instruction> The attribute type specifies the instruction type which is used to determine the package installation plugin (PIP) invoked to handle its value. The value must be a valid file relative to the location of package.xml . Many PIPs provide default file names which are used if no value is given: 1 <instruction type= \"objectTypeDefinition\" /> There is a list of all default PIPs available. Both the type -attribute and the element value are case-sensitive. Windows does not care if the file is called objecttypedefinition.xml but was referenced as objectTypeDefinition.xml , but both Linux and Mac systems will be unable to find the file. In addition to the type attribute, an optional run attribute (with standalone as the only valid value) is supported which forces the installation to execute this PIP in an isolated request, allowing a single, resource-heavy PIP to execute without encountering restrictions such as PHP\u2019s memory_limit or max_execution_time : 1 <instruction type= \"file\" run= \"standalone\" /> <void/> # Sometimes a package update should only adjust the metadata of the package, for example, an optional package was added. However, WoltLab Suite Core requires that the list of <instructions> is non-empty. Instead of using a dummy <instruction> that idempotently updates some PIP, the <void/> tag can be used for this use-case. Using the <void/> tag is only valid for <instructions type=\"update\"> and must not be accompanied by other <instruction> tags. Example: 1 2 3 <instructions type= \"update\" fromversion= \"1.0.0\" > <void/> </instructions>","title":"package.xml"},{"location":"package/package-xml/#packagexml","text":"The package.xml is the core component of every package. It provides the meta data (e.g. package name, description, author) and the instruction set for a new installation and/or updating from a previous version.","title":"package.xml"},{"location":"package/package-xml/#example","text":"package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.example.package\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/package.xsd\" > <packageinformation> <packagename> Simple Package </packagename> <packagedescription> A simple package to demonstrate the package system of WoltLab Suite Core </packagedescription> <version> 1.0.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> YOUR NAME </author> <authorurl> http://www.example.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"template\" > templates.tar </instruction> </instructions> </package>","title":"Example"},{"location":"package/package-xml/#elements","text":"","title":"Elements"},{"location":"package/package-xml/#package","text":"The root node of every package.xml it contains the reference to the namespace and the location of the XML Schema Definition (XSD). The attribute name is the most important part, it holds the unique package identifier and is mandatory. It is based upon your domain name and the package name of your choice. For example WoltLab Suite Forum (formerly know an WoltLab Burning Board and usually abbreviated as wbb ) is created by WoltLab which owns the domain woltlab.com . The resulting package identifier is com.woltlab.wbb ( <tld>.<domain>.<packageName> ).","title":"<package>"},{"location":"package/package-xml/#packageinformation","text":"Holds the entire meta data of the package.","title":"<packageinformation>"},{"location":"package/package-xml/#packagename","text":"This is the actual package name displayed to the end user, this can be anything you want, try to keep it short. It supports the attribute languagecode which allows you to provide the package name in different languages, please be aware that if it is not present, en (English) is assumed: 1 2 3 4 <packageinformation> <packagename> Simple Package </packagename> <packagename languagecode= \"de\" > Einfaches Paket </packagename> </packageinformation>","title":"<packagename>"},{"location":"package/package-xml/#packagedescription","text":"Brief summary of the package, use it to explain what it does since the package name might not always be clear enough. The attribute languagecode is available here too, please reference to <packagename> for details.","title":"<packagedescription>"},{"location":"package/package-xml/#version","text":"The package's version number, this is a string consisting of three numbers separated with a dot and optionally followed by a keyword (must be followed with another number). The possible keywords are: Alpha/dev (both is regarded to be the same) Beta RC (release candidate) pl (patch level) Valid examples: 1.0.0 1.12.13 Alpha 19 7.0.0 pl 3 Invalid examples: 1.0.0 Beta (keyword Beta must be followed by a number) 2.0 RC 3 (version number must consists of 3 blocks of numbers) 1.2.3 dev 4.5 (4.5 is not an integer, 4 or 5 would be valid but not the fraction)","title":"<version>"},{"location":"package/package-xml/#date","text":"Must be a valid ISO 8601 date, e.g. 2013-12-27 .","title":"<date>"},{"location":"package/package-xml/#authorinformation","text":"Holds meta data regarding the package's author.","title":"<authorinformation>"},{"location":"package/package-xml/#author","text":"Can be anything you want.","title":"<author>"},{"location":"package/package-xml/#authorurl","text":"(optional) URL to the author's website.","title":"<authorurl>"},{"location":"package/package-xml/#requiredpackages","text":"A list of packages including their version required for this package to work.","title":"<requiredpackages>"},{"location":"package/package-xml/#requiredpackage","text":"Example: 1 <requiredpackage minversion= \"2.7.5\" file= \"requirements/com.example.foo.tar\" > com.example.foo </requiredpackage> The attribute minversion must be a valid version number as described in <version> . The file attribute is optional and specifies the location of the required package's archive relative to the package.xml .","title":"<requiredpackage>"},{"location":"package/package-xml/#optionalpackage","text":"A list of optional packages which can be selected by the user at the very end of the installation process.","title":"<optionalpackage>"},{"location":"package/package-xml/#optionalpackage_1","text":"Example: 1 <optionalpackage file= \"optionals/com.example.bar.tar\" > com.example.bar </optionalpackage> The file attribute specifies the location of the optional package's archive relative to the package.xml .","title":"<optionalpackage>"},{"location":"package/package-xml/#excludedpackages","text":"List of packages which conflict with this package. It is not possible to install it if any of the specified packages is installed. In return you cannot install an excluded package if this package is installed.","title":"<excludedpackages>"},{"location":"package/package-xml/#excludedpackage","text":"Example: 1 <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> The attribute version must be a valid version number as described in the \\<version> section. In the example above it will be impossible to install this package in WoltLab Suite Core 6.0.0 Alpha 1 or higher.","title":"<excludedpackage>"},{"location":"package/package-xml/#compatibility","text":"Available since WoltLab Suite 3.1 With the release of WoltLab Suite 5.2 the API versions were abolished. Instead of using API versions packages should exclude version 6.0.0 Alpha 1 of com.woltlab.wcf going forward. WoltLab Suite 3.1 introduced a new versioning system that focused around the API compatibility and is intended to replace the <excludedpackage> instruction for the Core for most plugins. The <compatibility> -tag holds a list of compatible API versions, and while only a single version is available at the time of writing, future versions will add more versions with backwards-compatibility in mind. Example: 1 2 3 <compatibility> <api version= \"2018\" /> </compatibility>","title":"<compatibility>"},{"location":"package/package-xml/#existing-api-versions","text":"WoltLab Suite Core API-Version Backwards-Compatible to API-Version 3.1 2018 n/a","title":"Existing API versions"},{"location":"package/package-xml/#instructions","text":"List of instructions to be executed upon install or update. The order is important, the topmost <instruction> will be executed first.","title":"<instructions>"},{"location":"package/package-xml/#instructions-typeinstall","text":"List of instructions for a new installation of this package.","title":"<instructions type=\"install\">"},{"location":"package/package-xml/#instructions-typeupdate-fromversion","text":"The attribute fromversion must be a valid version number as described in the \\<version> section and specifies a possible update from that very version to the package's version. The installation process will pick exactly one update instruction, ignoring everything else. Please read the explanation below! Example: Installed version: 1.0.0 Package version: 1.0.2 1 2 3 4 5 6 <instructions type= \"update\" fromversion= \"1.0.0\" > <!-- \u2026 --> </instructions> <instructions type= \"update\" fromversion= \"1.0.1\" > <!-- \u2026 --> </instructions> In this example WoltLab Suite Core will pick the first update block since it allows an update from 1.0.0 -> 1.0.2 . The other block is not considered, since the currently installed version is 1.0.0 . After applying the update block ( fromversion=\"1.0.0\" ), the version now reads 1.0.2 .","title":"<instructions type=\"update\" fromversion=\"\u2026\">"},{"location":"package/package-xml/#instruction","text":"Example: 1 <instruction type= \"objectTypeDefinition\" > objectTypeDefinition.xml </instruction> The attribute type specifies the instruction type which is used to determine the package installation plugin (PIP) invoked to handle its value. The value must be a valid file relative to the location of package.xml . Many PIPs provide default file names which are used if no value is given: 1 <instruction type= \"objectTypeDefinition\" /> There is a list of all default PIPs available. Both the type -attribute and the element value are case-sensitive. Windows does not care if the file is called objecttypedefinition.xml but was referenced as objectTypeDefinition.xml , but both Linux and Mac systems will be unable to find the file. In addition to the type attribute, an optional run attribute (with standalone as the only valid value) is supported which forces the installation to execute this PIP in an isolated request, allowing a single, resource-heavy PIP to execute without encountering restrictions such as PHP\u2019s memory_limit or max_execution_time : 1 <instruction type= \"file\" run= \"standalone\" />","title":"<instruction>"},{"location":"package/package-xml/#void","text":"Sometimes a package update should only adjust the metadata of the package, for example, an optional package was added. However, WoltLab Suite Core requires that the list of <instructions> is non-empty. Instead of using a dummy <instruction> that idempotently updates some PIP, the <void/> tag can be used for this use-case. Using the <void/> tag is only valid for <instructions type=\"update\"> and must not be accompanied by other <instruction> tags. Example: 1 2 3 <instructions type= \"update\" fromversion= \"1.0.0\" > <void/> </instructions>","title":"<void/>"},{"location":"package/pip/","text":"Package Installation Plugins # Package Installation Plugins (PIPs) are interfaces to deploy and edit content as well as components. For XML-based PIPs: <![CDATA[]]> must be used for language items and page contents. In all other cases it may only be used when necessary. Built-In PIPs # Name Description aclOption Customizable permissions for individual objects acpMenu Admin panel menu categories and items acpSearchProvider Data provider for the admin panel search acpTemplate Admin panel templates acpTemplateDelete Deletes admin panel templates installed with acpTemplate bbcode BBCodes for rich message formatting box Boxes that can be placed anywhere on a page clipboardAction Perform bulk operations on marked objects coreObject Access Singletons from within the template cronjob Periodically execute code with customizable intervals database Updates the database layout using the PHP API eventListener Register listeners for the event system file Deploy any type of files with the exception of templates fileDelete Deletes files installed with file language Language items mediaProvider Detect and convert links to media providers menu Side-wide and custom per-page menus menuItem Menu items for menus created through the menu PIP objectType Flexible type registry based on definitions objectTypeDefinition Groups objects and classes by functionality option Side-wide configuration options page Register page controllers and text-based pages pip Package Installation Plugins script Execute arbitrary PHP code during installation, update and uninstallation smiley Smileys sql Execute SQL instructions using a MySQL-flavored syntax (also see database PHP API ) style Style template Frontend templates templateDelete Deletes frontend templates installed with template templateListener Embed template code into templates without altering the original userGroupOption Permissions for user groups userMenu User menu categories and items userNotificationEvent Events of the user notification system userOption User settings userProfileMenu User profile tabs","title":"Overview"},{"location":"package/pip/#package-installation-plugins","text":"Package Installation Plugins (PIPs) are interfaces to deploy and edit content as well as components. For XML-based PIPs: <![CDATA[]]> must be used for language items and page contents. In all other cases it may only be used when necessary.","title":"Package Installation Plugins"},{"location":"package/pip/#built-in-pips","text":"Name Description aclOption Customizable permissions for individual objects acpMenu Admin panel menu categories and items acpSearchProvider Data provider for the admin panel search acpTemplate Admin panel templates acpTemplateDelete Deletes admin panel templates installed with acpTemplate bbcode BBCodes for rich message formatting box Boxes that can be placed anywhere on a page clipboardAction Perform bulk operations on marked objects coreObject Access Singletons from within the template cronjob Periodically execute code with customizable intervals database Updates the database layout using the PHP API eventListener Register listeners for the event system file Deploy any type of files with the exception of templates fileDelete Deletes files installed with file language Language items mediaProvider Detect and convert links to media providers menu Side-wide and custom per-page menus menuItem Menu items for menus created through the menu PIP objectType Flexible type registry based on definitions objectTypeDefinition Groups objects and classes by functionality option Side-wide configuration options page Register page controllers and text-based pages pip Package Installation Plugins script Execute arbitrary PHP code during installation, update and uninstallation smiley Smileys sql Execute SQL instructions using a MySQL-flavored syntax (also see database PHP API ) style Style template Frontend templates templateDelete Deletes frontend templates installed with template templateListener Embed template code into templates without altering the original userGroupOption Permissions for user groups userMenu User menu categories and items userNotificationEvent Events of the user notification system userOption User settings userProfileMenu User profile tabs","title":"Built-In PIPs"},{"location":"package/pip/acl-option/","text":"ACL Option Package Installation Plugin # Add customizable permissions for individual objects. Option Components # Each acl option is described as an <option> element with the mandatory attribute name . <categoryname> # Optional The name of the acl option category to which the option belongs. <objecttype> # The name of the acl object type (of the object type definition com.woltlab.wcf.acl ). Category Components # Each acl option category is described as an <category> element with the mandatory attribute name that should follow the naming pattern <permissionName> or <permissionType>.<permissionName> , with <permissionType> generally having user or mod as value. <objecttype> # The name of the acl object type (of the object type definition com.woltlab.wcf.acl ). Example # aclOption.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/aclOption.xsd\" > <import> <categories> <category name= \"user.example\" > <objecttype> com.example.wcf.example </objecttype> </category> <category name= \"mod.example\" > <objecttype> com.example.wcf.example </objecttype> </category> </categories> <options> <option name= \"canAddExample\" > <categoryname> user.example </categoryname> <objecttype> com.example.wcf.example </objecttype> </option> <option name= \"canDeleteExample\" > <categoryname> mod.example </categoryname> <objecttype> com.example.wcf.example </objecttype> </option> </options> </import> <delete> <optioncategory name= \"old.example\" > <objecttype> com.example.wcf.example </objecttype> </optioncategory> <option name= \"canDoSomethingWithExample\" > <objecttype> com.example.wcf.example </objecttype> </option> </delete> </data>","title":"aclOption"},{"location":"package/pip/acl-option/#acl-option-package-installation-plugin","text":"Add customizable permissions for individual objects.","title":"ACL Option Package Installation Plugin"},{"location":"package/pip/acl-option/#option-components","text":"Each acl option is described as an <option> element with the mandatory attribute name .","title":"Option Components"},{"location":"package/pip/acl-option/#categoryname","text":"Optional The name of the acl option category to which the option belongs.","title":"<categoryname>"},{"location":"package/pip/acl-option/#objecttype","text":"The name of the acl object type (of the object type definition com.woltlab.wcf.acl ).","title":"<objecttype>"},{"location":"package/pip/acl-option/#category-components","text":"Each acl option category is described as an <category> element with the mandatory attribute name that should follow the naming pattern <permissionName> or <permissionType>.<permissionName> , with <permissionType> generally having user or mod as value.","title":"Category Components"},{"location":"package/pip/acl-option/#objecttype_1","text":"The name of the acl object type (of the object type definition com.woltlab.wcf.acl ).","title":"<objecttype>"},{"location":"package/pip/acl-option/#example","text":"aclOption.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/aclOption.xsd\" > <import> <categories> <category name= \"user.example\" > <objecttype> com.example.wcf.example </objecttype> </category> <category name= \"mod.example\" > <objecttype> com.example.wcf.example </objecttype> </category> </categories> <options> <option name= \"canAddExample\" > <categoryname> user.example </categoryname> <objecttype> com.example.wcf.example </objecttype> </option> <option name= \"canDeleteExample\" > <categoryname> mod.example </categoryname> <objecttype> com.example.wcf.example </objecttype> </option> </options> </import> <delete> <optioncategory name= \"old.example\" > <objecttype> com.example.wcf.example </objecttype> </optioncategory> <option name= \"canDoSomethingWithExample\" > <objecttype> com.example.wcf.example </objecttype> </option> </delete> </data>","title":"Example"},{"location":"package/pip/acp-menu/","text":"ACP Menu Package Installation Plugin # Registers new ACP menu items. Components # Each item is described as an <acpmenuitem> element with the mandatory attribute name . <parent> # Optional The item\u2019s parent item. <showorder> # Optional Specifies the order of this item within the parent item. <controller> # The fully qualified class name of the target controller. If not specified this item serves as a category. <link> # Additional components if <controller> is set, the full external link otherwise. <icon> # Use an icon only for top-level and 4th-level items. Name of the Font Awesome icon class. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the tab to be shown. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the tab to be shown. Example # acpMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpMenu.xsd\" > <import> <acpmenuitem name= \"foo.acp.menu.link.example\" > <parent> wcf.acp.menu.link.application </parent> </acpmenuitem> <acpmenuitem name= \"foo.acp.menu.link.example.list\" > <controller> foo\\acp\\page\\ExampleListPage </controller> <parent> foo.acp.menu.link.example </parent> <permissions> admin.foo.canManageExample </permissions> <showorder> 1 </showorder> </acpmenuitem> <acpmenuitem name= \"foo.acp.menu.link.example.add\" > <controller> foo\\acp\\form\\ExampleAddForm </controller> <parent> foo.acp.menu.link.example.list </parent> <permissions> admin.foo.canManageExample </permissions> <icon> fa-plus </icon> </acpmenuitem> </import> </data>","title":"acpMenu"},{"location":"package/pip/acp-menu/#acp-menu-package-installation-plugin","text":"Registers new ACP menu items.","title":"ACP Menu Package Installation Plugin"},{"location":"package/pip/acp-menu/#components","text":"Each item is described as an <acpmenuitem> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/acp-menu/#parent","text":"Optional The item\u2019s parent item.","title":"<parent>"},{"location":"package/pip/acp-menu/#showorder","text":"Optional Specifies the order of this item within the parent item.","title":"<showorder>"},{"location":"package/pip/acp-menu/#controller","text":"The fully qualified class name of the target controller. If not specified this item serves as a category.","title":"<controller>"},{"location":"package/pip/acp-menu/#link","text":"Additional components if <controller> is set, the full external link otherwise.","title":"<link>"},{"location":"package/pip/acp-menu/#icon","text":"Use an icon only for top-level and 4th-level items. Name of the Font Awesome icon class.","title":"<icon>"},{"location":"package/pip/acp-menu/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the tab to be shown.","title":"<options>"},{"location":"package/pip/acp-menu/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the tab to be shown.","title":"<permissions>"},{"location":"package/pip/acp-menu/#example","text":"acpMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpMenu.xsd\" > <import> <acpmenuitem name= \"foo.acp.menu.link.example\" > <parent> wcf.acp.menu.link.application </parent> </acpmenuitem> <acpmenuitem name= \"foo.acp.menu.link.example.list\" > <controller> foo\\acp\\page\\ExampleListPage </controller> <parent> foo.acp.menu.link.example </parent> <permissions> admin.foo.canManageExample </permissions> <showorder> 1 </showorder> </acpmenuitem> <acpmenuitem name= \"foo.acp.menu.link.example.add\" > <controller> foo\\acp\\form\\ExampleAddForm </controller> <parent> foo.acp.menu.link.example.list </parent> <permissions> admin.foo.canManageExample </permissions> <icon> fa-plus </icon> </acpmenuitem> </import> </data>","title":"Example"},{"location":"package/pip/acp-search-provider/","text":"ACP Search Provider Package Installation Plugin # Registers data provider for the admin panel search. Components # Each acp search result provider is described as an <acpsearchprovider> element with the mandatory attribute name . <classname> # The name of the class providing the search results, the class has to implement the wcf\\system\\search\\acp\\IACPSearchResultProvider interface. <showorder> # Optional Determines at which position of the search result list the provided results are shown. Example # acpSearchProvider.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpSearchProvider.xsd\" > <import> <acpsearchprovider name= \"com.woltlab.wcf.example\" > <classname> wcf\\system\\search\\acp\\ExampleACPSearchResultProvider </classname> <showorder> 1 </showorder> </acpsearchprovider> </import> </data>","title":"acpSearchProvider"},{"location":"package/pip/acp-search-provider/#acp-search-provider-package-installation-plugin","text":"Registers data provider for the admin panel search.","title":"ACP Search Provider Package Installation Plugin"},{"location":"package/pip/acp-search-provider/#components","text":"Each acp search result provider is described as an <acpsearchprovider> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/acp-search-provider/#classname","text":"The name of the class providing the search results, the class has to implement the wcf\\system\\search\\acp\\IACPSearchResultProvider interface.","title":"<classname>"},{"location":"package/pip/acp-search-provider/#showorder","text":"Optional Determines at which position of the search result list the provided results are shown.","title":"<showorder>"},{"location":"package/pip/acp-search-provider/#example","text":"acpSearchProvider.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpSearchProvider.xsd\" > <import> <acpsearchprovider name= \"com.woltlab.wcf.example\" > <classname> wcf\\system\\search\\acp\\ExampleACPSearchResultProvider </classname> <showorder> 1 </showorder> </acpsearchprovider> </import> </data>","title":"Example"},{"location":"package/pip/acp-template-delete/","text":"ACP Template Delete Package Installation Plugin # Available since WoltLab Suite 5.5. Deletes admin panel templates installed with the acpTemplate package installation plugin. You cannot delete acp templates provided by other packages. Components # Each item is described as a <template> element with an optional application , which behaves like it does for acp templates . The templates are identified by their name like when adding template listeners , i.e. by the file name without the .tpl file extension. Example # acpTemplateDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpTemplateDelete.xsd\" > <delete> <template> fouAdd </template> <template application= \"app\" > __appAdd </template> </delete> </data>","title":"acpTemplateDelete"},{"location":"package/pip/acp-template-delete/#acp-template-delete-package-installation-plugin","text":"Available since WoltLab Suite 5.5. Deletes admin panel templates installed with the acpTemplate package installation plugin. You cannot delete acp templates provided by other packages.","title":"ACP Template Delete Package Installation Plugin"},{"location":"package/pip/acp-template-delete/#components","text":"Each item is described as a <template> element with an optional application , which behaves like it does for acp templates . The templates are identified by their name like when adding template listeners , i.e. by the file name without the .tpl file extension.","title":"Components"},{"location":"package/pip/acp-template-delete/#example","text":"acpTemplateDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/acpTemplateDelete.xsd\" > <delete> <template> fouAdd </template> <template application= \"app\" > __appAdd </template> </delete> </data>","title":"Example"},{"location":"package/pip/acp-template/","text":"ACP Template Installation Plugin # Add templates for acp pages and forms by providing an archive containing the template files. You cannot overwrite acp templates provided by other packages. Archive # The acpTemplate package installation plugins expects a .tar (recommended) or .tar.gz archive. The templates must all be in the root of the archive. Do not include any directories in the archive. The file path given in the instruction element as its value must be relative to the package.xml file. Attributes # application # The application attribute determines to which application the installed acp templates belong and thus in which directory the templates are installed. The value of the application attribute has to be the abbreviation of an installed application. If no application attribute is given, the following rules are applied: If the package installing the acp templates is an application, then the templates will be installed in this application's directory. If the package installing the acp templates is no application, then the templates will be installed in WoltLab Suite Core's directory. Example in package.xml # 1 2 3 4 5 6 7 <instruction type= \"acpTemplate\" /> <!-- is the same as --> <instruction type= \"acpTemplate\" > acptemplates.tar </instruction> <!-- if an application \"com.woltlab.example\" is being installed, the following lines are equivalent --> <instruction type= \"acpTemplate\" /> <instruction type= \"acpTemplate\" application= \"example\" />","title":"acpTemplate"},{"location":"package/pip/acp-template/#acp-template-installation-plugin","text":"Add templates for acp pages and forms by providing an archive containing the template files. You cannot overwrite acp templates provided by other packages.","title":"ACP Template Installation Plugin"},{"location":"package/pip/acp-template/#archive","text":"The acpTemplate package installation plugins expects a .tar (recommended) or .tar.gz archive. The templates must all be in the root of the archive. Do not include any directories in the archive. The file path given in the instruction element as its value must be relative to the package.xml file.","title":"Archive"},{"location":"package/pip/acp-template/#attributes","text":"","title":"Attributes"},{"location":"package/pip/acp-template/#application","text":"The application attribute determines to which application the installed acp templates belong and thus in which directory the templates are installed. The value of the application attribute has to be the abbreviation of an installed application. If no application attribute is given, the following rules are applied: If the package installing the acp templates is an application, then the templates will be installed in this application's directory. If the package installing the acp templates is no application, then the templates will be installed in WoltLab Suite Core's directory.","title":"application"},{"location":"package/pip/acp-template/#example-in-packagexml","text":"1 2 3 4 5 6 7 <instruction type= \"acpTemplate\" /> <!-- is the same as --> <instruction type= \"acpTemplate\" > acptemplates.tar </instruction> <!-- if an application \"com.woltlab.example\" is being installed, the following lines are equivalent --> <instruction type= \"acpTemplate\" /> <instruction type= \"acpTemplate\" application= \"example\" />","title":"Example in package.xml"},{"location":"package/pip/bbcode/","text":"BBCode Package Installation Plugin # Registers new BBCodes. Components # Each bbcode is described as an <bbcode> element with the mandatory attribute name . The name attribute must contain alphanumeric characters only and is exposed to the user. <htmlopen> # Optional: Must not be provided if the BBCode is being processed a PHP class ( <classname> ). The contents of this tag are literally copied into the opening tag of the bbcode. <htmlclose> # Optional: Must not be provided if <htmlopen> is not given. Must match the <htmlopen> tag. Do not provide for self-closing tags. <classname> # The name of the class providing the bbcode output, the class has to implement the wcf\\system\\bbcode\\IBBCode interface. BBCodes can be statically converted to HTML during input processing using a wcf\\system\\html\\metacode\\converter\\*MetaConverter class. This class does not need to be registered. <wysiwygicon> # Optional Name of the Font Awesome icon class or path to a gif , jpg , jpeg , png , or svg image (placed inside the icon/ directory) to show in the editor toolbar. <buttonlabel> # Optional: Must be provided if an icon is given. Explanatory text to show when hovering the icon. <sourcecode> # Do not set this to 1 if you don't specify a PHP class for processing. You must perform XSS sanitizing yourself! If set to 1 contents of this BBCode will not be interpreted, but literally passed through instead. <isBlockElement> # Set to 1 if the output of this BBCode is a HTML block element (according to the HTML specification). <attributes> # Each bbcode is described as an <attribute> element with the mandatory attribute name . The name attribute is a 0-indexed integer. <html> # Optional: Must not be provided if the BBCode is being processed a PHP class ( <classname> ). The contents of this tag are copied into the opening tag of the bbcode. %s is replaced by the attribute value. <validationpattern> # Optional Defines a regular expression that is used to validate the value of the attribute. <required> # Optional Specifies whether this attribute must be provided. <usetext> # Optional Should only be set to 1 for the attribute with name 0 . Specifies whether the text content of the BBCode should become this attribute's value. Example # bbcode.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/bbcode.xsd\" > <import> <bbcode name= \"foo\" > <classname> wcf\\system\\bbcode\\FooBBCode </classname> <attributes> <attribute name= \"0\" > <validationpattern> ^\\d+$ </validationpattern> <required> 1 </required> </attribute> </attributes> </bbcode> <bbcode name= \"example\" > <htmlopen> div </htmlopen> <htmlclose> div </htmlclose> <isBlockElement> 1 </isBlockElement> <wysiwygicon> fa-bath </wysiwygicon> <buttonlabel> wcf.editor.button.example </buttonlabel> </bbcode> </import> </data>","title":"bbcode"},{"location":"package/pip/bbcode/#bbcode-package-installation-plugin","text":"Registers new BBCodes.","title":"BBCode Package Installation Plugin"},{"location":"package/pip/bbcode/#components","text":"Each bbcode is described as an <bbcode> element with the mandatory attribute name . The name attribute must contain alphanumeric characters only and is exposed to the user.","title":"Components"},{"location":"package/pip/bbcode/#htmlopen","text":"Optional: Must not be provided if the BBCode is being processed a PHP class ( <classname> ). The contents of this tag are literally copied into the opening tag of the bbcode.","title":"<htmlopen>"},{"location":"package/pip/bbcode/#htmlclose","text":"Optional: Must not be provided if <htmlopen> is not given. Must match the <htmlopen> tag. Do not provide for self-closing tags.","title":"<htmlclose>"},{"location":"package/pip/bbcode/#classname","text":"The name of the class providing the bbcode output, the class has to implement the wcf\\system\\bbcode\\IBBCode interface. BBCodes can be statically converted to HTML during input processing using a wcf\\system\\html\\metacode\\converter\\*MetaConverter class. This class does not need to be registered.","title":"<classname>"},{"location":"package/pip/bbcode/#wysiwygicon","text":"Optional Name of the Font Awesome icon class or path to a gif , jpg , jpeg , png , or svg image (placed inside the icon/ directory) to show in the editor toolbar.","title":"<wysiwygicon>"},{"location":"package/pip/bbcode/#buttonlabel","text":"Optional: Must be provided if an icon is given. Explanatory text to show when hovering the icon.","title":"<buttonlabel>"},{"location":"package/pip/bbcode/#sourcecode","text":"Do not set this to 1 if you don't specify a PHP class for processing. You must perform XSS sanitizing yourself! If set to 1 contents of this BBCode will not be interpreted, but literally passed through instead.","title":"<sourcecode>"},{"location":"package/pip/bbcode/#isblockelement","text":"Set to 1 if the output of this BBCode is a HTML block element (according to the HTML specification).","title":"<isBlockElement>"},{"location":"package/pip/bbcode/#attributes","text":"Each bbcode is described as an <attribute> element with the mandatory attribute name . The name attribute is a 0-indexed integer.","title":"<attributes>"},{"location":"package/pip/bbcode/#html","text":"Optional: Must not be provided if the BBCode is being processed a PHP class ( <classname> ). The contents of this tag are copied into the opening tag of the bbcode. %s is replaced by the attribute value.","title":"<html>"},{"location":"package/pip/bbcode/#validationpattern","text":"Optional Defines a regular expression that is used to validate the value of the attribute.","title":"<validationpattern>"},{"location":"package/pip/bbcode/#required","text":"Optional Specifies whether this attribute must be provided.","title":"<required>"},{"location":"package/pip/bbcode/#usetext","text":"Optional Should only be set to 1 for the attribute with name 0 . Specifies whether the text content of the BBCode should become this attribute's value.","title":"<usetext>"},{"location":"package/pip/bbcode/#example","text":"bbcode.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/bbcode.xsd\" > <import> <bbcode name= \"foo\" > <classname> wcf\\system\\bbcode\\FooBBCode </classname> <attributes> <attribute name= \"0\" > <validationpattern> ^\\d+$ </validationpattern> <required> 1 </required> </attribute> </attributes> </bbcode> <bbcode name= \"example\" > <htmlopen> div </htmlopen> <htmlclose> div </htmlclose> <isBlockElement> 1 </isBlockElement> <wysiwygicon> fa-bath </wysiwygicon> <buttonlabel> wcf.editor.button.example </buttonlabel> </bbcode> </import> </data>","title":"Example"},{"location":"package/pip/box/","text":"Box Package Installation Plugin # Deploy and manage boxes that can be placed anywhere on the site, they come in two flavors: system and content-based. Components # Each item is described as a <box> element with the mandatory attribute name that should follow the naming pattern <packageIdentifier>.<BoxName> , e.g. com.woltlab.wcf.RecentActivity . <name> # The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <name> elements. <boxType> # system # The special system type is reserved for boxes that pull their properties and content from a registered PHP class. Requires the <objectType> element. html , text or tpl # Provide arbitrary content, requires the <content> element. <objectType> # Required for boxes with boxType = system , must be registered through the objectType PIP for the definition com.woltlab.wcf.boxController . <position> # The default display position of this box, can be any of the following: bottom contentBottom contentTop footer footerBoxes headerBoxes hero sidebarLeft sidebarRight top Placeholder Positions # <showHeader> # Setting this to 0 will suppress display of the box title, useful for boxes containing advertisements or similar. Defaults to 1 . <visibleEverywhere> # Controls the display on all pages ( 1 ) or none ( 0 ), can be used in conjunction with <visibilityExceptions> . <visibilityExceptions> # Inverts the <visibleEverywhere> setting for the listed pages only. <cssClassName> # Provide a custom CSS class name that is added to the menu container, allowing further customization of the menu's appearance. <content> # The language attribute is required and should specify the ISO-639-1 language code. <title> # The title element is required and controls the box title shown to the end users. <content> # The content that should be used to populate the box, only used and required if the boxType equals text , html and tpl . Example # box.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/box.xsd\" > <import> <box identifier= \"com.woltlab.wcf.RecentActivity\" > <name language= \"de\" > Letzte Aktivit\u00e4ten </name> <name language= \"en\" > Recent Activities </name> <boxType> system </boxType> <objectType> com.woltlab.wcf.recentActivityList </objectType> <position> contentBottom </position> <showHeader> 0 </showHeader> <visibleEverywhere> 0 </visibleEverywhere> <visibilityExceptions> <page> com.woltlab.wcf.Dashboard </page> </visibilityExceptions> <limit> 10 </limit> <content language= \"de\" > <title> Letzte Aktivit\u00e4ten </title> </content> <content language= \"en\" > <title> Recent Activities </title> </content> </box> </import> <delete> <box identifier= \"com.woltlab.wcf.RecentActivity\" /> </delete> </data>","title":"box"},{"location":"package/pip/box/#box-package-installation-plugin","text":"Deploy and manage boxes that can be placed anywhere on the site, they come in two flavors: system and content-based.","title":"Box Package Installation Plugin"},{"location":"package/pip/box/#components","text":"Each item is described as a <box> element with the mandatory attribute name that should follow the naming pattern <packageIdentifier>.<BoxName> , e.g. com.woltlab.wcf.RecentActivity .","title":"Components"},{"location":"package/pip/box/#name","text":"The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <name> elements.","title":"<name>"},{"location":"package/pip/box/#boxtype","text":"","title":"<boxType>"},{"location":"package/pip/box/#system","text":"The special system type is reserved for boxes that pull their properties and content from a registered PHP class. Requires the <objectType> element.","title":"system"},{"location":"package/pip/box/#html-text-or-tpl","text":"Provide arbitrary content, requires the <content> element.","title":"html, text or tpl"},{"location":"package/pip/box/#objecttype","text":"Required for boxes with boxType = system , must be registered through the objectType PIP for the definition com.woltlab.wcf.boxController .","title":"<objectType>"},{"location":"package/pip/box/#position","text":"The default display position of this box, can be any of the following: bottom contentBottom contentTop footer footerBoxes headerBoxes hero sidebarLeft sidebarRight top","title":"<position>"},{"location":"package/pip/box/#placeholder-positions","text":"","title":"Placeholder Positions"},{"location":"package/pip/box/#showheader","text":"Setting this to 0 will suppress display of the box title, useful for boxes containing advertisements or similar. Defaults to 1 .","title":"<showHeader>"},{"location":"package/pip/box/#visibleeverywhere","text":"Controls the display on all pages ( 1 ) or none ( 0 ), can be used in conjunction with <visibilityExceptions> .","title":"<visibleEverywhere>"},{"location":"package/pip/box/#visibilityexceptions","text":"Inverts the <visibleEverywhere> setting for the listed pages only.","title":"<visibilityExceptions>"},{"location":"package/pip/box/#cssclassname","text":"Provide a custom CSS class name that is added to the menu container, allowing further customization of the menu's appearance.","title":"<cssClassName>"},{"location":"package/pip/box/#content","text":"The language attribute is required and should specify the ISO-639-1 language code.","title":"<content>"},{"location":"package/pip/box/#title","text":"The title element is required and controls the box title shown to the end users.","title":"<title>"},{"location":"package/pip/box/#content_1","text":"The content that should be used to populate the box, only used and required if the boxType equals text , html and tpl .","title":"<content>"},{"location":"package/pip/box/#example","text":"box.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/box.xsd\" > <import> <box identifier= \"com.woltlab.wcf.RecentActivity\" > <name language= \"de\" > Letzte Aktivit\u00e4ten </name> <name language= \"en\" > Recent Activities </name> <boxType> system </boxType> <objectType> com.woltlab.wcf.recentActivityList </objectType> <position> contentBottom </position> <showHeader> 0 </showHeader> <visibleEverywhere> 0 </visibleEverywhere> <visibilityExceptions> <page> com.woltlab.wcf.Dashboard </page> </visibilityExceptions> <limit> 10 </limit> <content language= \"de\" > <title> Letzte Aktivit\u00e4ten </title> </content> <content language= \"en\" > <title> Recent Activities </title> </content> </box> </import> <delete> <box identifier= \"com.woltlab.wcf.RecentActivity\" /> </delete> </data>","title":"Example"},{"location":"package/pip/clipboard-action/","text":"Clipboard Action Package Installation Plugin # Registers clipboard actions. Components # Each clipboard action is described as an <action> element with the mandatory attribute name . <actionclassname> # The name of the class used by the clipboard API to process the concrete action. The class has to implement the wcf\\system\\clipboard\\action\\IClipboardAction interface, best by extending wcf\\system\\clipboard\\action\\AbstractClipboardAction . <pages> # Element with <page> children whose value contains the class name of the controller of the page on which the clipboard action is available. <showorder> # Optional Determines at which position of the clipboard action list the action is shown. Example # clipboardAction.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/clipboardAction.xsd\" > <import> <action name= \"delete\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 1 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> <action name= \"foo\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 2 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> <action name= \"bar\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 3 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> </import> </data>","title":"clipboardAction"},{"location":"package/pip/clipboard-action/#clipboard-action-package-installation-plugin","text":"Registers clipboard actions.","title":"Clipboard Action Package Installation Plugin"},{"location":"package/pip/clipboard-action/#components","text":"Each clipboard action is described as an <action> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/clipboard-action/#actionclassname","text":"The name of the class used by the clipboard API to process the concrete action. The class has to implement the wcf\\system\\clipboard\\action\\IClipboardAction interface, best by extending wcf\\system\\clipboard\\action\\AbstractClipboardAction .","title":"<actionclassname>"},{"location":"package/pip/clipboard-action/#pages","text":"Element with <page> children whose value contains the class name of the controller of the page on which the clipboard action is available.","title":"<pages>"},{"location":"package/pip/clipboard-action/#showorder","text":"Optional Determines at which position of the clipboard action list the action is shown.","title":"<showorder>"},{"location":"package/pip/clipboard-action/#example","text":"clipboardAction.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/clipboardAction.xsd\" > <import> <action name= \"delete\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 1 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> <action name= \"foo\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 2 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> <action name= \"bar\" > <actionclassname> wcf\\system\\clipboard\\action\\ExampleClipboardAction </actionclassname> <showorder> 3 </showorder> <pages> <page> wcf\\acp\\page\\ExampleListPage </page> </pages> </action> </import> </data>","title":"Example"},{"location":"package/pip/core-object/","text":"Core Object Package Installation Plugin # Registers wcf\\system\\SingletonFactory objects to be accessible in templates. Components # Each item is described as a <coreobject> element with the mandatory element objectname . <objectname> # The fully qualified class name of the class. Example # coreObject.xml 1 2 3 4 5 6 7 8 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/coreObject.xsd\" > <import> <coreobject> <objectname> wcf\\system\\example\\ExampleHandler </objectname> </coreobject> </import> </data> This object can be accessed in templates via $__wcf->getExampleHandler() (in general: the method name begins with get and ends with the unqualified class name).","title":"coreObject"},{"location":"package/pip/core-object/#core-object-package-installation-plugin","text":"Registers wcf\\system\\SingletonFactory objects to be accessible in templates.","title":"Core Object Package Installation Plugin"},{"location":"package/pip/core-object/#components","text":"Each item is described as a <coreobject> element with the mandatory element objectname .","title":"Components"},{"location":"package/pip/core-object/#objectname","text":"The fully qualified class name of the class.","title":"<objectname>"},{"location":"package/pip/core-object/#example","text":"coreObject.xml 1 2 3 4 5 6 7 8 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/coreObject.xsd\" > <import> <coreobject> <objectname> wcf\\system\\example\\ExampleHandler </objectname> </coreobject> </import> </data> This object can be accessed in templates via $__wcf->getExampleHandler() (in general: the method name begins with get and ends with the unqualified class name).","title":"Example"},{"location":"package/pip/cronjob/","text":"Cronjob Package Installation Plugin # Registers new cronjobs. The cronjob schedular works similar to the cron(8) daemon, which might not available to web applications on regular webspaces. The main difference is that WoltLab Suite\u2019s cronjobs do not guarantee execution at the specified points in time: WoltLab Suite\u2019s cronjobs are triggered by regular visitors in an AJAX request, once the next execution point lies in the past. Components # Each cronjob is described as an <cronjob> element with the mandatory attribute name . <classname> # The name of the class providing the cronjob's behaviour, the class has to implement the wcf\\system\\cronjob\\ICronjob interface. <description> # The language attribute is optional and should specify the ISO-639-1 language code. Provides a human readable description for the administrator. <start*> # All of the five startMinute , startHour , startDom (Day Of Month), startMonth , startDow (Day Of Week) are required. They correspond to the fields in crontab(5) of a cron daemon and accept the same syntax. <canbeedited> # Controls whether the administrator may edit the fields of the cronjob. Defaults to 1 . <canbedisabled> # Controls whether the administrator may disable the cronjob. Defaults to 1 . <isdisabled> # Controls whether the cronjob is disabled by default. Defaults to 0 . <options> # The options element can contain a comma-separated list of options of which at least one needs to be enabled for the template listener to be executed. Example # cronjob.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/cronjob.xsd\" > <import> <cronjob name= \"com.example.package.example\" > <classname> wcf\\system\\cronjob\\ExampleCronjob </classname> <description> Serves as an example </description> <description language= \"de\" > Stellt ein Beispiel dar </description> <startminute> 0 </startminute> <starthour> 2 </starthour> <startdom> */2 </startdom> <startmonth> * </startmonth> <startdow> * </startdow> <canbeedited> 1 </canbeedited> <canbedisabled> 1 </canbedisabled> </cronjob> </import> </data>","title":"cronjob"},{"location":"package/pip/cronjob/#cronjob-package-installation-plugin","text":"Registers new cronjobs. The cronjob schedular works similar to the cron(8) daemon, which might not available to web applications on regular webspaces. The main difference is that WoltLab Suite\u2019s cronjobs do not guarantee execution at the specified points in time: WoltLab Suite\u2019s cronjobs are triggered by regular visitors in an AJAX request, once the next execution point lies in the past.","title":"Cronjob Package Installation Plugin"},{"location":"package/pip/cronjob/#components","text":"Each cronjob is described as an <cronjob> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/cronjob/#classname","text":"The name of the class providing the cronjob's behaviour, the class has to implement the wcf\\system\\cronjob\\ICronjob interface.","title":"<classname>"},{"location":"package/pip/cronjob/#description","text":"The language attribute is optional and should specify the ISO-639-1 language code. Provides a human readable description for the administrator.","title":"<description>"},{"location":"package/pip/cronjob/#start","text":"All of the five startMinute , startHour , startDom (Day Of Month), startMonth , startDow (Day Of Week) are required. They correspond to the fields in crontab(5) of a cron daemon and accept the same syntax.","title":"<start*>"},{"location":"package/pip/cronjob/#canbeedited","text":"Controls whether the administrator may edit the fields of the cronjob. Defaults to 1 .","title":"<canbeedited>"},{"location":"package/pip/cronjob/#canbedisabled","text":"Controls whether the administrator may disable the cronjob. Defaults to 1 .","title":"<canbedisabled>"},{"location":"package/pip/cronjob/#isdisabled","text":"Controls whether the cronjob is disabled by default. Defaults to 0 .","title":"<isdisabled>"},{"location":"package/pip/cronjob/#options","text":"The options element can contain a comma-separated list of options of which at least one needs to be enabled for the template listener to be executed.","title":"<options>"},{"location":"package/pip/cronjob/#example","text":"cronjob.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/cronjob.xsd\" > <import> <cronjob name= \"com.example.package.example\" > <classname> wcf\\system\\cronjob\\ExampleCronjob </classname> <description> Serves as an example </description> <description language= \"de\" > Stellt ein Beispiel dar </description> <startminute> 0 </startminute> <starthour> 2 </starthour> <startdom> */2 </startdom> <startmonth> * </startmonth> <startdow> * </startdow> <canbeedited> 1 </canbeedited> <canbedisabled> 1 </canbedisabled> </cronjob> </import> </data>","title":"Example"},{"location":"package/pip/database/","text":"Database Package Installation Plugin # Available since WoltLab Suite 5.4. Update the database layout using the PHP API . You must install the PHP script through the file package installation plugin . The installation will attempt to delete the script after successful execution. Attributes # application # The application attribute must have the same value as the application attribute of the file package installation plugin instruction so that the correct file in the intended application directory is executed. For further information about the application attribute, refer to its documentation on the acpTemplate package installation plugin page . Expected value # The database -PIP expects a relative path to a .php file that returns an array of DatabaseTable objects. Naming convention # The PHP script is deployed by using the file package installation plugin . To prevent it from colliding with other install script (remember: You cannot overwrite files created by another plugin), we highly recommend to make use of these naming conventions: Installation: acp/database/install_<package>.php (example: acp/database/install_com.woltlab.wbb.php ) Update: acp/database/update_<package>_<targetVersion>.php (example: acp/database/update_com.woltlab.wbb_5.4.1.php ) <targetVersion> equals the version number of the current package being installed. If you're updating from 1.0.0 to 1.0.1 , <targetVersion> should read 1.0.1 . If you run multiple update scripts, you can append additional information in the filename. Execution environment # The script is included using include() within DatabasePackageInstallationPlugin::updateDatabase() .","title":"database"},{"location":"package/pip/database/#database-package-installation-plugin","text":"Available since WoltLab Suite 5.4. Update the database layout using the PHP API . You must install the PHP script through the file package installation plugin . The installation will attempt to delete the script after successful execution.","title":"Database Package Installation Plugin"},{"location":"package/pip/database/#attributes","text":"","title":"Attributes"},{"location":"package/pip/database/#application","text":"The application attribute must have the same value as the application attribute of the file package installation plugin instruction so that the correct file in the intended application directory is executed. For further information about the application attribute, refer to its documentation on the acpTemplate package installation plugin page .","title":"application"},{"location":"package/pip/database/#expected-value","text":"The database -PIP expects a relative path to a .php file that returns an array of DatabaseTable objects.","title":"Expected value"},{"location":"package/pip/database/#naming-convention","text":"The PHP script is deployed by using the file package installation plugin . To prevent it from colliding with other install script (remember: You cannot overwrite files created by another plugin), we highly recommend to make use of these naming conventions: Installation: acp/database/install_<package>.php (example: acp/database/install_com.woltlab.wbb.php ) Update: acp/database/update_<package>_<targetVersion>.php (example: acp/database/update_com.woltlab.wbb_5.4.1.php ) <targetVersion> equals the version number of the current package being installed. If you're updating from 1.0.0 to 1.0.1 , <targetVersion> should read 1.0.1 . If you run multiple update scripts, you can append additional information in the filename.","title":"Naming convention"},{"location":"package/pip/database/#execution-environment","text":"The script is included using include() within DatabasePackageInstallationPlugin::updateDatabase() .","title":"Execution environment"},{"location":"package/pip/event-listener/","text":"Event Listener Package Installation Plugin # Registers event listeners. An explanation of events and event listeners can be found here . Components # Each event listener is described as an <eventlistener> element with a name attribute. As the name attribute has only be introduced with WSC 3.0, it is not yet mandatory to allow backwards compatibility. If name is not given, the system automatically sets the name based on the id of the event listener in the database. <eventclassname> # The event class name is the name of the class in which the event is fired. <eventname> # The event name is the name given when the event is fired to identify different events within the same class. You can either give a single event name or a comma-separated list of event names in which case the event listener listens to all of the listed events. Since the introduction of the new event system with version 5.5 , the event name is optional and defaults to :default . <listenerclassname> # The listener class name is the name of the class which is triggered if the relevant event is fired. The PHP class has to implement the wcf\\system\\event\\listener\\IParameterizedEventListener interface. Legacy event listeners are only required to implement the deprecated wcf\\system\\event\\IEventListener interface. When writing new code or update existing code, you should always implement the wcf\\system\\event\\listener\\IParameterizedEventListener interface! <inherit> # The inherit value can either be 0 (default value if the element is omitted) or 1 and determines if the event listener is also triggered for child classes of the given event class name. This is the case if 1 is used as the value. <environment> # The value of the environment element must be one of user , admin or all and defaults to user if no value is given. The value determines if the event listener will be executed in the frontend ( user ), the backend ( admin ) or both ( all ). <nice> # The nice value element can contain an integer value out of the interval [-128,127] with 0 being the default value if the element is omitted. The nice value determines the execution order of event listeners. Event listeners with smaller nice values are executed first. If the nice value of two event listeners is equal, they are sorted by the listener class name. If you pass a value out of the mentioned interval, the value will be adjusted to the closest value in the interval. <options> # The options element can contain a comma-separated list of options of which at least one needs to be enabled for the event listener to be executed. <permissions> # The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the event listener to be executed. Example # eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/eventListener.xsd\" > <import> <eventlistener name= \"inheritedAdminExample\" > <eventclassname> wcf\\acp\\form\\UserAddForm </eventclassname> <eventname> assignVariables,readFormParameters,save,validate </eventname> <listenerclassname> wcf\\system\\event\\listener\\InheritedAdminExampleListener </listenerclassname> <inherit> 1 </inherit> <environment> admin </environment> </eventlistener> <eventlistener name= \"nonInheritedUserExample\" > <eventclassname> wcf\\form\\SettingsForm </eventclassname> <eventname> assignVariables </eventname> <listenerclassname> wcf\\system\\event\\listener\\NonInheritedUserExampleListener </listenerclassname> </eventlistener> </import> <delete> <eventlistener name= \"oldEventListenerName\" /> </delete> </data>","title":"eventListener"},{"location":"package/pip/event-listener/#event-listener-package-installation-plugin","text":"Registers event listeners. An explanation of events and event listeners can be found here .","title":"Event Listener Package Installation Plugin"},{"location":"package/pip/event-listener/#components","text":"Each event listener is described as an <eventlistener> element with a name attribute. As the name attribute has only be introduced with WSC 3.0, it is not yet mandatory to allow backwards compatibility. If name is not given, the system automatically sets the name based on the id of the event listener in the database.","title":"Components"},{"location":"package/pip/event-listener/#eventclassname","text":"The event class name is the name of the class in which the event is fired.","title":"<eventclassname>"},{"location":"package/pip/event-listener/#eventname","text":"The event name is the name given when the event is fired to identify different events within the same class. You can either give a single event name or a comma-separated list of event names in which case the event listener listens to all of the listed events. Since the introduction of the new event system with version 5.5 , the event name is optional and defaults to :default .","title":"<eventname>"},{"location":"package/pip/event-listener/#listenerclassname","text":"The listener class name is the name of the class which is triggered if the relevant event is fired. The PHP class has to implement the wcf\\system\\event\\listener\\IParameterizedEventListener interface. Legacy event listeners are only required to implement the deprecated wcf\\system\\event\\IEventListener interface. When writing new code or update existing code, you should always implement the wcf\\system\\event\\listener\\IParameterizedEventListener interface!","title":"<listenerclassname>"},{"location":"package/pip/event-listener/#inherit","text":"The inherit value can either be 0 (default value if the element is omitted) or 1 and determines if the event listener is also triggered for child classes of the given event class name. This is the case if 1 is used as the value.","title":"<inherit>"},{"location":"package/pip/event-listener/#environment","text":"The value of the environment element must be one of user , admin or all and defaults to user if no value is given. The value determines if the event listener will be executed in the frontend ( user ), the backend ( admin ) or both ( all ).","title":"<environment>"},{"location":"package/pip/event-listener/#nice","text":"The nice value element can contain an integer value out of the interval [-128,127] with 0 being the default value if the element is omitted. The nice value determines the execution order of event listeners. Event listeners with smaller nice values are executed first. If the nice value of two event listeners is equal, they are sorted by the listener class name. If you pass a value out of the mentioned interval, the value will be adjusted to the closest value in the interval.","title":"<nice>"},{"location":"package/pip/event-listener/#options","text":"The options element can contain a comma-separated list of options of which at least one needs to be enabled for the event listener to be executed.","title":"<options>"},{"location":"package/pip/event-listener/#permissions","text":"The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the event listener to be executed.","title":"<permissions>"},{"location":"package/pip/event-listener/#example","text":"eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/eventListener.xsd\" > <import> <eventlistener name= \"inheritedAdminExample\" > <eventclassname> wcf\\acp\\form\\UserAddForm </eventclassname> <eventname> assignVariables,readFormParameters,save,validate </eventname> <listenerclassname> wcf\\system\\event\\listener\\InheritedAdminExampleListener </listenerclassname> <inherit> 1 </inherit> <environment> admin </environment> </eventlistener> <eventlistener name= \"nonInheritedUserExample\" > <eventclassname> wcf\\form\\SettingsForm </eventclassname> <eventname> assignVariables </eventname> <listenerclassname> wcf\\system\\event\\listener\\NonInheritedUserExampleListener </listenerclassname> </eventlistener> </import> <delete> <eventlistener name= \"oldEventListenerName\" /> </delete> </data>","title":"Example"},{"location":"package/pip/file-delete/","text":"File Delete Package Installation Plugin # Available since WoltLab Suite 5.5. Deletes files installed with the file package installation plugin. You cannot delete files provided by other packages. Components # Each item is described as a <file> element with an optional application , which behaves like it does for acp templates . The file path is relative to the installation of the app to which the file belongs. Example # fileDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/fileDelete.xsd\" > <delete> <file> path/file.ext </file> <file application= \"app\" > lib/data/foo/Fou.class.php </file> </delete> </data>","title":"fileDelete"},{"location":"package/pip/file-delete/#file-delete-package-installation-plugin","text":"Available since WoltLab Suite 5.5. Deletes files installed with the file package installation plugin. You cannot delete files provided by other packages.","title":"File Delete Package Installation Plugin"},{"location":"package/pip/file-delete/#components","text":"Each item is described as a <file> element with an optional application , which behaves like it does for acp templates . The file path is relative to the installation of the app to which the file belongs.","title":"Components"},{"location":"package/pip/file-delete/#example","text":"fileDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/fileDelete.xsd\" > <delete> <file> path/file.ext </file> <file application= \"app\" > lib/data/foo/Fou.class.php </file> </delete> </data>","title":"Example"},{"location":"package/pip/file/","text":"File Package Installation Plugin # Adds any type of files with the exception of templates. You cannot overwrite files provided by other packages. The application attribute behaves like it does for acp templates . Archive # The acpTemplate package installation plugins expects a .tar (recommended) or .tar.gz archive. The file path given in the instruction element as its value must be relative to the package.xml file. Example in package.xml # 1 2 3 4 5 6 7 8 9 10 <instruction type= \"file\" /> <!-- is the same as --> <instruction type= \"file\" > files.tar </instruction> <!-- if an application \"com.woltlab.example\" is being installed, the following lines are equivalent --> <instruction type= \"file\" /> <instruction type= \"file\" application= \"example\" /> <!-- if the same application wants to install additional files, in WoltLab Suite Core's directory: --> <instruction type= \"file\" application= \"wcf\" > files_wcf.tar </instruction>","title":"file"},{"location":"package/pip/file/#file-package-installation-plugin","text":"Adds any type of files with the exception of templates. You cannot overwrite files provided by other packages. The application attribute behaves like it does for acp templates .","title":"File Package Installation Plugin"},{"location":"package/pip/file/#archive","text":"The acpTemplate package installation plugins expects a .tar (recommended) or .tar.gz archive. The file path given in the instruction element as its value must be relative to the package.xml file.","title":"Archive"},{"location":"package/pip/file/#example-in-packagexml","text":"1 2 3 4 5 6 7 8 9 10 <instruction type= \"file\" /> <!-- is the same as --> <instruction type= \"file\" > files.tar </instruction> <!-- if an application \"com.woltlab.example\" is being installed, the following lines are equivalent --> <instruction type= \"file\" /> <instruction type= \"file\" application= \"example\" /> <!-- if the same application wants to install additional files, in WoltLab Suite Core's directory: --> <instruction type= \"file\" application= \"wcf\" > files_wcf.tar </instruction>","title":"Example in package.xml"},{"location":"package/pip/language/","text":"Language Package Installation Plugin # Registers new language items. Components # The languagecode attribute is required and should specify the ISO-639-1 language code. The top level <language> node must contain a languagecode attribute. <category> # Each category must contain a name attribute containing two or three components consisting of alphanumeric character only, separated by a single full stop ( . , U+002E). <item> # Each language item must contain a name attribute containing at least three components consisting of alphanumeric character only, separated by a single full stop ( . , U+002E). The name of the parent <category> node followed by a full stop must be a prefix of the <item> \u2019s name . Wrap the text content inside a CDATA to avoid escaping of special characters. Do not use the {lang} tag inside a language item. The text content of the <item> node is the value of the language item. Language items that are not in the wcf.global category support template scripting. Example # Prior to version 5.5, there was no support for deleting language items and the category elements had to be placed directly as children of the language element, see the migration guide to version 5.5 . language/en.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/language.xsd\" languagecode= \"en\" > <import> <category name= \"wcf.example\" > <item name= \"wcf.example.foo\" > <![CDATA[<strong>Look!</strong>]]> </item> </category> </import> <delete> <item name= \"wcf.example.obsolete\" /> </delete> </language>","title":"language"},{"location":"package/pip/language/#language-package-installation-plugin","text":"Registers new language items.","title":"Language Package Installation Plugin"},{"location":"package/pip/language/#components","text":"The languagecode attribute is required and should specify the ISO-639-1 language code. The top level <language> node must contain a languagecode attribute.","title":"Components"},{"location":"package/pip/language/#category","text":"Each category must contain a name attribute containing two or three components consisting of alphanumeric character only, separated by a single full stop ( . , U+002E).","title":"<category>"},{"location":"package/pip/language/#item","text":"Each language item must contain a name attribute containing at least three components consisting of alphanumeric character only, separated by a single full stop ( . , U+002E). The name of the parent <category> node followed by a full stop must be a prefix of the <item> \u2019s name . Wrap the text content inside a CDATA to avoid escaping of special characters. Do not use the {lang} tag inside a language item. The text content of the <item> node is the value of the language item. Language items that are not in the wcf.global category support template scripting.","title":"<item>"},{"location":"package/pip/language/#example","text":"Prior to version 5.5, there was no support for deleting language items and the category elements had to be placed directly as children of the language element, see the migration guide to version 5.5 . language/en.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <language xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/language.xsd\" languagecode= \"en\" > <import> <category name= \"wcf.example\" > <item name= \"wcf.example.foo\" > <![CDATA[<strong>Look!</strong>]]> </item> </category> </import> <delete> <item name= \"wcf.example.obsolete\" /> </delete> </language>","title":"Example"},{"location":"package/pip/media-provider/","text":"Media Provider Package Installation Plugin # Media providers are responsible to detect and convert links to a 3rd party service inside messages. Components # Each item is described as a <provider> element with the mandatory attribute name that should equal the lower-cased provider name. If a provider provides multiple components that are (largely) unrelated to each other, it is recommended to use a dash to separate the name and the component, e. g. youtube-playlist . <title> # The title is displayed in the administration control panel and is only used there, the value is neither localizable nor is it ever exposed to regular users. <regex> # The regular expression used to identify links to this provider, it must not contain anchors or delimiters. It is strongly recommended to capture the primary object id using the (?P<ID>...) group. <className> # <className> and <html> are mutually exclusive. PHP-Callback-Class that is invoked to process the matched link in case that additional logic must be applied that cannot be handled through a simple replacement as defined by the <html> element. The callback-class must implement the interface \\wcf\\system\\bbcode\\media\\provider\\IBBCodeMediaProvider . <html> # <className> and <html> are mutually exclusive. Replacement HTML that gets populated using the captured matches in <regex> , variables are accessed as {$VariableName} . For example, the capture group (?P<ID>...) is accessed using {$ID} . Example # mediaProvider.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/mediaProvider.xsd\" > <import> <provider name= \"youtube\" > <title> YouTube </title> <regex> <![CDATA[https?://(?:.+?\\.)?youtu(?:\\.be/|be\\.com/(?:#/)?watch\\?(?:.*?&)?v=)(?P<ID>[a-zA-Z0-9_-]+)(?:(?:\\?|&)t=(?P<start>[0-9hms]+)$)?]]> </regex> <!-- advanced PHP callback --> <className> <![CDATA[wcf\\system\\bbcode\\media\\provider\\YouTubeBBCodeMediaProvider]]> </className> </provider> <provider name= \"youtube-playlist\" > <title> YouTube Playlist </title> <regex> <![CDATA[https?://(?:.+?\\.)?youtu(?:\\.be/|be\\.com/)playlist\\?(?:.*?&)?list=(?P<ID>[a-zA-Z0-9_-]+)]]> </regex> <!-- uses a simple HTML replacement --> <html> <![CDATA[<div class=\"videoContainer\"><iframe src=\"https://www.youtube.com/embed/videoseries?list={$ID}\" allowfullscreen></iframe></div>]]> </html> </provider> </import> <delete> <provider name= \"example\" /> </delete> </data>","title":"mediaProvider"},{"location":"package/pip/media-provider/#media-provider-package-installation-plugin","text":"Media providers are responsible to detect and convert links to a 3rd party service inside messages.","title":"Media Provider Package Installation Plugin"},{"location":"package/pip/media-provider/#components","text":"Each item is described as a <provider> element with the mandatory attribute name that should equal the lower-cased provider name. If a provider provides multiple components that are (largely) unrelated to each other, it is recommended to use a dash to separate the name and the component, e. g. youtube-playlist .","title":"Components"},{"location":"package/pip/media-provider/#title","text":"The title is displayed in the administration control panel and is only used there, the value is neither localizable nor is it ever exposed to regular users.","title":"<title>"},{"location":"package/pip/media-provider/#regex","text":"The regular expression used to identify links to this provider, it must not contain anchors or delimiters. It is strongly recommended to capture the primary object id using the (?P<ID>...) group.","title":"<regex>"},{"location":"package/pip/media-provider/#classname","text":"<className> and <html> are mutually exclusive. PHP-Callback-Class that is invoked to process the matched link in case that additional logic must be applied that cannot be handled through a simple replacement as defined by the <html> element. The callback-class must implement the interface \\wcf\\system\\bbcode\\media\\provider\\IBBCodeMediaProvider .","title":"<className>"},{"location":"package/pip/media-provider/#html","text":"<className> and <html> are mutually exclusive. Replacement HTML that gets populated using the captured matches in <regex> , variables are accessed as {$VariableName} . For example, the capture group (?P<ID>...) is accessed using {$ID} .","title":"<html>"},{"location":"package/pip/media-provider/#example","text":"mediaProvider.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/mediaProvider.xsd\" > <import> <provider name= \"youtube\" > <title> YouTube </title> <regex> <![CDATA[https?://(?:.+?\\.)?youtu(?:\\.be/|be\\.com/(?:#/)?watch\\?(?:.*?&)?v=)(?P<ID>[a-zA-Z0-9_-]+)(?:(?:\\?|&)t=(?P<start>[0-9hms]+)$)?]]> </regex> <!-- advanced PHP callback --> <className> <![CDATA[wcf\\system\\bbcode\\media\\provider\\YouTubeBBCodeMediaProvider]]> </className> </provider> <provider name= \"youtube-playlist\" > <title> YouTube Playlist </title> <regex> <![CDATA[https?://(?:.+?\\.)?youtu(?:\\.be/|be\\.com/)playlist\\?(?:.*?&)?list=(?P<ID>[a-zA-Z0-9_-]+)]]> </regex> <!-- uses a simple HTML replacement --> <html> <![CDATA[<div class=\"videoContainer\"><iframe src=\"https://www.youtube.com/embed/videoseries?list={$ID}\" allowfullscreen></iframe></div>]]> </html> </provider> </import> <delete> <provider name= \"example\" /> </delete> </data>","title":"Example"},{"location":"package/pip/menu-item/","text":"Menu Item Package Installation Plugin # Adds menu items to existing menus. Components # Each item is described as an <item> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<PageName> , e.g. com.woltlab.wcf.Dashboard . <menu> # The target menu that the item should be added to, requires the internal identifier set by creating a menu through the menu.xml . <title> # The language attribute is required and should specify the ISO-639-1 language code. The title is displayed as the link title of the menu item and can be fully customized by the administrator, thus is immutable after deployment. Supports multiple <title> elements to provide localized values. <page> # The page that the link should point to, requires the internal identifier set by creating a page through the page.xml . Example # menuItem.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/menuItem.xsd\" > <import> <item identifier= \"com.woltlab.wcf.Dashboard\" > <menu> com.woltlab.wcf.MainMenu </menu> <title language= \"de\" > Dashboard </title> <title language= \"en\" > Dashboard </title> <page> com.woltlab.wcf.Dashboard </page> </item> </import> <delete> <item identifier= \"com.woltlab.wcf.FooterLinks\" /> </delete> </data>","title":"menuItem"},{"location":"package/pip/menu-item/#menu-item-package-installation-plugin","text":"Adds menu items to existing menus.","title":"Menu Item Package Installation Plugin"},{"location":"package/pip/menu-item/#components","text":"Each item is described as an <item> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<PageName> , e.g. com.woltlab.wcf.Dashboard .","title":"Components"},{"location":"package/pip/menu-item/#menu","text":"The target menu that the item should be added to, requires the internal identifier set by creating a menu through the menu.xml .","title":"<menu>"},{"location":"package/pip/menu-item/#title","text":"The language attribute is required and should specify the ISO-639-1 language code. The title is displayed as the link title of the menu item and can be fully customized by the administrator, thus is immutable after deployment. Supports multiple <title> elements to provide localized values.","title":"<title>"},{"location":"package/pip/menu-item/#page","text":"The page that the link should point to, requires the internal identifier set by creating a page through the page.xml .","title":"<page>"},{"location":"package/pip/menu-item/#example","text":"menuItem.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/menuItem.xsd\" > <import> <item identifier= \"com.woltlab.wcf.Dashboard\" > <menu> com.woltlab.wcf.MainMenu </menu> <title language= \"de\" > Dashboard </title> <title language= \"en\" > Dashboard </title> <page> com.woltlab.wcf.Dashboard </page> </item> </import> <delete> <item identifier= \"com.woltlab.wcf.FooterLinks\" /> </delete> </data>","title":"Example"},{"location":"package/pip/menu/","text":"Menu Package Installation Plugin # Deploy and manage menus that can be placed anywhere on the site. Components # Each item is described as a <menu> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<MenuName> , e.g. com.woltlab.wcf.MainMenu . <title> # The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <title> elements. <box> # The following elements of the box PIP are supported, please refer to the documentation to learn more about them: <position> <showHeader> <visibleEverywhere> <visibilityExceptions> cssClassName Example # menu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/menu.xsd\" > <import> <menu identifier= \"com.woltlab.wcf.FooterLinks\" > <title language= \"de\" > Footer-Links </title> <title language= \"en\" > Footer Links </title> <box> <position> footer </position> <cssClassName> boxMenuLinkGroup </cssClassName> <showHeader> 0 </showHeader> <visibleEverywhere> 1 </visibleEverywhere> </box> </menu> </import> <delete> <menu identifier= \"com.woltlab.wcf.FooterLinks\" /> </delete> </data>","title":"menu"},{"location":"package/pip/menu/#menu-package-installation-plugin","text":"Deploy and manage menus that can be placed anywhere on the site.","title":"Menu Package Installation Plugin"},{"location":"package/pip/menu/#components","text":"Each item is described as a <menu> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<MenuName> , e.g. com.woltlab.wcf.MainMenu .","title":"Components"},{"location":"package/pip/menu/#title","text":"The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <title> elements.","title":"<title>"},{"location":"package/pip/menu/#box","text":"The following elements of the box PIP are supported, please refer to the documentation to learn more about them: <position> <showHeader> <visibleEverywhere> <visibilityExceptions> cssClassName","title":"<box>"},{"location":"package/pip/menu/#example","text":"menu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/menu.xsd\" > <import> <menu identifier= \"com.woltlab.wcf.FooterLinks\" > <title language= \"de\" > Footer-Links </title> <title language= \"en\" > Footer Links </title> <box> <position> footer </position> <cssClassName> boxMenuLinkGroup </cssClassName> <showHeader> 0 </showHeader> <visibleEverywhere> 1 </visibleEverywhere> </box> </menu> </import> <delete> <menu identifier= \"com.woltlab.wcf.FooterLinks\" /> </delete> </data>","title":"Example"},{"location":"package/pip/object-type-definition/","text":"Object Type Definition Package Installation Plugin # Registers an object type definition. An object type definition is a blueprint for a certain behaviour that is particularized by objectTypes . As an example: Tags can be attached to different types of content (such as forum posts or gallery images). The bulk of the work is implemented in a generalized fashion, with all the tags stored in a single database table. Certain things, such as permission checking, need to be particularized for the specific type of content, though. Thus tags (or rather \u201ctaggable content\u201d) are registered as an object type definition. Posts are then registered as an object type, implementing the \u201ctaggable content\u201d behaviour. Other types of object type definitions include attachments, likes, polls, subscriptions, or even the category system. Components # Each item is described as a <definition> element with the mandatory child <name> that should follow the naming pattern <packageIdentifier>.<definition> , e.g. com.woltlab.wcf.example . <interfacename> # Optional The name of the PHP interface objectTypes have to implement. Example # objectTypeDefinition.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectTypeDefinition.xsd\" > <import> <definition> <name> com.woltlab.wcf.example </name> <interfacename> wcf\\system\\example\\IExampleObjectType </interfacename> </definition> </import> </data>","title":"objectTypeDefinition"},{"location":"package/pip/object-type-definition/#object-type-definition-package-installation-plugin","text":"Registers an object type definition. An object type definition is a blueprint for a certain behaviour that is particularized by objectTypes . As an example: Tags can be attached to different types of content (such as forum posts or gallery images). The bulk of the work is implemented in a generalized fashion, with all the tags stored in a single database table. Certain things, such as permission checking, need to be particularized for the specific type of content, though. Thus tags (or rather \u201ctaggable content\u201d) are registered as an object type definition. Posts are then registered as an object type, implementing the \u201ctaggable content\u201d behaviour. Other types of object type definitions include attachments, likes, polls, subscriptions, or even the category system.","title":"Object Type Definition Package Installation Plugin"},{"location":"package/pip/object-type-definition/#components","text":"Each item is described as a <definition> element with the mandatory child <name> that should follow the naming pattern <packageIdentifier>.<definition> , e.g. com.woltlab.wcf.example .","title":"Components"},{"location":"package/pip/object-type-definition/#interfacename","text":"Optional The name of the PHP interface objectTypes have to implement.","title":"<interfacename>"},{"location":"package/pip/object-type-definition/#example","text":"objectTypeDefinition.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectTypeDefinition.xsd\" > <import> <definition> <name> com.woltlab.wcf.example </name> <interfacename> wcf\\system\\example\\IExampleObjectType </interfacename> </definition> </import> </data>","title":"Example"},{"location":"package/pip/object-type/","text":"Object Type Package Installation Plugin # Registers an object type. Read about object types in the objectTypeDefinition PIP. Components # Each item is described as a <type> element with the mandatory child <name> that should follow the naming pattern <packageIdentifier>.<definition> , e.g. com.woltlab.wcf.example . <definitionname> # The <name> of the objectTypeDefinition . <classname> # The name of the class providing the object types's behaviour, the class has to implement the <interfacename> interface of the object type definition. <*> # Optional Additional fields may be defined for specific definitions of object types. Refer to the documentation of these for further explanation. Example # objectType.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectType.xsd\" > <import> <type> <name> com.woltlab.wcf.example </name> <definitionname> com.woltlab.wcf.rebuildData </definitionname> <classname> wcf\\system\\worker\\ExampleRebuildWorker </classname> <nicevalue> 130 </nicevalue> </type> </import> </data>","title":"objectType"},{"location":"package/pip/object-type/#object-type-package-installation-plugin","text":"Registers an object type. Read about object types in the objectTypeDefinition PIP.","title":"Object Type Package Installation Plugin"},{"location":"package/pip/object-type/#components","text":"Each item is described as a <type> element with the mandatory child <name> that should follow the naming pattern <packageIdentifier>.<definition> , e.g. com.woltlab.wcf.example .","title":"Components"},{"location":"package/pip/object-type/#definitionname","text":"The <name> of the objectTypeDefinition .","title":"<definitionname>"},{"location":"package/pip/object-type/#classname","text":"The name of the class providing the object types's behaviour, the class has to implement the <interfacename> interface of the object type definition.","title":"<classname>"},{"location":"package/pip/object-type/#_1","text":"Optional Additional fields may be defined for specific definitions of object types. Refer to the documentation of these for further explanation.","title":"<*>"},{"location":"package/pip/object-type/#example","text":"objectType.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectType.xsd\" > <import> <type> <name> com.woltlab.wcf.example </name> <definitionname> com.woltlab.wcf.rebuildData </definitionname> <classname> wcf\\system\\worker\\ExampleRebuildWorker </classname> <nicevalue> 130 </nicevalue> </type> </import> </data>","title":"Example"},{"location":"package/pip/option/","text":"Option Package Installation Plugin # Registers new options. Options allow the administrator to configure the behaviour of installed packages. The specified values are exposed as PHP constants. Category Components # Each category is described as an <category> element with the mandatory attribute name . <parent> # Optional The category\u2019s parent category. <showorder> # Optional Specifies the order of this option within the parent category. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the category to be shown to the administrator. Option Components # Each option is described as an <option> element with the mandatory attribute name . The name is transformed into a PHP constant name by uppercasing it. <categoryname> # The option\u2019s category. <optiontype> # The type of input to be used for this option. Valid types are defined by the wcf\\system\\option\\*OptionType classes. <defaultvalue> # The value that is set after installation of a package. Valid values are defined by the optiontype . <validationpattern> # Optional Defines a regular expression that is used to validate the value of a free form option (such as text ). <showorder> # Optional Specifies the order of this option within the category. <selectoptions> # Optional Defined only for select , multiSelect and radioButton types. Specifies a newline-separated list of selectable values. Each line consists of an internal handle, followed by a colon ( : , U+003A), followed by a language item. The language item is shown to the administrator, the internal handle is what is saved and exposed to the code. <enableoptions> # Optional Defined only for boolean , select and radioButton types. Specifies a comma-separated list of options which should be visually enabled when this option is enabled. A leading exclamation mark ( ! , U+0021) will disable the specified option when this option is enabled. For select and radioButton types the list should be prefixed by the internal selectoptions handle followed by a colon ( : , U+003A). This setting is a visual helper for the administrator only. It does not have an effect on the server side processing of the option. <hidden> # Optional If hidden is set to 1 the option will not be shown to the administrator. It still can be modified programmatically. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the option to be shown to the administrator. <supporti18n> # Optional Specifies whether this option supports localized input. <requirei18n> # Optional Specifies whether this option requires localized input (i.e. the administrator must specify a value for every installed language). <*> # Optional Additional fields may be defined by specific types of options. Refer to the documentation of these for further explanation. Language Items # All relevant language items have to be put into the wcf.acp.option language item category. Categories # If you install a category named example.sub , you have to provide the language item wcf.acp.option.category.example.sub , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.acp.option.category.example.sub.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level. Options # If you install an option named module_example , you have to provide the language item wcf.acp.option.module_example , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.acp.option.module_example.description . Example # option.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/option.xsd\" > <import> <categories> <category name= \"example\" /> <category name= \"example.sub\" > <parent> example </parent> <options> module_example </options> </category> </categories> <options> <option name= \"module_example\" > <categoryname> module.community </categoryname> <optiontype> boolean </optiontype> <defaultvalue> 1 </defaultvalue> </option> <option name= \"example_integer\" > <categoryname> example.sub </categoryname> <optiontype> integer </optiontype> <defaultvalue> 10 </defaultvalue> <minvalue> 5 </minvalue> <maxvalue> 40 </maxvalue> </option> <option name= \"example_select\" > <categoryname> example.sub </categoryname> <optiontype> select </optiontype> <defaultvalue> DESC </defaultvalue> <selectoptions> ASC:wcf.global.sortOrder.ascending DESC:wcf.global.sortOrder.descending </selectoptions> </option> </options> </import> <delete> <option name= \"outdated_example\" /> </delete> </data>","title":"option"},{"location":"package/pip/option/#option-package-installation-plugin","text":"Registers new options. Options allow the administrator to configure the behaviour of installed packages. The specified values are exposed as PHP constants.","title":"Option Package Installation Plugin"},{"location":"package/pip/option/#category-components","text":"Each category is described as an <category> element with the mandatory attribute name .","title":"Category Components"},{"location":"package/pip/option/#parent","text":"Optional The category\u2019s parent category.","title":"<parent>"},{"location":"package/pip/option/#showorder","text":"Optional Specifies the order of this option within the parent category.","title":"<showorder>"},{"location":"package/pip/option/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the category to be shown to the administrator.","title":"<options>"},{"location":"package/pip/option/#option-components","text":"Each option is described as an <option> element with the mandatory attribute name . The name is transformed into a PHP constant name by uppercasing it.","title":"Option Components"},{"location":"package/pip/option/#categoryname","text":"The option\u2019s category.","title":"<categoryname>"},{"location":"package/pip/option/#optiontype","text":"The type of input to be used for this option. Valid types are defined by the wcf\\system\\option\\*OptionType classes.","title":"<optiontype>"},{"location":"package/pip/option/#defaultvalue","text":"The value that is set after installation of a package. Valid values are defined by the optiontype .","title":"<defaultvalue>"},{"location":"package/pip/option/#validationpattern","text":"Optional Defines a regular expression that is used to validate the value of a free form option (such as text ).","title":"<validationpattern>"},{"location":"package/pip/option/#showorder_1","text":"Optional Specifies the order of this option within the category.","title":"<showorder>"},{"location":"package/pip/option/#selectoptions","text":"Optional Defined only for select , multiSelect and radioButton types. Specifies a newline-separated list of selectable values. Each line consists of an internal handle, followed by a colon ( : , U+003A), followed by a language item. The language item is shown to the administrator, the internal handle is what is saved and exposed to the code.","title":"<selectoptions>"},{"location":"package/pip/option/#enableoptions","text":"Optional Defined only for boolean , select and radioButton types. Specifies a comma-separated list of options which should be visually enabled when this option is enabled. A leading exclamation mark ( ! , U+0021) will disable the specified option when this option is enabled. For select and radioButton types the list should be prefixed by the internal selectoptions handle followed by a colon ( : , U+003A). This setting is a visual helper for the administrator only. It does not have an effect on the server side processing of the option.","title":"<enableoptions>"},{"location":"package/pip/option/#hidden","text":"Optional If hidden is set to 1 the option will not be shown to the administrator. It still can be modified programmatically.","title":"<hidden>"},{"location":"package/pip/option/#options_1","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the option to be shown to the administrator.","title":"<options>"},{"location":"package/pip/option/#supporti18n","text":"Optional Specifies whether this option supports localized input.","title":"<supporti18n>"},{"location":"package/pip/option/#requirei18n","text":"Optional Specifies whether this option requires localized input (i.e. the administrator must specify a value for every installed language).","title":"<requirei18n>"},{"location":"package/pip/option/#_1","text":"Optional Additional fields may be defined by specific types of options. Refer to the documentation of these for further explanation.","title":"<*>"},{"location":"package/pip/option/#language-items","text":"All relevant language items have to be put into the wcf.acp.option language item category.","title":"Language Items"},{"location":"package/pip/option/#categories","text":"If you install a category named example.sub , you have to provide the language item wcf.acp.option.category.example.sub , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.acp.option.category.example.sub.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level.","title":"Categories"},{"location":"package/pip/option/#options_2","text":"If you install an option named module_example , you have to provide the language item wcf.acp.option.module_example , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.acp.option.module_example.description .","title":"Options"},{"location":"package/pip/option/#example","text":"option.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/option.xsd\" > <import> <categories> <category name= \"example\" /> <category name= \"example.sub\" > <parent> example </parent> <options> module_example </options> </category> </categories> <options> <option name= \"module_example\" > <categoryname> module.community </categoryname> <optiontype> boolean </optiontype> <defaultvalue> 1 </defaultvalue> </option> <option name= \"example_integer\" > <categoryname> example.sub </categoryname> <optiontype> integer </optiontype> <defaultvalue> 10 </defaultvalue> <minvalue> 5 </minvalue> <maxvalue> 40 </maxvalue> </option> <option name= \"example_select\" > <categoryname> example.sub </categoryname> <optiontype> select </optiontype> <defaultvalue> DESC </defaultvalue> <selectoptions> ASC:wcf.global.sortOrder.ascending DESC:wcf.global.sortOrder.descending </selectoptions> </option> </options> </import> <delete> <option name= \"outdated_example\" /> </delete> </data>","title":"Example"},{"location":"package/pip/page/","text":"Page Package Installation Plugin # Registers page controllers, making them available for selection and configuration, including but not limited to boxes and menus. Components # Each item is described as a <page> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<PageName> , e.g. com.woltlab.wcf.MembersList . <pageType> # system # The special system type is reserved for pages that pull their properties and content from a registered PHP class. Requires the <controller> element. html , text or tpl # Provide arbitrary content, requires the <content> element. <controller> # Fully qualified class name for the controller, must implement wcf\\page\\IPage or wcf\\form\\IForm . <handler> # Fully qualified class name that can be optionally set to provide additional methods, such as displaying a badge for unread content and verifying permissions per page object id. <name> # The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <name> elements. <parent> # Sets the default parent page using its internal identifier, this setting controls the breadcrumbs and active menu item hierarchy. <hasFixedParent> # Pages can be assigned any other page as parent page by default, set to 1 to make the parent setting immutable. <permissions> # The comma represents a logical or , the check is successful if at least one permission is set. Comma separated list of permission names that will be checked one after another until at least one permission is set. <options> # The comma represents a logical or , the check is successful if at least one option is enabled. Comma separated list of options that will be checked one after another until at least one option is set. <excludeFromLandingPage> # Some pages should not be used as landing page, because they may not always be available and/or accessible to the user. For example, the account management page is available to logged-in users only and any guest attempting to visit that page would be presented with a permission denied message. Set this to 1 to prevent this page from becoming a landing page ever. <requireObjectID> # If the page requires an id of a specific object, like the user profile page requires the id of the user whose profile page is requested, <requireObjectID>1</requireObjectID> has to be added. If this item is not present, requireObjectID defaults to 0 . <availableDuringOfflineMode> # During offline mode, most pages should generally not be available. Certain pages, however, might still have to be accessible due to, for example, legal reasons. To make a page available during offline mode, <availableDuringOfflineMode>1</availableDuringOfflineMode> has to be added. If this item is not present, availableDuringOfflineMode defaults to 0 . <allowSpidersToIndex> # Administrators are able to set in the admin panel for each page, whether or not spiders are allowed to index it. The default value for this option can be set with the allowSpidersToIndex item whose value defaults to 0 . <cssClassName> # To add custom CSS classes to a page\u2019s <body> HTML element, you can specify them via the cssClassName item. If you want to add multiple CSS classes, separate them with spaces! <content> # The language attribute is required and should specify the ISO-639-1 language code. <title> # The title element is required and controls the page title shown to the end users. <content> # The content that should be used to populate the page, only used and required if the pageType equals text , html and tpl . Example # page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.MembersList\" > <pageType> system </pageType> <controller> wcf\\page\\MembersListPage </controller> <name language= \"de\" > Mitglieder </name> <name language= \"en\" > Members </name> <options> module_members_list </options> <permissions> user.profile.canViewMembersList </permissions> <allowSpidersToIndex> 1 </allowSpidersToIndex> <content language= \"en\" > <title> Members </title> </content> <content language= \"de\" > <title> Mitglieder </title> </content> </page> </import> <delete> <page identifier= \"com.woltlab.wcf.MembersList\" /> </delete> </data>","title":"page"},{"location":"package/pip/page/#page-package-installation-plugin","text":"Registers page controllers, making them available for selection and configuration, including but not limited to boxes and menus.","title":"Page Package Installation Plugin"},{"location":"package/pip/page/#components","text":"Each item is described as a <page> element with the mandatory attribute identifier that should follow the naming pattern <packageIdentifier>.<PageName> , e.g. com.woltlab.wcf.MembersList .","title":"Components"},{"location":"package/pip/page/#pagetype","text":"","title":"<pageType>"},{"location":"package/pip/page/#system","text":"The special system type is reserved for pages that pull their properties and content from a registered PHP class. Requires the <controller> element.","title":"system"},{"location":"package/pip/page/#html-text-or-tpl","text":"Provide arbitrary content, requires the <content> element.","title":"html, text or tpl"},{"location":"package/pip/page/#controller","text":"Fully qualified class name for the controller, must implement wcf\\page\\IPage or wcf\\form\\IForm .","title":"<controller>"},{"location":"package/pip/page/#handler","text":"Fully qualified class name that can be optionally set to provide additional methods, such as displaying a badge for unread content and verifying permissions per page object id.","title":"<handler>"},{"location":"package/pip/page/#name","text":"The language attribute is required and should specify the ISO-639-1 language code. The internal name displayed in the admin panel only, can be fully customized by the administrator and is immutable. Only one value is accepted and will be picked based on the site's default language, but you can provide localized values by including multiple <name> elements.","title":"<name>"},{"location":"package/pip/page/#parent","text":"Sets the default parent page using its internal identifier, this setting controls the breadcrumbs and active menu item hierarchy.","title":"<parent>"},{"location":"package/pip/page/#hasfixedparent","text":"Pages can be assigned any other page as parent page by default, set to 1 to make the parent setting immutable.","title":"<hasFixedParent>"},{"location":"package/pip/page/#permissions","text":"The comma represents a logical or , the check is successful if at least one permission is set. Comma separated list of permission names that will be checked one after another until at least one permission is set.","title":"<permissions>"},{"location":"package/pip/page/#options","text":"The comma represents a logical or , the check is successful if at least one option is enabled. Comma separated list of options that will be checked one after another until at least one option is set.","title":"<options>"},{"location":"package/pip/page/#excludefromlandingpage","text":"Some pages should not be used as landing page, because they may not always be available and/or accessible to the user. For example, the account management page is available to logged-in users only and any guest attempting to visit that page would be presented with a permission denied message. Set this to 1 to prevent this page from becoming a landing page ever.","title":"<excludeFromLandingPage>"},{"location":"package/pip/page/#requireobjectid","text":"If the page requires an id of a specific object, like the user profile page requires the id of the user whose profile page is requested, <requireObjectID>1</requireObjectID> has to be added. If this item is not present, requireObjectID defaults to 0 .","title":"<requireObjectID>"},{"location":"package/pip/page/#availableduringofflinemode","text":"During offline mode, most pages should generally not be available. Certain pages, however, might still have to be accessible due to, for example, legal reasons. To make a page available during offline mode, <availableDuringOfflineMode>1</availableDuringOfflineMode> has to be added. If this item is not present, availableDuringOfflineMode defaults to 0 .","title":"<availableDuringOfflineMode>"},{"location":"package/pip/page/#allowspiderstoindex","text":"Administrators are able to set in the admin panel for each page, whether or not spiders are allowed to index it. The default value for this option can be set with the allowSpidersToIndex item whose value defaults to 0 .","title":"<allowSpidersToIndex>"},{"location":"package/pip/page/#cssclassname","text":"To add custom CSS classes to a page\u2019s <body> HTML element, you can specify them via the cssClassName item. If you want to add multiple CSS classes, separate them with spaces!","title":"<cssClassName>"},{"location":"package/pip/page/#content","text":"The language attribute is required and should specify the ISO-639-1 language code.","title":"<content>"},{"location":"package/pip/page/#title","text":"The title element is required and controls the page title shown to the end users.","title":"<title>"},{"location":"package/pip/page/#content_1","text":"The content that should be used to populate the page, only used and required if the pageType equals text , html and tpl .","title":"<content>"},{"location":"package/pip/page/#example","text":"page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.MembersList\" > <pageType> system </pageType> <controller> wcf\\page\\MembersListPage </controller> <name language= \"de\" > Mitglieder </name> <name language= \"en\" > Members </name> <options> module_members_list </options> <permissions> user.profile.canViewMembersList </permissions> <allowSpidersToIndex> 1 </allowSpidersToIndex> <content language= \"en\" > <title> Members </title> </content> <content language= \"de\" > <title> Mitglieder </title> </content> </page> </import> <delete> <page identifier= \"com.woltlab.wcf.MembersList\" /> </delete> </data>","title":"Example"},{"location":"package/pip/pip/","text":"Package Installation Plugin Package Installation Plugin # Registers new package installation plugins. Components # Each package installation plugin is described as an <pip> element with a name attribute and a PHP classname as the text content. The package installation plugin\u2019s class file must be installed into the wcf application and must not include classes outside the \\wcf\\* hierarchy to allow for proper uninstallation! Example # packageInstallationPlugin.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/packageInstallationPlugin.xsd\" > <import> <pip name= \"custom\" > wcf\\system\\package\\plugin\\CustomPackageInstallationPlugin </pip> </import> <delete> <pip name= \"outdated\" /> </delete> </data>","title":"pip"},{"location":"package/pip/pip/#package-installation-plugin-package-installation-plugin","text":"Registers new package installation plugins.","title":"Package Installation Plugin Package Installation Plugin"},{"location":"package/pip/pip/#components","text":"Each package installation plugin is described as an <pip> element with a name attribute and a PHP classname as the text content. The package installation plugin\u2019s class file must be installed into the wcf application and must not include classes outside the \\wcf\\* hierarchy to allow for proper uninstallation!","title":"Components"},{"location":"package/pip/pip/#example","text":"packageInstallationPlugin.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/packageInstallationPlugin.xsd\" > <import> <pip name= \"custom\" > wcf\\system\\package\\plugin\\CustomPackageInstallationPlugin </pip> </import> <delete> <pip name= \"outdated\" /> </delete> </data>","title":"Example"},{"location":"package/pip/script/","text":"Script Package Installation Plugin # Execute arbitrary PHP code during installation, update and uninstallation of the package. You must install the PHP script through the file package installation plugin . The installation will attempt to delete the script after successful execution. Attributes # application # The application attribute must have the same value as the application attribute of the file package installation plugin instruction so that the correct file in the intended application directory is executed. For further information about the application attribute, refer to its documentation on the acpTemplate package installation plugin page . Expected value # The script -PIP expects a relative path to a .php file. Naming convention # The PHP script is deployed by using the file package installation plugin . To prevent it from colliding with other install script (remember: You cannot overwrite files created by another plugin), we highly recommend to make use of these naming conventions: Installation: install_<package>.php (example: install_com.woltlab.wbb.php ) Update: update_<package>_<targetVersion>.php (example: update_com.woltlab.wbb_5.0.0_pl_1.php ) <targetVersion> equals the version number of the current package being installed. If you're updating from 1.0.0 to 1.0.1 , <targetVersion> should read 1.0.1 . Execution environment # The script is included using include() within ScriptPackageInstallationPlugin::run() . This grants you access to the class members, including $this->installation . You can retrieve the package id of the current package through $this->installation->getPackageID() .","title":"script"},{"location":"package/pip/script/#script-package-installation-plugin","text":"Execute arbitrary PHP code during installation, update and uninstallation of the package. You must install the PHP script through the file package installation plugin . The installation will attempt to delete the script after successful execution.","title":"Script Package Installation Plugin"},{"location":"package/pip/script/#attributes","text":"","title":"Attributes"},{"location":"package/pip/script/#application","text":"The application attribute must have the same value as the application attribute of the file package installation plugin instruction so that the correct file in the intended application directory is executed. For further information about the application attribute, refer to its documentation on the acpTemplate package installation plugin page .","title":"application"},{"location":"package/pip/script/#expected-value","text":"The script -PIP expects a relative path to a .php file.","title":"Expected value"},{"location":"package/pip/script/#naming-convention","text":"The PHP script is deployed by using the file package installation plugin . To prevent it from colliding with other install script (remember: You cannot overwrite files created by another plugin), we highly recommend to make use of these naming conventions: Installation: install_<package>.php (example: install_com.woltlab.wbb.php ) Update: update_<package>_<targetVersion>.php (example: update_com.woltlab.wbb_5.0.0_pl_1.php ) <targetVersion> equals the version number of the current package being installed. If you're updating from 1.0.0 to 1.0.1 , <targetVersion> should read 1.0.1 .","title":"Naming convention"},{"location":"package/pip/script/#execution-environment","text":"The script is included using include() within ScriptPackageInstallationPlugin::run() . This grants you access to the class members, including $this->installation . You can retrieve the package id of the current package through $this->installation->getPackageID() .","title":"Execution environment"},{"location":"package/pip/smiley/","text":"Smiley Package Installation Plugin # Installs new smileys. Components # Each smiley is described as an <smiley> element with the mandatory attribute name . <title> # Short human readable description of the smiley. <path(2x)?> # The files must be installed using the file PIP. File path relative to the root of WoltLab Suite Core. path2x is optional and being used for High-DPI screens. <aliases> # Optional List of smiley aliases. Aliases must be separated by a line feed character ( \\n , U+000A). <showorder> # Optional Determines at which position of the smiley list the smiley is shown. Example # smiley.xml 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/smiley.xsd\" > <import> <smiley name= \":example:\" > <title> example </title> <path> images/smilies/example.png </path> <path2x> images/smilies/example@2x.png </path2x> <aliases> <![CDATA[:alias: :more_aliases:]]> </aliases> </smiley> </import> </data>","title":"smiley"},{"location":"package/pip/smiley/#smiley-package-installation-plugin","text":"Installs new smileys.","title":"Smiley Package Installation Plugin"},{"location":"package/pip/smiley/#components","text":"Each smiley is described as an <smiley> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/smiley/#title","text":"Short human readable description of the smiley.","title":"<title>"},{"location":"package/pip/smiley/#path2x","text":"The files must be installed using the file PIP. File path relative to the root of WoltLab Suite Core. path2x is optional and being used for High-DPI screens.","title":"<path(2x)?>"},{"location":"package/pip/smiley/#aliases","text":"Optional List of smiley aliases. Aliases must be separated by a line feed character ( \\n , U+000A).","title":"<aliases>"},{"location":"package/pip/smiley/#showorder","text":"Optional Determines at which position of the smiley list the smiley is shown.","title":"<showorder>"},{"location":"package/pip/smiley/#example","text":"smiley.xml 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/smiley.xsd\" > <import> <smiley name= \":example:\" > <title> example </title> <path> images/smilies/example.png </path> <path2x> images/smilies/example@2x.png </path2x> <aliases> <![CDATA[:alias: :more_aliases:]]> </aliases> </smiley> </import> </data>","title":"Example"},{"location":"package/pip/sql/","text":"SQL Package Installation Plugin # Execute SQL instructions using a MySQL-flavored syntax. This file is parsed by WoltLab Suite Core to allow reverting of certain changes, but not every syntax MySQL supports is recognized by the parser. To avoid any troubles, you should always use statements relying on the SQL standard. Expected Value # The sql package installation plugin expects a relative path to a .sql file. Features # Logging # WoltLab Suite Core uses a SQL parser to extract queries and log certain actions. This allows WoltLab Suite Core to revert some of the changes you apply upon package uninstallation. The logged changes are: CREATE TABLE ALTER TABLE \u2026 ADD COLUMN ALTER TABLE \u2026 ADD \u2026 KEY Instance Number # It is possible to use different instance numbers, e.g. two separate WoltLab Suite Core installations within one database. WoltLab Suite Core requires you to always use wcf1_<tableName> or <app>1_<tableName> (e.g. blog1_blog in WoltLab Suite Blog), the number ( 1 ) will be automatically replaced prior to execution. If you every use anything other but 1 , you will eventually break things, thus always use 1 ! Table Type # WoltLab Suite Core will determine the type of database tables on its own: If the table contains a FULLTEXT index, it uses MyISAM , otherwise InnoDB is used. Limitations # Logging # WoltLab Suite Core cannot revert changes to the database structure which would cause to the data to be either changed or new data to be incompatible with the original format. Additionally, WoltLab Suite Core does not track regular SQL queries such as DELETE or UPDATE . Triggers # WoltLab Suite Core does not support trigger since MySQL does not support execution of triggers if the event was fired by a cascading foreign key action. If you really need triggers, you should consider adding them by custom SQL queries using a script . Example # package.xml : 1 <instruction type= \"sql\" > install.sql </instruction> Example content: install.sql 1 2 3 4 5 6 7 8 9 10 CREATE TABLE wcf1_foo_bar ( fooID INT ( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , packageID INT ( 10 ) NOT NULL , bar VARCHAR ( 255 ) NOT NULL DEFAULT '' , foobar VARCHAR ( 50 ) NOT NULL DEFAULT '' , UNIQUE KEY baz ( bar , foobar ) ); ALTER TABLE wcf1_foo_bar ADD FOREIGN KEY ( packageID ) REFERENCES wcf1_package ( packageID ) ON DELETE CASCADE ;","title":"sql"},{"location":"package/pip/sql/#sql-package-installation-plugin","text":"Execute SQL instructions using a MySQL-flavored syntax. This file is parsed by WoltLab Suite Core to allow reverting of certain changes, but not every syntax MySQL supports is recognized by the parser. To avoid any troubles, you should always use statements relying on the SQL standard.","title":"SQL Package Installation Plugin"},{"location":"package/pip/sql/#expected-value","text":"The sql package installation plugin expects a relative path to a .sql file.","title":"Expected Value"},{"location":"package/pip/sql/#features","text":"","title":"Features"},{"location":"package/pip/sql/#logging","text":"WoltLab Suite Core uses a SQL parser to extract queries and log certain actions. This allows WoltLab Suite Core to revert some of the changes you apply upon package uninstallation. The logged changes are: CREATE TABLE ALTER TABLE \u2026 ADD COLUMN ALTER TABLE \u2026 ADD \u2026 KEY","title":"Logging"},{"location":"package/pip/sql/#instance-number","text":"It is possible to use different instance numbers, e.g. two separate WoltLab Suite Core installations within one database. WoltLab Suite Core requires you to always use wcf1_<tableName> or <app>1_<tableName> (e.g. blog1_blog in WoltLab Suite Blog), the number ( 1 ) will be automatically replaced prior to execution. If you every use anything other but 1 , you will eventually break things, thus always use 1 !","title":"Instance Number"},{"location":"package/pip/sql/#table-type","text":"WoltLab Suite Core will determine the type of database tables on its own: If the table contains a FULLTEXT index, it uses MyISAM , otherwise InnoDB is used.","title":"Table Type"},{"location":"package/pip/sql/#limitations","text":"","title":"Limitations"},{"location":"package/pip/sql/#logging_1","text":"WoltLab Suite Core cannot revert changes to the database structure which would cause to the data to be either changed or new data to be incompatible with the original format. Additionally, WoltLab Suite Core does not track regular SQL queries such as DELETE or UPDATE .","title":"Logging"},{"location":"package/pip/sql/#triggers","text":"WoltLab Suite Core does not support trigger since MySQL does not support execution of triggers if the event was fired by a cascading foreign key action. If you really need triggers, you should consider adding them by custom SQL queries using a script .","title":"Triggers"},{"location":"package/pip/sql/#example","text":"package.xml : 1 <instruction type= \"sql\" > install.sql </instruction> Example content: install.sql 1 2 3 4 5 6 7 8 9 10 CREATE TABLE wcf1_foo_bar ( fooID INT ( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , packageID INT ( 10 ) NOT NULL , bar VARCHAR ( 255 ) NOT NULL DEFAULT '' , foobar VARCHAR ( 50 ) NOT NULL DEFAULT '' , UNIQUE KEY baz ( bar , foobar ) ); ALTER TABLE wcf1_foo_bar ADD FOREIGN KEY ( packageID ) REFERENCES wcf1_package ( packageID ) ON DELETE CASCADE ;","title":"Example"},{"location":"package/pip/style/","text":"Style Package Installation Plugin # Install styles during package installation. The style package installation plugins expects a relative path to a .tar file, a .tar.gz file or a .tgz file. Please use the ACP's export mechanism to export styles. Example in package.xml # 1 <instruction type= \"style\" > style.tgz </instruction>","title":"style"},{"location":"package/pip/style/#style-package-installation-plugin","text":"Install styles during package installation. The style package installation plugins expects a relative path to a .tar file, a .tar.gz file or a .tgz file. Please use the ACP's export mechanism to export styles.","title":"Style Package Installation Plugin"},{"location":"package/pip/style/#example-in-packagexml","text":"1 <instruction type= \"style\" > style.tgz </instruction>","title":"Example in package.xml"},{"location":"package/pip/template-delete/","text":"Template Delete Package Installation Plugin # Available since WoltLab Suite 5.5. Deletes frontend templates installed with the template package installation plugin. You cannot delete templates provided by other packages. Components # Each item is described as a <template> element with an optional application , which behaves like it does for acp templates . The templates are identified by their name like when adding template listeners , i.e. by the file name without the .tpl file extension. Example # templateDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/templateDelete.xsd\" > <delete> <template> fouAdd </template> <template application= \"app\" > __appAdd </template> </delete> </data>","title":"templateDelete"},{"location":"package/pip/template-delete/#template-delete-package-installation-plugin","text":"Available since WoltLab Suite 5.5. Deletes frontend templates installed with the template package installation plugin. You cannot delete templates provided by other packages.","title":"Template Delete Package Installation Plugin"},{"location":"package/pip/template-delete/#components","text":"Each item is described as a <template> element with an optional application , which behaves like it does for acp templates . The templates are identified by their name like when adding template listeners , i.e. by the file name without the .tpl file extension.","title":"Components"},{"location":"package/pip/template-delete/#example","text":"templateDelete.xml 1 2 3 4 5 6 7 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/templateDelete.xsd\" > <delete> <template> fouAdd </template> <template application= \"app\" > __appAdd </template> </delete> </data>","title":"Example"},{"location":"package/pip/template-listener/","text":"Template Listener Package Installation Plugin # Registers template listeners. Template listeners supplement event listeners , which modify server side behaviour, by adding additional template code to display additional elements. The added template code behaves as if it was part of the original template (i.e. it has access to all local variables). Components # Each event listener is described as an <templatelistener> element with a name attribute. As the name attribute has only be introduced with WSC 3.0, it is not yet mandatory to allow backwards compatibility. If name is not given, the system automatically sets the name based on the id of the event listener in the database. <templatename> # The template name is the name of the template in which the event is fired. It correspondes to the eventclassname field of event listeners. <eventname> # The event name is the name given when the event is fired to identify different events within the same template. <templatecode> # The given template code is literally copied into the target template during compile time. The original template is not modified. If multiple template listeners listen to a single event their output is concatenated using the line feed character ( \\n , U+000A) in the order defined by the niceValue . It is recommend that the only code is an {include} of a template to enable changes by the administrator. Names of templates included by a template listener start with two underscores by convention. <environment> # The value of the environment element can either be admin or user and is user if no value is given. The value determines if the template listener will be executed in the frontend ( user ) or the backend ( admin ). <nice> # Optional The nice value element can contain an integer value out of the interval [-128,127] with 0 being the default value if the element is omitted. The nice value determines the execution order of template listeners. Template listeners with smaller nice values are executed first. If the nice value of two template listeners is equal, the order is undefined. If you pass a value out of the mentioned interval, the value will be adjusted to the closest value in the interval. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the template listener to be executed. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the template listener to be executed. Example # templateListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/templatelistener.xsd\" > <import> <templatelistener name= \"example\" > <environment> user </environment> <templatename> headIncludeJavaScript </templatename> <eventname> javascriptInclude </eventname> <templatecode> <![CDATA[{include file='__myCustomJavaScript'}]]> </templatecode> </templatelistener> </import> <delete> <templatelistener name= \"oldTemplateListenerName\" > <environment> user </environment> <templatename> headIncludeJavaScript </templatename> <eventname> javascriptInclude </eventname> </templatelistener> </delete> </data>","title":"templateListener"},{"location":"package/pip/template-listener/#template-listener-package-installation-plugin","text":"Registers template listeners. Template listeners supplement event listeners , which modify server side behaviour, by adding additional template code to display additional elements. The added template code behaves as if it was part of the original template (i.e. it has access to all local variables).","title":"Template Listener Package Installation Plugin"},{"location":"package/pip/template-listener/#components","text":"Each event listener is described as an <templatelistener> element with a name attribute. As the name attribute has only be introduced with WSC 3.0, it is not yet mandatory to allow backwards compatibility. If name is not given, the system automatically sets the name based on the id of the event listener in the database.","title":"Components"},{"location":"package/pip/template-listener/#templatename","text":"The template name is the name of the template in which the event is fired. It correspondes to the eventclassname field of event listeners.","title":"<templatename>"},{"location":"package/pip/template-listener/#eventname","text":"The event name is the name given when the event is fired to identify different events within the same template.","title":"<eventname>"},{"location":"package/pip/template-listener/#templatecode","text":"The given template code is literally copied into the target template during compile time. The original template is not modified. If multiple template listeners listen to a single event their output is concatenated using the line feed character ( \\n , U+000A) in the order defined by the niceValue . It is recommend that the only code is an {include} of a template to enable changes by the administrator. Names of templates included by a template listener start with two underscores by convention.","title":"<templatecode>"},{"location":"package/pip/template-listener/#environment","text":"The value of the environment element can either be admin or user and is user if no value is given. The value determines if the template listener will be executed in the frontend ( user ) or the backend ( admin ).","title":"<environment>"},{"location":"package/pip/template-listener/#nice","text":"Optional The nice value element can contain an integer value out of the interval [-128,127] with 0 being the default value if the element is omitted. The nice value determines the execution order of template listeners. Template listeners with smaller nice values are executed first. If the nice value of two template listeners is equal, the order is undefined. If you pass a value out of the mentioned interval, the value will be adjusted to the closest value in the interval.","title":"<nice>"},{"location":"package/pip/template-listener/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the template listener to be executed.","title":"<options>"},{"location":"package/pip/template-listener/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the template listener to be executed.","title":"<permissions>"},{"location":"package/pip/template-listener/#example","text":"templateListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/templatelistener.xsd\" > <import> <templatelistener name= \"example\" > <environment> user </environment> <templatename> headIncludeJavaScript </templatename> <eventname> javascriptInclude </eventname> <templatecode> <![CDATA[{include file='__myCustomJavaScript'}]]> </templatecode> </templatelistener> </import> <delete> <templatelistener name= \"oldTemplateListenerName\" > <environment> user </environment> <templatename> headIncludeJavaScript </templatename> <eventname> javascriptInclude </eventname> </templatelistener> </delete> </data>","title":"Example"},{"location":"package/pip/template/","text":"Template Package Installation Plugin # Add templates for frontend pages and forms by providing an archive containing the template files. You cannot overwrite templates provided by other packages. This package installation plugin behaves exactly like the acpTemplate package installation plugin except for installing frontend templates instead of backend/acp templates.","title":"template"},{"location":"package/pip/template/#template-package-installation-plugin","text":"Add templates for frontend pages and forms by providing an archive containing the template files. You cannot overwrite templates provided by other packages. This package installation plugin behaves exactly like the acpTemplate package installation plugin except for installing frontend templates instead of backend/acp templates.","title":"Template Package Installation Plugin"},{"location":"package/pip/user-group-option/","text":"User Group Option Package Installation Plugin # Registers new user group options (\u201cpermissions\u201d). The behaviour of this package installation plugin closely follows the option PIP. Category Components # The category definition works exactly like the option PIP. Option Components # The fields hidden , supporti18n and requirei18n do not apply. The following extra fields are defined: <(admin|mod|user)defaultvalue> # Defines the defaultvalue s for subsets of the groups: Type Description admin Groups where the admin.user.accessibleGroups user group option includes every group. mod Groups where the mod.general.canUseModeration is set to true . user Groups where the internal group type is neither UserGroup::EVERYONE nor UserGroup::GUESTS . <usersonly> # Makes the option unavailable for groups with the group type UserGroup::GUESTS . Language Items # All relevant language items have to be put into the wcf.acp.group language item category. Categories # If you install a category named user.foo , you have to provide the language item wcf.acp.group.option.category.user.foo , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.acp.group.option.category.user.foo.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level. Options # If you install an option named user.foo.canBar , you have to provide the language item wcf.acp.group.option.user.foo.canBar , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.acp.group.option.user.foo.canBar.description .","title":"userGroupOption"},{"location":"package/pip/user-group-option/#user-group-option-package-installation-plugin","text":"Registers new user group options (\u201cpermissions\u201d). The behaviour of this package installation plugin closely follows the option PIP.","title":"User Group Option Package Installation Plugin"},{"location":"package/pip/user-group-option/#category-components","text":"The category definition works exactly like the option PIP.","title":"Category Components"},{"location":"package/pip/user-group-option/#option-components","text":"The fields hidden , supporti18n and requirei18n do not apply. The following extra fields are defined:","title":"Option Components"},{"location":"package/pip/user-group-option/#adminmoduserdefaultvalue","text":"Defines the defaultvalue s for subsets of the groups: Type Description admin Groups where the admin.user.accessibleGroups user group option includes every group. mod Groups where the mod.general.canUseModeration is set to true . user Groups where the internal group type is neither UserGroup::EVERYONE nor UserGroup::GUESTS .","title":"<(admin|mod|user)defaultvalue>"},{"location":"package/pip/user-group-option/#usersonly","text":"Makes the option unavailable for groups with the group type UserGroup::GUESTS .","title":"<usersonly>"},{"location":"package/pip/user-group-option/#language-items","text":"All relevant language items have to be put into the wcf.acp.group language item category.","title":"Language Items"},{"location":"package/pip/user-group-option/#categories","text":"If you install a category named user.foo , you have to provide the language item wcf.acp.group.option.category.user.foo , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.acp.group.option.category.user.foo.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level.","title":"Categories"},{"location":"package/pip/user-group-option/#options","text":"If you install an option named user.foo.canBar , you have to provide the language item wcf.acp.group.option.user.foo.canBar , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.acp.group.option.user.foo.canBar.description .","title":"Options"},{"location":"package/pip/user-menu/","text":"User Menu Package Installation Plugin # Registers new user menu items. Components # Each item is described as an <usermenuitem> element with the mandatory attribute name . <parent> # Optional The item\u2019s parent item. <showorder> # Optional Specifies the order of this item within the parent item. <controller> # The fully qualified class name of the target controller. If not specified this item serves as a category. <link> # Additional components if <controller> is set, the full external link otherwise. <iconclassname> # Use an icon only for top-level items. Name of the Font Awesome icon class. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the menu item to be shown. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the menu item to be shown. <classname> # The name of the class providing the user menu item\u2019s behaviour, the class has to implement the wcf\\system\\menu\\user\\IUserMenuItemProvider interface. Example # userMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userMenu.xsd\" > <import> <usermenuitem name= \"wcf.user.menu.foo\" > <iconclassname> fa-home </iconclassname> </usermenuitem> <usermenuitem name= \"wcf.user.menu.foo.bar\" > <controller> wcf\\page\\FooBarListPage </controller> <parent> wcf.user.menu.foo </parent> <permissions> user.foo.canBar </permissions> <classname> wcf\\system\\menu\\user\\FooBarMenuItemProvider </classname> </usermenuitem> <usermenuitem name= \"wcf.user.menu.foo.baz\" > <controller> wcf\\page\\FooBazListPage </controller> <parent> wcf.user.menu.foo </parent> <permissions> user.foo.canBaz </permissions> <options> module_foo_bar </options> </usermenuitem> </import> </data>","title":"userMenu"},{"location":"package/pip/user-menu/#user-menu-package-installation-plugin","text":"Registers new user menu items.","title":"User Menu Package Installation Plugin"},{"location":"package/pip/user-menu/#components","text":"Each item is described as an <usermenuitem> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/user-menu/#parent","text":"Optional The item\u2019s parent item.","title":"<parent>"},{"location":"package/pip/user-menu/#showorder","text":"Optional Specifies the order of this item within the parent item.","title":"<showorder>"},{"location":"package/pip/user-menu/#controller","text":"The fully qualified class name of the target controller. If not specified this item serves as a category.","title":"<controller>"},{"location":"package/pip/user-menu/#link","text":"Additional components if <controller> is set, the full external link otherwise.","title":"<link>"},{"location":"package/pip/user-menu/#iconclassname","text":"Use an icon only for top-level items. Name of the Font Awesome icon class.","title":"<iconclassname>"},{"location":"package/pip/user-menu/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the menu item to be shown.","title":"<options>"},{"location":"package/pip/user-menu/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the menu item to be shown.","title":"<permissions>"},{"location":"package/pip/user-menu/#classname","text":"The name of the class providing the user menu item\u2019s behaviour, the class has to implement the wcf\\system\\menu\\user\\IUserMenuItemProvider interface.","title":"<classname>"},{"location":"package/pip/user-menu/#example","text":"userMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userMenu.xsd\" > <import> <usermenuitem name= \"wcf.user.menu.foo\" > <iconclassname> fa-home </iconclassname> </usermenuitem> <usermenuitem name= \"wcf.user.menu.foo.bar\" > <controller> wcf\\page\\FooBarListPage </controller> <parent> wcf.user.menu.foo </parent> <permissions> user.foo.canBar </permissions> <classname> wcf\\system\\menu\\user\\FooBarMenuItemProvider </classname> </usermenuitem> <usermenuitem name= \"wcf.user.menu.foo.baz\" > <controller> wcf\\page\\FooBazListPage </controller> <parent> wcf.user.menu.foo </parent> <permissions> user.foo.canBaz </permissions> <options> module_foo_bar </options> </usermenuitem> </import> </data>","title":"Example"},{"location":"package/pip/user-notification-event/","text":"User Notification Event Package Installation Plugin # Registers new user notification events. Components # Each package installation plugin is described as an <event> element with the mandatory child <name> . <objectType> # The (name, objectType) pair must be unique. The given object type must implement the com.woltlab.wcf.notification.objectType definition. <classname> # The name of the class providing the event's behaviour, the class has to implement the wcf\\system\\user\\notification\\event\\IUserNotificationEvent interface. <preset> # Defines whether this event is enabled by default. <presetmailnotificationtype> # Avoid using this option, as sending unsolicited mail can be seen as spamming. One of instant or daily . Defines whether this type of email notifications is enabled by default. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the notification type to be available. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the notification type to be available. Example # userNotificationEvent.xml 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userNotificationEvent.xsd\" > <import> <event> <name> like </name> <objecttype> com.woltlab.example.comment.like.notification </objecttype> <classname> wcf\\system\\user\\notification\\event\\ExampleCommentLikeUserNotificationEvent </classname> <preset> 1 </preset> <options> module_like </options> </event> </import> </data>","title":"userNotificationEvent"},{"location":"package/pip/user-notification-event/#user-notification-event-package-installation-plugin","text":"Registers new user notification events.","title":"User Notification Event Package Installation Plugin"},{"location":"package/pip/user-notification-event/#components","text":"Each package installation plugin is described as an <event> element with the mandatory child <name> .","title":"Components"},{"location":"package/pip/user-notification-event/#objecttype","text":"The (name, objectType) pair must be unique. The given object type must implement the com.woltlab.wcf.notification.objectType definition.","title":"<objectType>"},{"location":"package/pip/user-notification-event/#classname","text":"The name of the class providing the event's behaviour, the class has to implement the wcf\\system\\user\\notification\\event\\IUserNotificationEvent interface.","title":"<classname>"},{"location":"package/pip/user-notification-event/#preset","text":"Defines whether this event is enabled by default.","title":"<preset>"},{"location":"package/pip/user-notification-event/#presetmailnotificationtype","text":"Avoid using this option, as sending unsolicited mail can be seen as spamming. One of instant or daily . Defines whether this type of email notifications is enabled by default.","title":"<presetmailnotificationtype>"},{"location":"package/pip/user-notification-event/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the notification type to be available.","title":"<options>"},{"location":"package/pip/user-notification-event/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the notification type to be available.","title":"<permissions>"},{"location":"package/pip/user-notification-event/#example","text":"userNotificationEvent.xml 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userNotificationEvent.xsd\" > <import> <event> <name> like </name> <objecttype> com.woltlab.example.comment.like.notification </objecttype> <classname> wcf\\system\\user\\notification\\event\\ExampleCommentLikeUserNotificationEvent </classname> <preset> 1 </preset> <options> module_like </options> </event> </import> </data>","title":"Example"},{"location":"package/pip/user-option/","text":"User Option Package Installation Plugin # Registers new user options (profile fields / user settings). The behaviour of this package installation plugin closely follows the option PIP. Category Components # The category definition works exactly like the option PIP. Option Components # The fields hidden , supporti18n and requirei18n do not apply. The following extra fields are defined: <required> # Requires that a value is provided. <askduringregistration> # If set to 1 the field is shown during user registration in the frontend. <editable> # Bitfield with the following options (constants in wcf\\data\\user\\option\\UserOption ) Name Value EDITABILITY_OWNER 1 EDITABILITY_ADMINISTRATOR 2 EDITABILITY_OWNER_DURING_REGISTRATION 4 <visible> # Bitfield with the following options (constants in wcf\\data\\user\\option\\UserOption ) Name Value VISIBILITY_OWNER 1 VISIBILITY_ADMINISTRATOR 2 VISIBILITY_REGISTERED 4 VISIBILITY_GUEST 8 <searchable> # If set to 1 the field is searchable. <outputclass> # PHP class responsible for output formatting of this field. the class has to implement the wcf\\system\\option\\user\\IUserOptionOutput interface. Language Items # All relevant language items have to be put into the wcf.user.option language item category. Categories # If you install a category named example , you have to provide the language item wcf.user.option.category.example , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.user.option.category.example.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level. Options # If you install an option named exampleOption , you have to provide the language item wcf.user.option.exampleOption , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.user.option.exampleOption.description .","title":"userOption"},{"location":"package/pip/user-option/#user-option-package-installation-plugin","text":"Registers new user options (profile fields / user settings). The behaviour of this package installation plugin closely follows the option PIP.","title":"User Option Package Installation Plugin"},{"location":"package/pip/user-option/#category-components","text":"The category definition works exactly like the option PIP.","title":"Category Components"},{"location":"package/pip/user-option/#option-components","text":"The fields hidden , supporti18n and requirei18n do not apply. The following extra fields are defined:","title":"Option Components"},{"location":"package/pip/user-option/#required","text":"Requires that a value is provided.","title":"<required>"},{"location":"package/pip/user-option/#askduringregistration","text":"If set to 1 the field is shown during user registration in the frontend.","title":"<askduringregistration>"},{"location":"package/pip/user-option/#editable","text":"Bitfield with the following options (constants in wcf\\data\\user\\option\\UserOption ) Name Value EDITABILITY_OWNER 1 EDITABILITY_ADMINISTRATOR 2 EDITABILITY_OWNER_DURING_REGISTRATION 4","title":"<editable>"},{"location":"package/pip/user-option/#visible","text":"Bitfield with the following options (constants in wcf\\data\\user\\option\\UserOption ) Name Value VISIBILITY_OWNER 1 VISIBILITY_ADMINISTRATOR 2 VISIBILITY_REGISTERED 4 VISIBILITY_GUEST 8","title":"<visible>"},{"location":"package/pip/user-option/#searchable","text":"If set to 1 the field is searchable.","title":"<searchable>"},{"location":"package/pip/user-option/#outputclass","text":"PHP class responsible for output formatting of this field. the class has to implement the wcf\\system\\option\\user\\IUserOptionOutput interface.","title":"<outputclass>"},{"location":"package/pip/user-option/#language-items","text":"All relevant language items have to be put into the wcf.user.option language item category.","title":"Language Items"},{"location":"package/pip/user-option/#categories","text":"If you install a category named example , you have to provide the language item wcf.user.option.category.example , which is used when displaying the options. If you want to provide an optional description of the category, you have to provide the language item wcf.user.option.category.example.description . Descriptions are only relevant for categories whose parent has a parent itself, i.e. categories on the third level.","title":"Categories"},{"location":"package/pip/user-option/#options","text":"If you install an option named exampleOption , you have to provide the language item wcf.user.option.exampleOption , which is used as a label for setting the option value. If you want to provide an optional description of the option, you have to provide the language item wcf.user.option.exampleOption.description .","title":"Options"},{"location":"package/pip/user-profile-menu/","text":"User Profile Menu Package Installation Plugin # Registers new user profile tabs. Components # Each tab is described as an <userprofilemenuitem> element with the mandatory attribute name . <classname> # The name of the class providing the tab\u2019s behaviour, the class has to implement the wcf\\system\\menu\\user\\profile\\content\\IUserProfileMenuContent interface. <showorder> # Optional Determines at which position of the tab list the tab is shown. <options> # Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the tab to be shown. <permissions> # Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the tab to be shown. Example # userProfileMenu.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"utf-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userProfileMenu.xsd\" > <import> <userprofilemenuitem name= \"example\" > <classname> wcf\\system\\menu\\user\\profile\\content\\ExampleProfileMenuContent </classname> <showorder> 3 </showorder> <options> module_example </options> </userprofilemenuitem> </import> </data>","title":"userProfileMenu"},{"location":"package/pip/user-profile-menu/#user-profile-menu-package-installation-plugin","text":"Registers new user profile tabs.","title":"User Profile Menu Package Installation Plugin"},{"location":"package/pip/user-profile-menu/#components","text":"Each tab is described as an <userprofilemenuitem> element with the mandatory attribute name .","title":"Components"},{"location":"package/pip/user-profile-menu/#classname","text":"The name of the class providing the tab\u2019s behaviour, the class has to implement the wcf\\system\\menu\\user\\profile\\content\\IUserProfileMenuContent interface.","title":"<classname>"},{"location":"package/pip/user-profile-menu/#showorder","text":"Optional Determines at which position of the tab list the tab is shown.","title":"<showorder>"},{"location":"package/pip/user-profile-menu/#options","text":"Optional The options element can contain a comma-separated list of options of which at least one needs to be enabled for the tab to be shown.","title":"<options>"},{"location":"package/pip/user-profile-menu/#permissions","text":"Optional The permissions element can contain a comma-separated list of permissions of which the active user needs to have at least one for the tab to be shown.","title":"<permissions>"},{"location":"package/pip/user-profile-menu/#example","text":"userProfileMenu.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"utf-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userProfileMenu.xsd\" > <import> <userprofilemenuitem name= \"example\" > <classname> wcf\\system\\menu\\user\\profile\\content\\ExampleProfileMenuContent </classname> <showorder> 3 </showorder> <options> module_example </options> </userprofilemenuitem> </import> </data>","title":"Example"},{"location":"php/apps/","text":"Apps for WoltLab Suite # Introduction # Apps are among the most powerful components in WoltLab Suite. Unlike plugins that extend an existing functionality and pages, apps have their own frontend with a dedicated namespace, database table prefixes and template locations. However, apps are meant to be a logical (and to some extent physical) separation from other parts of the framework, including other installed apps. They offer an additional layer of isolation and enable you to re-use class and template names that are already in use by the Core itself. If you've come here, thinking about the question if your next package should be an app instead of a regular plugin, the result is almost always: No. Differences to Plugins # Apps do offer a couple of unique features that are not available to plugins and there are valid reasons to use one instead of a plugin, but they also increase both the code and system complexity. There is a performance penalty for each installed app, regardless if it is actively used in a request or not, simplying being there forces the Core to include it in many places, for example, class resolution or even simple tasks such as constructing a link. Unique Namespace # Each app has its own unique namespace that is entirely separated from the Core and any other installed apps. The namespace is derived from the last part of the package identifier, for example, com.example.foo will yield the namespace foo . The namespace is always relative to the installation directory of the app, it doesn't matter if the app is installed on example.com/foo/ or in example.com/bar/ , the namespace will always resolve to the right directory. This app namespace is also used for ACP templates, frontend templates and files: 1 2 <!-- somewhere in the package.xml --> <instructions type= \"file\" application= \"foo\" /> Unique Database Table Prefix # All database tables make use of a generic prefix that is derived from one of the installed apps, including wcf which resolves to the Core itself. Following the aforementioned example, the new prefix fooN_ will be automatically registered and recognized in any generated statement. Any DatabaseObject that uses the app's namespace is automatically assumed to use the app's database prefix. For instance, foo\\data\\bar\\Bar is implicitly mapped to the database table fooN_bar . The app prefix is recognized in SQL-PIPs and statements that reference one of its database tables are automatically rewritten to use the Core's instance number. Separate Domain and Path Configuration # Any controller that is provided by a plugin is served from the configured domain and path of the corresponding app, such as plugins for the Core are always served from the Core's directory. Apps are different and use their own domain and/or path to present their content, additionally, this allows the app to re-use a controller name that is already provided by the Core or any other app itself. Creating an App # This is a non-reversible operation! Once a package has been installed, its type cannot be changed without uninstalling and reinstalling the entire package, an app will always be an app and vice versa. package.xml # The package.xml supports two additional elements in the <packageinformation> block that are unique to applications. <isapplication>1</isapplication> # This element is responsible to flag a package as an app. <applicationdirectory>example</applicationdirectory> # Sets the suggested name of the application directory when installing it, the path result in <path-to-the-core>/example/ . If you leave this element out, the app identifier ( com.example.foo -> foo ) will be used instead. Minimum Required Files # An example project with the source code can be found on GitHub , it includes everything that is required for a basic app.","title":"Apps"},{"location":"php/apps/#apps-for-woltlab-suite","text":"","title":"Apps for WoltLab Suite"},{"location":"php/apps/#introduction","text":"Apps are among the most powerful components in WoltLab Suite. Unlike plugins that extend an existing functionality and pages, apps have their own frontend with a dedicated namespace, database table prefixes and template locations. However, apps are meant to be a logical (and to some extent physical) separation from other parts of the framework, including other installed apps. They offer an additional layer of isolation and enable you to re-use class and template names that are already in use by the Core itself. If you've come here, thinking about the question if your next package should be an app instead of a regular plugin, the result is almost always: No.","title":"Introduction"},{"location":"php/apps/#differences-to-plugins","text":"Apps do offer a couple of unique features that are not available to plugins and there are valid reasons to use one instead of a plugin, but they also increase both the code and system complexity. There is a performance penalty for each installed app, regardless if it is actively used in a request or not, simplying being there forces the Core to include it in many places, for example, class resolution or even simple tasks such as constructing a link.","title":"Differences to Plugins"},{"location":"php/apps/#unique-namespace","text":"Each app has its own unique namespace that is entirely separated from the Core and any other installed apps. The namespace is derived from the last part of the package identifier, for example, com.example.foo will yield the namespace foo . The namespace is always relative to the installation directory of the app, it doesn't matter if the app is installed on example.com/foo/ or in example.com/bar/ , the namespace will always resolve to the right directory. This app namespace is also used for ACP templates, frontend templates and files: 1 2 <!-- somewhere in the package.xml --> <instructions type= \"file\" application= \"foo\" />","title":"Unique Namespace"},{"location":"php/apps/#unique-database-table-prefix","text":"All database tables make use of a generic prefix that is derived from one of the installed apps, including wcf which resolves to the Core itself. Following the aforementioned example, the new prefix fooN_ will be automatically registered and recognized in any generated statement. Any DatabaseObject that uses the app's namespace is automatically assumed to use the app's database prefix. For instance, foo\\data\\bar\\Bar is implicitly mapped to the database table fooN_bar . The app prefix is recognized in SQL-PIPs and statements that reference one of its database tables are automatically rewritten to use the Core's instance number.","title":"Unique Database Table Prefix"},{"location":"php/apps/#separate-domain-and-path-configuration","text":"Any controller that is provided by a plugin is served from the configured domain and path of the corresponding app, such as plugins for the Core are always served from the Core's directory. Apps are different and use their own domain and/or path to present their content, additionally, this allows the app to re-use a controller name that is already provided by the Core or any other app itself.","title":"Separate Domain and Path Configuration"},{"location":"php/apps/#creating-an-app","text":"This is a non-reversible operation! Once a package has been installed, its type cannot be changed without uninstalling and reinstalling the entire package, an app will always be an app and vice versa.","title":"Creating an App"},{"location":"php/apps/#packagexml","text":"The package.xml supports two additional elements in the <packageinformation> block that are unique to applications.","title":"package.xml"},{"location":"php/apps/#isapplication1isapplication","text":"This element is responsible to flag a package as an app.","title":"<isapplication>1</isapplication>"},{"location":"php/apps/#applicationdirectoryexampleapplicationdirectory","text":"Sets the suggested name of the application directory when installing it, the path result in <path-to-the-core>/example/ . If you leave this element out, the app identifier ( com.example.foo -> foo ) will be used instead.","title":"<applicationdirectory>example</applicationdirectory>"},{"location":"php/apps/#minimum-required-files","text":"An example project with the source code can be found on GitHub , it includes everything that is required for a basic app.","title":"Minimum Required Files"},{"location":"php/code-style-documentation/","text":"Documentation # The following documentation conventions are used by us for our own packages. While you do not have to follow every rule, you are encouraged to do so. Database Objects # Database Table Columns as Properties # As the database table columns are not explicit properties of the classes extending wcf\\data\\DatabaseObject but rather stored in DatabaseObject::$data and accessible via DatabaseObject::__get($name) , the IDE we use, PhpStorm, is neither able to autocomplete such property access nor to interfere the type of the property. To solve this problem, @property-read tags must be added to the class documentation which registers the database table columns as public read-only properties: 1 * @property-read propertyType $propertyName property description The properties have to be in the same order as the order in the database table. The following table provides templates for common description texts so that similar database table columns have similar description texts. property description template and example unique object id unique id of the {object name} example: unique id of the acl option id of the delivering package id of the package which delivers the {object name} example: id of the package which delivers the acl option show order for nested structure position of the {object name} in relation to its siblings example: position of the ACP menu item in relation to its siblings show order within different object position of the {object name} in relation to the other {object name}s in the {parent object name} example: position of the label in relation to the other labels in the label group required permissions comma separated list of user group permissions of which the active user needs to have at least one to see (access, \u2026) the {object name} example: comma separated list of user group permissions of which the active user needs to have at least one to see the ACP menu item required options comma separated list of options of which at least one needs to be enabled for the {object name} to be shown (accessible, \u2026) example: comma separated list of options of which at least one needs to be enabled for the ACP menu item to be shown id of the user who has created the object id of the user who created (wrote, \u2026) the {object name} (or `null` if the user does not exist anymore (or if the {object name} has been created by a guest)) example: id of the user who wrote the comment or `null` if the user does not exist anymore or if the comment has been written by a guest name of the user who has created the object name of the user (or guest) who created (wrote, \u2026) the {object name} example: name of the user or guest who wrote the comment additional data array with additional data of the {object name} example: array with additional data of the user activity event time-related columns timestamp at which the {object name} has been created (written, \u2026) example: timestamp at which the comment has been written boolean options is `1` (or `0`) if the {object name} \u2026 (and thus \u2026), otherwise `0` (or `1`) example: is `1` if the ad is disabled and thus not shown, otherwise `0` $cumulativeLikes cumulative result of likes (counting `+1`) and dislikes (counting `-1`) for the {object name} example: cumulative result of likes (counting `+1`) and dislikes (counting `-1`) for the article $comments number of comments on the {object name} example: number of comments on the article $views number of times the {object name} has been viewed example: number of times the article has been viewed text field with potential language item name as value {text type} of the {object name} or name of language item which contains the {text type} example: description of the cronjob or name of language item which contains the description $objectTypeID id of the `{object type definition name}` object type example: id of the `com.woltlab.wcf.modifiableContent` object type Database Object Editors # Class Tags # Any database object editor class comment must have to following tags to properly support autocompletion by IDEs: 1 2 3 4 5 6 /** * \u2026 * @method static {DBO class name} create(array $parameters = []) * @method {DBO class name} getDecoratedObject() * @mixin {DBO class name} */ The only exception to this rule is if the class overwrites the create() method which itself has to be properly documentation then. The first and second line makes sure that when calling the create() or getDecoratedObject() method, the return value is correctly recognized and not just a general DatabaseObject instance. The third line tells the IDE (if @mixin is supported) that the database object editor decorates the database object and therefore offers autocompletion for properties and methods from the database object class itself. Runtime Caches # Class Tags # Any class implementing the IRuntimeCache interface must have the following class tags: 1 2 3 4 5 6 /** * \u2026 * @method {DBO class name}[] getCachedObjects() * @method {DBO class name} getObject($objectID) * @method {DBO class name}[] getObjects(array $objectIDs) */ These tags ensure that when calling any of the mentioned methods, the return value refers to the concrete database object and not just generically to DatabaseObject .","title":"Documentation"},{"location":"php/code-style-documentation/#documentation","text":"The following documentation conventions are used by us for our own packages. While you do not have to follow every rule, you are encouraged to do so.","title":"Documentation"},{"location":"php/code-style-documentation/#database-objects","text":"","title":"Database Objects"},{"location":"php/code-style-documentation/#database-table-columns-as-properties","text":"As the database table columns are not explicit properties of the classes extending wcf\\data\\DatabaseObject but rather stored in DatabaseObject::$data and accessible via DatabaseObject::__get($name) , the IDE we use, PhpStorm, is neither able to autocomplete such property access nor to interfere the type of the property. To solve this problem, @property-read tags must be added to the class documentation which registers the database table columns as public read-only properties: 1 * @property-read propertyType $propertyName property description The properties have to be in the same order as the order in the database table. The following table provides templates for common description texts so that similar database table columns have similar description texts. property description template and example unique object id unique id of the {object name} example: unique id of the acl option id of the delivering package id of the package which delivers the {object name} example: id of the package which delivers the acl option show order for nested structure position of the {object name} in relation to its siblings example: position of the ACP menu item in relation to its siblings show order within different object position of the {object name} in relation to the other {object name}s in the {parent object name} example: position of the label in relation to the other labels in the label group required permissions comma separated list of user group permissions of which the active user needs to have at least one to see (access, \u2026) the {object name} example: comma separated list of user group permissions of which the active user needs to have at least one to see the ACP menu item required options comma separated list of options of which at least one needs to be enabled for the {object name} to be shown (accessible, \u2026) example: comma separated list of options of which at least one needs to be enabled for the ACP menu item to be shown id of the user who has created the object id of the user who created (wrote, \u2026) the {object name} (or `null` if the user does not exist anymore (or if the {object name} has been created by a guest)) example: id of the user who wrote the comment or `null` if the user does not exist anymore or if the comment has been written by a guest name of the user who has created the object name of the user (or guest) who created (wrote, \u2026) the {object name} example: name of the user or guest who wrote the comment additional data array with additional data of the {object name} example: array with additional data of the user activity event time-related columns timestamp at which the {object name} has been created (written, \u2026) example: timestamp at which the comment has been written boolean options is `1` (or `0`) if the {object name} \u2026 (and thus \u2026), otherwise `0` (or `1`) example: is `1` if the ad is disabled and thus not shown, otherwise `0` $cumulativeLikes cumulative result of likes (counting `+1`) and dislikes (counting `-1`) for the {object name} example: cumulative result of likes (counting `+1`) and dislikes (counting `-1`) for the article $comments number of comments on the {object name} example: number of comments on the article $views number of times the {object name} has been viewed example: number of times the article has been viewed text field with potential language item name as value {text type} of the {object name} or name of language item which contains the {text type} example: description of the cronjob or name of language item which contains the description $objectTypeID id of the `{object type definition name}` object type example: id of the `com.woltlab.wcf.modifiableContent` object type","title":"Database Table Columns as Properties"},{"location":"php/code-style-documentation/#database-object-editors","text":"","title":"Database Object Editors"},{"location":"php/code-style-documentation/#class-tags","text":"Any database object editor class comment must have to following tags to properly support autocompletion by IDEs: 1 2 3 4 5 6 /** * \u2026 * @method static {DBO class name} create(array $parameters = []) * @method {DBO class name} getDecoratedObject() * @mixin {DBO class name} */ The only exception to this rule is if the class overwrites the create() method which itself has to be properly documentation then. The first and second line makes sure that when calling the create() or getDecoratedObject() method, the return value is correctly recognized and not just a general DatabaseObject instance. The third line tells the IDE (if @mixin is supported) that the database object editor decorates the database object and therefore offers autocompletion for properties and methods from the database object class itself.","title":"Class Tags"},{"location":"php/code-style-documentation/#runtime-caches","text":"","title":"Runtime Caches"},{"location":"php/code-style-documentation/#class-tags_1","text":"Any class implementing the IRuntimeCache interface must have the following class tags: 1 2 3 4 5 6 /** * \u2026 * @method {DBO class name}[] getCachedObjects() * @method {DBO class name} getObject($objectID) * @method {DBO class name}[] getObjects(array $objectIDs) */ These tags ensure that when calling any of the mentioned methods, the return value refers to the concrete database object and not just generically to DatabaseObject .","title":"Class Tags"},{"location":"php/code-style/","text":"Code Style # The following code style conventions are used by us for our own packages. While you do not have to follow every rule, you are encouraged to do so. For information about how to document your code, please refer to the documentation page . General Code Style # Naming conventions # The relevant naming conventions are: Upper camel case : The first letters of all compound words are written in upper case. Lower camel case : The first letters of compound words are written in upper case, except for the first letter which is written in lower case. Screaming snake case : All letters are written in upper case and compound words are separated by underscores. Type Convention Example Variable lower camel case $variableName Class upper camel case class UserGroupEditor Properties lower camel case public $propertyName Method lower camel case public function getObjectByName() Constant screaming snake case MODULE_USER_THING Arrays # For arrays, use the short array syntax introduced with PHP 5.4. The following example illustrates the different cases that can occur when working with arrays and how to format them: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $empty = []; $oneElement = [ 1 ]; $multipleElements = [ 1 , 2 , 3 ]; $oneElementWithKey = [ 'firstElement' => 1 ]; $multipleElementsWithKey = [ 'firstElement' => 1 , 'secondElement' => 2 , 'thirdElement' => 3 ]; Ternary Operator # The ternary operator can be used for short conditioned assignments: 1 2 3 <? php $name = isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ; The condition and the values should be short so that the code does not result in a very long line which thus decreases the readability compared to an if-else statement. Parentheses may only be used around the condition and not around the whole statement: 1 2 3 4 <? php // do not do it like this $name = ( isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ); Parentheses around the conditions may not be used to wrap simple function calls: 1 2 3 4 <? php // do not do it like this $name = ( isset ( $tagArgs [ 'name' ])) ? $tagArgs [ 'name' ] : 'default' ; but have to be used for comparisons or other binary operators: 1 2 3 <? php $value = ( $otherValue > $upperLimit ) ? $additionalValue : $otherValue ; If you need to use more than one binary operator, use an if-else statement. The same rules apply to assigning array values: 1 2 3 4 5 6 7 <? php $values = [ 'first' => $firstValue , 'second' => $secondToggle ? $secondValueA : $secondValueB , 'third' => ( $thirdToogle > 13 ) ? $thirdToogleA : $thirdToogleB ]; or return values: 1 2 3 <? php return isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ; Whitespaces # You have to put a whitespace in front of the following things: equal sign in assignments: $x = 1; comparison operators: $x == 1 opening bracket of a block public function test() { You have to put a whitespace behind the following things: equal sign in assignments: $x = 1; comparison operators: $x == 1 comma in a function/method parameter list if the comma is not followed by a line break: public function test($a, $b) { if , for , foreach , while : if ($x == 1) Classes # Referencing Class Names # If you have to reference a class name inside a php file, you have to use the class keyword. 1 2 3 4 5 6 7 8 <? php // not like this $className = 'wcf\\data\\example\\Example' ; // like this use wcf\\data\\example\\Example ; $className = Example :: class ; Static Getters (of DatabaseObject Classes) # Some database objects provide static getters, either if they are decorators or for a unique combination of database table columns, like wcf\\data\\box\\Box::getBoxByIdentifier() : files/lib/data/box/Box.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <? php namespace wcf\\data\\box ; use wcf\\data\\DatabaseObject ; use wcf\\system\\WCF ; class Box extends DatabaseObject { /** * Returns the box with the given identifier. * * @param string $identifier * @return Box|null */ public static function getBoxByIdentifier ( $identifier ) { $sql = \"SELECT * FROM wcf\" . WCF_N . \"_box WHERE identifier = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ([ $identifier ]); return $statement -> fetchObject ( self :: class ); } } Such methods should always either return the desired object or null if the object does not exist. wcf\\system\\database\\statement\\PreparedStatement::fetchObject() already takes care of this distinction so that its return value can simply be returned by such methods. The name of such getters should generally follow the convention get{object type}By{column or other description} . Long method calls # In some instances, methods with many argument have to be called which can result in lines of code like this one: 1 2 3 <? php \\wcf\\system\\search\\SearchIndexManager :: getInstance () -> set ( 'com.woltlab.wcf.article' , $articleContent -> articleContentID , $articleContent -> content , $articleContent -> title , $articles [ $articleContent -> articleID ] -> time , $articles [ $articleContent -> articleID ] -> userID , $articles [ $articleContent -> articleID ] -> username , $articleContent -> languageID , $articleContent -> teaser ); which is hardly readable. Therefore, the line must be split into multiple lines with each argument in a separate line: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php \\wcf\\system\\search\\SearchIndexManager :: getInstance () -> set ( 'com.woltlab.wcf.article' , $articleContent -> articleContentID , $articleContent -> content , $articleContent -> title , $articles [ $articleContent -> articleID ] -> time , $articles [ $articleContent -> articleID ] -> userID , $articles [ $articleContent -> articleID ] -> username , $articleContent -> languageID , $articleContent -> teaser ); In general, this rule applies to the following methods: wcf\\system\\edit\\EditHistoryManager::add() wcf\\system\\message\\quote\\MessageQuoteManager::addQuote() wcf\\system\\message\\quote\\MessageQuoteManager::getQuoteID() wcf\\system\\search\\SearchIndexManager::set() wcf\\system\\user\\object\\watch\\UserObjectWatchHandler::updateObject() wcf\\system\\user\\notification\\UserNotificationHandler::fireEvent()","title":"Code Style"},{"location":"php/code-style/#code-style","text":"The following code style conventions are used by us for our own packages. While you do not have to follow every rule, you are encouraged to do so. For information about how to document your code, please refer to the documentation page .","title":"Code Style"},{"location":"php/code-style/#general-code-style","text":"","title":"General Code Style"},{"location":"php/code-style/#naming-conventions","text":"The relevant naming conventions are: Upper camel case : The first letters of all compound words are written in upper case. Lower camel case : The first letters of compound words are written in upper case, except for the first letter which is written in lower case. Screaming snake case : All letters are written in upper case and compound words are separated by underscores. Type Convention Example Variable lower camel case $variableName Class upper camel case class UserGroupEditor Properties lower camel case public $propertyName Method lower camel case public function getObjectByName() Constant screaming snake case MODULE_USER_THING","title":"Naming conventions"},{"location":"php/code-style/#arrays","text":"For arrays, use the short array syntax introduced with PHP 5.4. The following example illustrates the different cases that can occur when working with arrays and how to format them: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $empty = []; $oneElement = [ 1 ]; $multipleElements = [ 1 , 2 , 3 ]; $oneElementWithKey = [ 'firstElement' => 1 ]; $multipleElementsWithKey = [ 'firstElement' => 1 , 'secondElement' => 2 , 'thirdElement' => 3 ];","title":"Arrays"},{"location":"php/code-style/#ternary-operator","text":"The ternary operator can be used for short conditioned assignments: 1 2 3 <? php $name = isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ; The condition and the values should be short so that the code does not result in a very long line which thus decreases the readability compared to an if-else statement. Parentheses may only be used around the condition and not around the whole statement: 1 2 3 4 <? php // do not do it like this $name = ( isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ); Parentheses around the conditions may not be used to wrap simple function calls: 1 2 3 4 <? php // do not do it like this $name = ( isset ( $tagArgs [ 'name' ])) ? $tagArgs [ 'name' ] : 'default' ; but have to be used for comparisons or other binary operators: 1 2 3 <? php $value = ( $otherValue > $upperLimit ) ? $additionalValue : $otherValue ; If you need to use more than one binary operator, use an if-else statement. The same rules apply to assigning array values: 1 2 3 4 5 6 7 <? php $values = [ 'first' => $firstValue , 'second' => $secondToggle ? $secondValueA : $secondValueB , 'third' => ( $thirdToogle > 13 ) ? $thirdToogleA : $thirdToogleB ]; or return values: 1 2 3 <? php return isset ( $tagArgs [ 'name' ]) ? $tagArgs [ 'name' ] : 'default' ;","title":"Ternary Operator"},{"location":"php/code-style/#whitespaces","text":"You have to put a whitespace in front of the following things: equal sign in assignments: $x = 1; comparison operators: $x == 1 opening bracket of a block public function test() { You have to put a whitespace behind the following things: equal sign in assignments: $x = 1; comparison operators: $x == 1 comma in a function/method parameter list if the comma is not followed by a line break: public function test($a, $b) { if , for , foreach , while : if ($x == 1)","title":"Whitespaces"},{"location":"php/code-style/#classes","text":"","title":"Classes"},{"location":"php/code-style/#referencing-class-names","text":"If you have to reference a class name inside a php file, you have to use the class keyword. 1 2 3 4 5 6 7 8 <? php // not like this $className = 'wcf\\data\\example\\Example' ; // like this use wcf\\data\\example\\Example ; $className = Example :: class ;","title":"Referencing Class Names"},{"location":"php/code-style/#static-getters-of-databaseobject-classes","text":"Some database objects provide static getters, either if they are decorators or for a unique combination of database table columns, like wcf\\data\\box\\Box::getBoxByIdentifier() : files/lib/data/box/Box.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <? php namespace wcf\\data\\box ; use wcf\\data\\DatabaseObject ; use wcf\\system\\WCF ; class Box extends DatabaseObject { /** * Returns the box with the given identifier. * * @param string $identifier * @return Box|null */ public static function getBoxByIdentifier ( $identifier ) { $sql = \"SELECT * FROM wcf\" . WCF_N . \"_box WHERE identifier = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ([ $identifier ]); return $statement -> fetchObject ( self :: class ); } } Such methods should always either return the desired object or null if the object does not exist. wcf\\system\\database\\statement\\PreparedStatement::fetchObject() already takes care of this distinction so that its return value can simply be returned by such methods. The name of such getters should generally follow the convention get{object type}By{column or other description} .","title":"Static Getters (of DatabaseObject Classes)"},{"location":"php/code-style/#long-method-calls","text":"In some instances, methods with many argument have to be called which can result in lines of code like this one: 1 2 3 <? php \\wcf\\system\\search\\SearchIndexManager :: getInstance () -> set ( 'com.woltlab.wcf.article' , $articleContent -> articleContentID , $articleContent -> content , $articleContent -> title , $articles [ $articleContent -> articleID ] -> time , $articles [ $articleContent -> articleID ] -> userID , $articles [ $articleContent -> articleID ] -> username , $articleContent -> languageID , $articleContent -> teaser ); which is hardly readable. Therefore, the line must be split into multiple lines with each argument in a separate line: 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php \\wcf\\system\\search\\SearchIndexManager :: getInstance () -> set ( 'com.woltlab.wcf.article' , $articleContent -> articleContentID , $articleContent -> content , $articleContent -> title , $articles [ $articleContent -> articleID ] -> time , $articles [ $articleContent -> articleID ] -> userID , $articles [ $articleContent -> articleID ] -> username , $articleContent -> languageID , $articleContent -> teaser ); In general, this rule applies to the following methods: wcf\\system\\edit\\EditHistoryManager::add() wcf\\system\\message\\quote\\MessageQuoteManager::addQuote() wcf\\system\\message\\quote\\MessageQuoteManager::getQuoteID() wcf\\system\\search\\SearchIndexManager::set() wcf\\system\\user\\object\\watch\\UserObjectWatchHandler::updateObject() wcf\\system\\user\\notification\\UserNotificationHandler::fireEvent()","title":"Long method calls"},{"location":"php/database-access/","text":"Database Access # Database Objects provide a convenient and object-oriented approach to work with the database, but there can be use-cases that require raw access including writing methods for model classes. This section assumes that you have either used prepared statements before or at least understand how it works. The PreparedStatement Object # The database access is designed around PreparedStatement , built on top of PHP's PDOStatement so that you call all of PDOStatement 's methods, and each query requires you to obtain a statement object. 1 2 3 4 5 6 <? php $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( \"SELECT * FROM wcf\" . WCF_N . \"_example\" ); $statement -> execute (); while ( $row = $statement -> fetchArray ()) { // handle result } Query Parameters # The example below illustrates the usage of parameters where each value is replaced with the generic ? -placeholder. Values are provided by calling $statement->execute() with a continuous, one-dimensional array that exactly match the number of question marks. 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example WHERE exampleID = ? OR bar IN (?, ?, ?, ?, ?)\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ([ $exampleID , $list , $of , $values , $for , $bar ]); while ( $row = $statement -> fetchArray ()) { // handle result } Fetching a Single Result # Do not attempt to use fetchSingleRow() or fetchSingleColumn() if the result contains more than one row. You can opt-in to retrieve only a single row from database and make use of shortcut methods to reduce the code that you have to write. 1 2 3 4 5 6 7 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql , 1 ); $statement -> execute ([ $exampleID ]); $row = $statement -> fetchSingleRow (); There are two distinct differences when comparing with the example on query parameters above: The method prepareStatement() receives a secondary parameter that will be appended to the query as LIMIT 1 . Data is read using fetchSingleRow() instead of fetchArray() or similar methods, that will read one result and close the cursor. Fetch by Column # There is no way to return another column from the same row if you use fetchColumn() to retrieve data. Fetching an array is only useful if there is going to be more than one column per result row, otherwise accessing the column directly is much more convenient and increases the code readability. 1 2 3 4 5 6 7 8 9 <? php $sql = \"SELECT bar FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); while ( $bar = $statement -> fetchColumn ()) { // handle result } $bar = $statement -> fetchSingleColumn (); Similar to fetching a single row, you can also issue a query that will select a single row, but reads only one column from the result row. 1 2 3 4 5 6 7 <? php $sql = \"SELECT bar FROM wcf\" . WCF_N . \"_example WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql , 1 ); $statement -> execute ([ $exampleID ]); $bar = $statement -> fetchSingleColumn (); Fetching All Results # If you want to fetch all results of a query but only store them in an array without directly processing them, in most cases, you can rely on built-in methods. To fetch all rows of query, you can use PDOStatement::fetchAll() with \\PDO::FETCH_ASSOC as the first parameter: 1 2 3 4 5 6 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $rows = $statement -> fetchAll ( \\PDO :: FETCH_ASSOC ); As a result, you get an array containing associative arrays with the rows of the wcf{WCF_N}_example database table as content. If you only want to fetch a list of the values of a certain column, you can use \\PDO::FETCH_COLUMN as the first parameter: 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $exampleIDs = $statement -> fetchAll ( \\PDO :: FETCH_COLUMN ); As a result, you get an array with all exampleID values. The PreparedStatement class adds an additional methods that covers another common use case in our code: Fetching two columns and using the first column's value as the array key and the second column's value as the array value. This case is covered by PreparedStatement::fetchMap() : 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID, userID FROM wcf\" . WCF_N . \"_example_mapping\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $map = $statement -> fetchMap ( 'exampleID' , 'userID' ); $map is a one-dimensional array where each exampleID value maps to the corresponding userID value. If there are multiple entries for a certain exampleID value with different userID values, the existing entry in the array will be overwritten and contain the last read value from the database table. Therefore, this method should generally only be used for unique combinations. If you do not have a combination of columns with unique pairs of values, but you want to get a list of userID values with the same exampleID , you can set the third parameter of fetchMap() to false and get a list: 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID, userID FROM wcf\" . WCF_N . \"_example_mapping\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $map = $statement -> fetchMap ( 'exampleID' , 'userID' , false ); Now, as a result, you get a two-dimensional array with the array keys being the exampleID values and the array values being arrays with all userID values from rows with the respective exampleID value. Building Complex Conditions # Building conditional conditions can turn out to be a real mess and it gets even worse with SQL's IN (\u2026) which requires as many placeholders as there will be values. The solutions is PreparedStatementConditionBuilder , a simple but useful helper class with a bulky name, it is also the class used when accessing DatabaseObjecList::getConditionBuilder() . 1 2 3 4 5 6 <? php $conditions = new \\wcf\\system\\database\\util\\PreparedStatementConditionBuilder (); $conditions -> add ( \"exampleID = ?\" , [ $exampleID ]); if ( ! empty ( $valuesForBar )) { $conditions -> add ( \"(bar IN (?) OR baz = ?)\" , [ $valuesForBar , $baz ]); } The IN (?) in the example above is automatically expanded to match the number of items contained in $valuesForBar . Be aware that the method will generate an invalid query if $valuesForBar is empty! INSERT or UPDATE in Bulk # Prepared statements not only protect against SQL injection by separating the logical query and the actual data, but also provides the ability to reuse the same query with different values. This leads to a performance improvement as the code does not have to transmit the query with for every data set and only has to parse and analyze the query once. 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $data = [ 'abc' , 'def' , 'ghi' ]; $sql = \"INSERT INTO wcf\" . WCF_N . \"_example (bar) VALUES (?)\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); \\wcf\\system\\WCF :: getDB () -> beginTransaction (); foreach ( $data as $bar ) { $statement -> execute ([ $bar ]); } \\wcf\\system\\WCF :: getDB () -> commitTransaction (); It is generally advised to wrap bulk operations in a transaction as it allows the database to optimize the process, including fewer I/O operations. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <? php $data = [ 1 => 'abc' , 3 => 'def' , 4 => 'ghi' ]; $sql = \"UPDATE wcf\" . WCF_N . \"_example SET bar = ? WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); \\wcf\\system\\WCF :: getDB () -> beginTransaction (); foreach ( $data as $exampleID => $bar ) { $statement -> execute ([ $bar , $exampleID ]); } \\wcf\\system\\WCF :: getDB () -> commitTransaction ();","title":"Database Access"},{"location":"php/database-access/#database-access","text":"Database Objects provide a convenient and object-oriented approach to work with the database, but there can be use-cases that require raw access including writing methods for model classes. This section assumes that you have either used prepared statements before or at least understand how it works.","title":"Database Access"},{"location":"php/database-access/#the-preparedstatement-object","text":"The database access is designed around PreparedStatement , built on top of PHP's PDOStatement so that you call all of PDOStatement 's methods, and each query requires you to obtain a statement object. 1 2 3 4 5 6 <? php $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( \"SELECT * FROM wcf\" . WCF_N . \"_example\" ); $statement -> execute (); while ( $row = $statement -> fetchArray ()) { // handle result }","title":"The PreparedStatement Object"},{"location":"php/database-access/#query-parameters","text":"The example below illustrates the usage of parameters where each value is replaced with the generic ? -placeholder. Values are provided by calling $statement->execute() with a continuous, one-dimensional array that exactly match the number of question marks. 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example WHERE exampleID = ? OR bar IN (?, ?, ?, ?, ?)\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ([ $exampleID , $list , $of , $values , $for , $bar ]); while ( $row = $statement -> fetchArray ()) { // handle result }","title":"Query Parameters"},{"location":"php/database-access/#fetching-a-single-result","text":"Do not attempt to use fetchSingleRow() or fetchSingleColumn() if the result contains more than one row. You can opt-in to retrieve only a single row from database and make use of shortcut methods to reduce the code that you have to write. 1 2 3 4 5 6 7 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql , 1 ); $statement -> execute ([ $exampleID ]); $row = $statement -> fetchSingleRow (); There are two distinct differences when comparing with the example on query parameters above: The method prepareStatement() receives a secondary parameter that will be appended to the query as LIMIT 1 . Data is read using fetchSingleRow() instead of fetchArray() or similar methods, that will read one result and close the cursor.","title":"Fetching a Single Result"},{"location":"php/database-access/#fetch-by-column","text":"There is no way to return another column from the same row if you use fetchColumn() to retrieve data. Fetching an array is only useful if there is going to be more than one column per result row, otherwise accessing the column directly is much more convenient and increases the code readability. 1 2 3 4 5 6 7 8 9 <? php $sql = \"SELECT bar FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); while ( $bar = $statement -> fetchColumn ()) { // handle result } $bar = $statement -> fetchSingleColumn (); Similar to fetching a single row, you can also issue a query that will select a single row, but reads only one column from the result row. 1 2 3 4 5 6 7 <? php $sql = \"SELECT bar FROM wcf\" . WCF_N . \"_example WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql , 1 ); $statement -> execute ([ $exampleID ]); $bar = $statement -> fetchSingleColumn ();","title":"Fetch by Column"},{"location":"php/database-access/#fetching-all-results","text":"If you want to fetch all results of a query but only store them in an array without directly processing them, in most cases, you can rely on built-in methods. To fetch all rows of query, you can use PDOStatement::fetchAll() with \\PDO::FETCH_ASSOC as the first parameter: 1 2 3 4 5 6 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $rows = $statement -> fetchAll ( \\PDO :: FETCH_ASSOC ); As a result, you get an array containing associative arrays with the rows of the wcf{WCF_N}_example database table as content. If you only want to fetch a list of the values of a certain column, you can use \\PDO::FETCH_COLUMN as the first parameter: 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID FROM wcf\" . WCF_N . \"_example\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $exampleIDs = $statement -> fetchAll ( \\PDO :: FETCH_COLUMN ); As a result, you get an array with all exampleID values. The PreparedStatement class adds an additional methods that covers another common use case in our code: Fetching two columns and using the first column's value as the array key and the second column's value as the array value. This case is covered by PreparedStatement::fetchMap() : 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID, userID FROM wcf\" . WCF_N . \"_example_mapping\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $map = $statement -> fetchMap ( 'exampleID' , 'userID' ); $map is a one-dimensional array where each exampleID value maps to the corresponding userID value. If there are multiple entries for a certain exampleID value with different userID values, the existing entry in the array will be overwritten and contain the last read value from the database table. Therefore, this method should generally only be used for unique combinations. If you do not have a combination of columns with unique pairs of values, but you want to get a list of userID values with the same exampleID , you can set the third parameter of fetchMap() to false and get a list: 1 2 3 4 5 6 <? php $sql = \"SELECT exampleID, userID FROM wcf\" . WCF_N . \"_example_mapping\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); $map = $statement -> fetchMap ( 'exampleID' , 'userID' , false ); Now, as a result, you get a two-dimensional array with the array keys being the exampleID values and the array values being arrays with all userID values from rows with the respective exampleID value.","title":"Fetching All Results"},{"location":"php/database-access/#building-complex-conditions","text":"Building conditional conditions can turn out to be a real mess and it gets even worse with SQL's IN (\u2026) which requires as many placeholders as there will be values. The solutions is PreparedStatementConditionBuilder , a simple but useful helper class with a bulky name, it is also the class used when accessing DatabaseObjecList::getConditionBuilder() . 1 2 3 4 5 6 <? php $conditions = new \\wcf\\system\\database\\util\\PreparedStatementConditionBuilder (); $conditions -> add ( \"exampleID = ?\" , [ $exampleID ]); if ( ! empty ( $valuesForBar )) { $conditions -> add ( \"(bar IN (?) OR baz = ?)\" , [ $valuesForBar , $baz ]); } The IN (?) in the example above is automatically expanded to match the number of items contained in $valuesForBar . Be aware that the method will generate an invalid query if $valuesForBar is empty!","title":"Building Complex Conditions"},{"location":"php/database-access/#insert-or-update-in-bulk","text":"Prepared statements not only protect against SQL injection by separating the logical query and the actual data, but also provides the ability to reuse the same query with different values. This leads to a performance improvement as the code does not have to transmit the query with for every data set and only has to parse and analyze the query once. 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php $data = [ 'abc' , 'def' , 'ghi' ]; $sql = \"INSERT INTO wcf\" . WCF_N . \"_example (bar) VALUES (?)\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); \\wcf\\system\\WCF :: getDB () -> beginTransaction (); foreach ( $data as $bar ) { $statement -> execute ([ $bar ]); } \\wcf\\system\\WCF :: getDB () -> commitTransaction (); It is generally advised to wrap bulk operations in a transaction as it allows the database to optimize the process, including fewer I/O operations. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <? php $data = [ 1 => 'abc' , 3 => 'def' , 4 => 'ghi' ]; $sql = \"UPDATE wcf\" . WCF_N . \"_example SET bar = ? WHERE exampleID = ?\" ; $statement = \\wcf\\system\\WCF :: getDB () -> prepareStatement ( $sql ); \\wcf\\system\\WCF :: getDB () -> beginTransaction (); foreach ( $data as $exampleID => $bar ) { $statement -> execute ([ $bar , $exampleID ]); } \\wcf\\system\\WCF :: getDB () -> commitTransaction ();","title":"INSERT or UPDATE in Bulk"},{"location":"php/database-objects/","text":"Database Objects # WoltLab Suite uses a unified interface to work with database rows using an object based approach instead of using native arrays holding arbitrary data. Each database table is mapped to a model class that is designed to hold a single record from that table and expose methods to work with the stored data, for example providing assistance when working with normalized datasets. Developers are required to provide the proper DatabaseObject implementations themselves, they're not automatically generated, all though the actual code that needs to be written is rather small. The following examples assume the fictional database table wcf1_example , exampleID as the auto-incrementing primary key and the column bar to store some text. DatabaseObject # The basic model derives from wcf\\data\\DatabaseObject and provides a convenient constructor to fetch a single row or construct an instance using pre-loaded rows. files/lib/data/example/Example.class.php 1 2 3 4 5 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObject ; class Example extends DatabaseObject {} The class is intended to be empty by default and there only needs to be code if you want to add additional logic to your model. Both the class name and primary key are determined by DatabaseObject using the namespace and class name of the derived class. The example above uses the namespace wcf\\\u2026 which is used as table prefix and the class name Example is converted into exampleID , resulting in the database table name wcfN_example with the primary key exampleID . You can prevent this automatic guessing by setting the class properties $databaseTableName and $databaseTableIndexName manually. DatabaseObjectDecorator # If you already have a DatabaseObject class and would like to extend it with additional data or methods, for example by providing a class ViewableExample which features view-related changes without polluting the original object, you can use DatabaseObjectDecorator which a default implementation of a decorator for database objects. files/lib/data/example/ViewableExample.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectDecorator ; class ViewableExample extends DatabaseObjectDecorator { protected static $baseClass = Example :: class ; public function getOutput () { $output = '' ; // [determine output] return $output ; } } It is mandatory to set the static $baseClass property to the name of the decorated class. Like for any decorator, you can directly access the decorated object's properties and methods for a decorated object by accessing the property or calling the method on the decorated object. You can access the decorated objects directly via DatabaseObjectDecorator::getDecoratedObject() . DatabaseObjectEditor # This is the low-level interface to manipulate data rows, it is recommended to use AbstractDatabaseObjectAction . Adding, editing and deleting models is done using the DatabaseObjectEditor class that decorates a DatabaseObject and uses its data to perform the actions. files/lib/data/example/ExampleEditor.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectEditor ; class ExampleEditor extends DatabaseObjectEditor { protected static $baseClass = Example :: class ; } The editor class requires you to provide the fully qualified name of the model, that is the class name including the complete namespace. Database table name and index key will be pulled directly from the model. Create a new row # Inserting a new row into the database table is provided through DatabaseObjectEditor::create() which yields a DatabaseObject instance after creation. 1 2 3 4 5 6 7 <? php $example = \\wcf\\data\\example\\ExampleEditor :: create ([ 'bar' => 'Hello World!' ]); // output: Hello World! echo $example -> bar ; Updating an existing row # The internal state of the decorated DatabaseObject is not altered at any point, the values will still be the same after editing or deleting the represented row. If you need an object with the latest data, you'll have to discard the current object and refetch the data from database. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php $example = new \\wcf\\data\\example\\Example ( $id ); $exampleEditor = new \\wcf\\data\\example\\ExampleEditor ( $example ); $exampleEditor -> update ([ 'bar' => 'baz' ]); // output: Hello World! echo $example -> bar ; // re-creating the object will query the database again and retrieve the updated value $example = new \\wcf\\data\\example\\Example ( $example -> id ); // output: baz echo $example -> bar ; Deleting a row # Similar to the update process, the decorated DatabaseObject is not altered and will then point to an inexistent row. 1 2 3 4 <? php $example = new \\wcf\\data\\example\\Example ( $id ); $exampleEditor = new \\wcf\\data\\example\\ExampleEditor ( $example ); $exampleEditor -> delete (); DatabaseObjectList # Every row is represented as a single instance of the model, but the instance creation deals with single rows only. Retrieving larger sets of rows would be quite inefficient due to the large amount of queries that will be dispatched. This is solved with the DatabaseObjectList object that exposes an interface to query the database table using arbitrary conditions for data selection. All rows will be fetched using a single query and the resulting rows are automatically loaded into separate models. files/lib/data/example/ExampleList.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectList ; class ExampleList extends DatabaseObjectList { public $className = Example :: class ; } The following code listing illustrates loading a large set of examples and iterating over the list to retrieve the objects. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php $exampleList = new \\wcf\\data\\example\\ExampleList (); // add constraints using the condition builder $exampleList -> getConditionBuilder () -> add ( 'bar IN (?)' , [[ 'Hello World!' , 'bar' , 'baz' ]]); // actually read the rows $exampleList -> readObjects (); foreach ( $exampleList as $example ) { echo $example -> bar ; } // retrieve the models directly instead of iterating over them $examples = $exampleList -> getObjects (); // just retrieve the number of rows $exampleCount = $exampleList -> countObjects (); DatabaseObjectList implements both SeekableIterator and Countable . Additionally, DatabaseObjectList objects has the following three public properties that are useful when fetching data with lists: $sqlLimit determines how many rows are fetched. If its value is 0 (which is the default value), all results are fetched. So be careful when dealing with large tables and you only want a limited number of rows: Set $sqlLimit to a value larger than zero! $sqlOffset : Paginated pages like a thread list use this feature a lot, it allows you to skip a given number of results. Imagine you want to display 20 threads per page but there are a total of 60 threads available. In this case you would specify $sqlLimit = 20 and $sqlOffset = 20 which will skip the first 20 threads, effectively displaying thread 21 to 40. $sqlOrderBy determines by which column(s) the rows are sorted in which order. Using our example in $sqlOffset you might want to display the 20 most recent threads on page 1, thus you should specify the order field and its direction, e.g. $sqlOrderBy = 'thread.lastPostTime DESC' which returns the most recent thread first. For more advanced usage, there two additional fields that deal with the type of objects returned. First, let's go into a bit more detail what setting the $className property actually does: It is the type of database object in which the rows are wrapped. It determines which database table is actually queried and which index is used (see the $databaseTableName and $databaseTableIndexName properties of DatabaseObject ). Sometimes you might use the database table of some database object but wrap the rows in another database object. This can be achieved by setting the $objectClassName property to the desired class name. In other cases, you might want to wrap the created objects in a database object decorator which can be done by setting the $decoratorClassName property to the desired class name: 1 2 3 <? php $exampleList = new \\wcf\\data\\example\\ExampleList (); $exampleList -> decoratorClassName = \\wcf\\data\\example\\ViewableExample :: class ; Of course, you do not have to set the property after creating the list object, you can also set it by creating a dedicated class: files/lib/data/example/ViewableExampleList.class.php 1 2 3 4 5 6 <? php namespace wcf\\data\\example ; class ViewableExampleList extends ExampleList { public $decoratorClassName = ViewableExample :: class ; } AbstractDatabaseObjectAction # Row creation and manipulation can be performed using the aforementioned DatabaseObjectEditor class, but this approach has two major issues: Row creation, update and deletion takes place silently without notifying any other components. Data is passed to the database adapter without any further processing. The AbstractDatabaseObjectAction solves both problems by wrapping around the editor class and thus provide an additional layer between the action that should be taken and the actual process. The first problem is solved by a fixed set of events being fired, the second issue is addressed by having a single entry point for all data editing. files/lib/data/example/ExampleAction.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\AbstractDatabaseObjectAction ; class ExampleAction extends AbstractDatabaseObjectAction { public $className = ExampleEditor :: class ; } Executing an Action # The method AbstractDatabaseObjectAction::validateAction() is internally used for AJAX method invocation and must not be called programmatically. The next example represents the same functionality as seen for DatabaseObjectEditor : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <? php use wcf\\data\\example\\ExampleAction ; // create a row $exampleAction = new ExampleAction ([], 'create' , [ 'data' => [ 'bar' => 'Hello World' ] ]); $example = $exampleAction -> executeAction ()[ 'returnValues' ]; // update a row using the id $exampleAction = new ExampleAction ([ 1 ], 'update' , [ 'data' => [ 'bar' => 'baz' ] ]); $exampleAction -> executeAction (); // delete a row using a model $exampleAction = new ExampleAction ([ $example ], 'delete' ); $exampleAction -> executeAction (); You can access the return values both by storing the return value of executeAction() or by retrieving it via getReturnValues() . Events initializeAction , validateAction and finalizeAction Custom Method with AJAX Support # This section is about adding the method baz() to ExampleAction and calling it via AJAX. AJAX Validation # Methods of an action cannot be called via AJAX, unless they have a validation method. This means that ExampleAction must define both a public function baz() and public function validateBaz() , the name for the validation method is constructed by upper-casing the first character of the method name and prepending validate . The lack of the companion validate* method will cause the AJAX proxy to deny the request instantaneously. Do not add a validation method if you don't want it to be callable via AJAX ever! create, update and delete # The methods create , update and delete are available for all classes deriving from AbstractDatabaseObjectAction and directly pass the input data to the DatabaseObjectEditor . These methods deny access to them via AJAX by default, unless you explicitly enable access. Depending on your case, there are two different strategies to enable AJAX access to them. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <? php namespace wcf\\data\\example ; use wcf\\data\\AbstractDatabaseObjectAction ; class ExampleAction extends AbstractDatabaseObjectAction { // `create()` can now be called via AJAX if the requesting user posses the listed permissions protected $permissionsCreate = [ 'admin.example.canManageExample' ]; public function validateUpdate () { // your very own validation logic that does not make use of the // built-in `$permissionsUpdate` property // you can still invoke the built-in permissions check if you like to parent :: validateUpdate (); } } Allow Invokation by Guests # Invoking methods is restricted to logged-in users by default and the only way to override this behavior is to alter the property $allowGuestAccess . It is a simple string array that is expected to hold all methods that should be accessible by users, excluding their companion validation methods. ACP Access Only # Method access is usually limited by permissions, but sometimes there might be the need for some added security to avoid mistakes. The $requireACP property works similar to $allowGuestAccess , but enforces the request to originate from the ACP together with a valid ACP session, ensuring that only users able to access the ACP can actually invoke these methods.","title":"Database Objects"},{"location":"php/database-objects/#database-objects","text":"WoltLab Suite uses a unified interface to work with database rows using an object based approach instead of using native arrays holding arbitrary data. Each database table is mapped to a model class that is designed to hold a single record from that table and expose methods to work with the stored data, for example providing assistance when working with normalized datasets. Developers are required to provide the proper DatabaseObject implementations themselves, they're not automatically generated, all though the actual code that needs to be written is rather small. The following examples assume the fictional database table wcf1_example , exampleID as the auto-incrementing primary key and the column bar to store some text.","title":"Database Objects"},{"location":"php/database-objects/#databaseobject","text":"The basic model derives from wcf\\data\\DatabaseObject and provides a convenient constructor to fetch a single row or construct an instance using pre-loaded rows. files/lib/data/example/Example.class.php 1 2 3 4 5 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObject ; class Example extends DatabaseObject {} The class is intended to be empty by default and there only needs to be code if you want to add additional logic to your model. Both the class name and primary key are determined by DatabaseObject using the namespace and class name of the derived class. The example above uses the namespace wcf\\\u2026 which is used as table prefix and the class name Example is converted into exampleID , resulting in the database table name wcfN_example with the primary key exampleID . You can prevent this automatic guessing by setting the class properties $databaseTableName and $databaseTableIndexName manually.","title":"DatabaseObject"},{"location":"php/database-objects/#databaseobjectdecorator","text":"If you already have a DatabaseObject class and would like to extend it with additional data or methods, for example by providing a class ViewableExample which features view-related changes without polluting the original object, you can use DatabaseObjectDecorator which a default implementation of a decorator for database objects. files/lib/data/example/ViewableExample.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectDecorator ; class ViewableExample extends DatabaseObjectDecorator { protected static $baseClass = Example :: class ; public function getOutput () { $output = '' ; // [determine output] return $output ; } } It is mandatory to set the static $baseClass property to the name of the decorated class. Like for any decorator, you can directly access the decorated object's properties and methods for a decorated object by accessing the property or calling the method on the decorated object. You can access the decorated objects directly via DatabaseObjectDecorator::getDecoratedObject() .","title":"DatabaseObjectDecorator"},{"location":"php/database-objects/#databaseobjecteditor","text":"This is the low-level interface to manipulate data rows, it is recommended to use AbstractDatabaseObjectAction . Adding, editing and deleting models is done using the DatabaseObjectEditor class that decorates a DatabaseObject and uses its data to perform the actions. files/lib/data/example/ExampleEditor.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectEditor ; class ExampleEditor extends DatabaseObjectEditor { protected static $baseClass = Example :: class ; } The editor class requires you to provide the fully qualified name of the model, that is the class name including the complete namespace. Database table name and index key will be pulled directly from the model.","title":"DatabaseObjectEditor"},{"location":"php/database-objects/#create-a-new-row","text":"Inserting a new row into the database table is provided through DatabaseObjectEditor::create() which yields a DatabaseObject instance after creation. 1 2 3 4 5 6 7 <? php $example = \\wcf\\data\\example\\ExampleEditor :: create ([ 'bar' => 'Hello World!' ]); // output: Hello World! echo $example -> bar ;","title":"Create a new row"},{"location":"php/database-objects/#updating-an-existing-row","text":"The internal state of the decorated DatabaseObject is not altered at any point, the values will still be the same after editing or deleting the represented row. If you need an object with the latest data, you'll have to discard the current object and refetch the data from database. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php $example = new \\wcf\\data\\example\\Example ( $id ); $exampleEditor = new \\wcf\\data\\example\\ExampleEditor ( $example ); $exampleEditor -> update ([ 'bar' => 'baz' ]); // output: Hello World! echo $example -> bar ; // re-creating the object will query the database again and retrieve the updated value $example = new \\wcf\\data\\example\\Example ( $example -> id ); // output: baz echo $example -> bar ;","title":"Updating an existing row"},{"location":"php/database-objects/#deleting-a-row","text":"Similar to the update process, the decorated DatabaseObject is not altered and will then point to an inexistent row. 1 2 3 4 <? php $example = new \\wcf\\data\\example\\Example ( $id ); $exampleEditor = new \\wcf\\data\\example\\ExampleEditor ( $example ); $exampleEditor -> delete ();","title":"Deleting a row"},{"location":"php/database-objects/#databaseobjectlist","text":"Every row is represented as a single instance of the model, but the instance creation deals with single rows only. Retrieving larger sets of rows would be quite inefficient due to the large amount of queries that will be dispatched. This is solved with the DatabaseObjectList object that exposes an interface to query the database table using arbitrary conditions for data selection. All rows will be fetched using a single query and the resulting rows are automatically loaded into separate models. files/lib/data/example/ExampleList.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\DatabaseObjectList ; class ExampleList extends DatabaseObjectList { public $className = Example :: class ; } The following code listing illustrates loading a large set of examples and iterating over the list to retrieve the objects. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php $exampleList = new \\wcf\\data\\example\\ExampleList (); // add constraints using the condition builder $exampleList -> getConditionBuilder () -> add ( 'bar IN (?)' , [[ 'Hello World!' , 'bar' , 'baz' ]]); // actually read the rows $exampleList -> readObjects (); foreach ( $exampleList as $example ) { echo $example -> bar ; } // retrieve the models directly instead of iterating over them $examples = $exampleList -> getObjects (); // just retrieve the number of rows $exampleCount = $exampleList -> countObjects (); DatabaseObjectList implements both SeekableIterator and Countable . Additionally, DatabaseObjectList objects has the following three public properties that are useful when fetching data with lists: $sqlLimit determines how many rows are fetched. If its value is 0 (which is the default value), all results are fetched. So be careful when dealing with large tables and you only want a limited number of rows: Set $sqlLimit to a value larger than zero! $sqlOffset : Paginated pages like a thread list use this feature a lot, it allows you to skip a given number of results. Imagine you want to display 20 threads per page but there are a total of 60 threads available. In this case you would specify $sqlLimit = 20 and $sqlOffset = 20 which will skip the first 20 threads, effectively displaying thread 21 to 40. $sqlOrderBy determines by which column(s) the rows are sorted in which order. Using our example in $sqlOffset you might want to display the 20 most recent threads on page 1, thus you should specify the order field and its direction, e.g. $sqlOrderBy = 'thread.lastPostTime DESC' which returns the most recent thread first. For more advanced usage, there two additional fields that deal with the type of objects returned. First, let's go into a bit more detail what setting the $className property actually does: It is the type of database object in which the rows are wrapped. It determines which database table is actually queried and which index is used (see the $databaseTableName and $databaseTableIndexName properties of DatabaseObject ). Sometimes you might use the database table of some database object but wrap the rows in another database object. This can be achieved by setting the $objectClassName property to the desired class name. In other cases, you might want to wrap the created objects in a database object decorator which can be done by setting the $decoratorClassName property to the desired class name: 1 2 3 <? php $exampleList = new \\wcf\\data\\example\\ExampleList (); $exampleList -> decoratorClassName = \\wcf\\data\\example\\ViewableExample :: class ; Of course, you do not have to set the property after creating the list object, you can also set it by creating a dedicated class: files/lib/data/example/ViewableExampleList.class.php 1 2 3 4 5 6 <? php namespace wcf\\data\\example ; class ViewableExampleList extends ExampleList { public $decoratorClassName = ViewableExample :: class ; }","title":"DatabaseObjectList"},{"location":"php/database-objects/#abstractdatabaseobjectaction","text":"Row creation and manipulation can be performed using the aforementioned DatabaseObjectEditor class, but this approach has two major issues: Row creation, update and deletion takes place silently without notifying any other components. Data is passed to the database adapter without any further processing. The AbstractDatabaseObjectAction solves both problems by wrapping around the editor class and thus provide an additional layer between the action that should be taken and the actual process. The first problem is solved by a fixed set of events being fired, the second issue is addressed by having a single entry point for all data editing. files/lib/data/example/ExampleAction.class.php 1 2 3 4 5 6 7 <? php namespace wcf\\data\\example ; use wcf\\data\\AbstractDatabaseObjectAction ; class ExampleAction extends AbstractDatabaseObjectAction { public $className = ExampleEditor :: class ; }","title":"AbstractDatabaseObjectAction"},{"location":"php/database-objects/#executing-an-action","text":"The method AbstractDatabaseObjectAction::validateAction() is internally used for AJAX method invocation and must not be called programmatically. The next example represents the same functionality as seen for DatabaseObjectEditor : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <? php use wcf\\data\\example\\ExampleAction ; // create a row $exampleAction = new ExampleAction ([], 'create' , [ 'data' => [ 'bar' => 'Hello World' ] ]); $example = $exampleAction -> executeAction ()[ 'returnValues' ]; // update a row using the id $exampleAction = new ExampleAction ([ 1 ], 'update' , [ 'data' => [ 'bar' => 'baz' ] ]); $exampleAction -> executeAction (); // delete a row using a model $exampleAction = new ExampleAction ([ $example ], 'delete' ); $exampleAction -> executeAction (); You can access the return values both by storing the return value of executeAction() or by retrieving it via getReturnValues() . Events initializeAction , validateAction and finalizeAction","title":"Executing an Action"},{"location":"php/database-objects/#custom-method-with-ajax-support","text":"This section is about adding the method baz() to ExampleAction and calling it via AJAX.","title":"Custom Method with AJAX Support"},{"location":"php/database-objects/#ajax-validation","text":"Methods of an action cannot be called via AJAX, unless they have a validation method. This means that ExampleAction must define both a public function baz() and public function validateBaz() , the name for the validation method is constructed by upper-casing the first character of the method name and prepending validate . The lack of the companion validate* method will cause the AJAX proxy to deny the request instantaneously. Do not add a validation method if you don't want it to be callable via AJAX ever!","title":"AJAX Validation"},{"location":"php/database-objects/#create-update-and-delete","text":"The methods create , update and delete are available for all classes deriving from AbstractDatabaseObjectAction and directly pass the input data to the DatabaseObjectEditor . These methods deny access to them via AJAX by default, unless you explicitly enable access. Depending on your case, there are two different strategies to enable AJAX access to them. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <? php namespace wcf\\data\\example ; use wcf\\data\\AbstractDatabaseObjectAction ; class ExampleAction extends AbstractDatabaseObjectAction { // `create()` can now be called via AJAX if the requesting user posses the listed permissions protected $permissionsCreate = [ 'admin.example.canManageExample' ]; public function validateUpdate () { // your very own validation logic that does not make use of the // built-in `$permissionsUpdate` property // you can still invoke the built-in permissions check if you like to parent :: validateUpdate (); } }","title":"create, update and delete"},{"location":"php/database-objects/#allow-invokation-by-guests","text":"Invoking methods is restricted to logged-in users by default and the only way to override this behavior is to alter the property $allowGuestAccess . It is a simple string array that is expected to hold all methods that should be accessible by users, excluding their companion validation methods.","title":"Allow Invokation by Guests"},{"location":"php/database-objects/#acp-access-only","text":"Method access is usually limited by permissions, but sometimes there might be the need for some added security to avoid mistakes. The $requireACP property works similar to $allowGuestAccess , but enforces the request to originate from the ACP together with a valid ACP session, ensuring that only users able to access the ACP can actually invoke these methods.","title":"ACP Access Only"},{"location":"php/exceptions/","text":"Exceptions # SPL Exceptions # The Standard PHP Library (SPL) provides some exceptions that should be used whenever possible. Custom Exceptions # Do not use wcf\\system\\exception\\SystemException anymore, use specific exception classes! The following table contains a list of custom exceptions that are commonly used. All of the exceptions are found in the wcf\\system\\exception namespace. Class name (examples) when to use IllegalLinkException access to a page that belongs to a non-existing object, executing actions on specific non-existing objects (is shown as http 404 error to the user) ImplementationException a class does not implement an expected interface InvalidObjectArgument 5.4+ API method support generic objects but specific implementation requires objects of specific (sub)class and different object is given InvalidObjectTypeException object type is not of an expected object type definition InvalidSecurityTokenException given security token does not match the security token of the active user's session ParentClassException a class does not extend an expected (parent) class PermissionDeniedException page access without permission, action execution without permission (is shown as http 403 error to the user) UserInputException user input does not pass validation Sensitive Arguments in Stack Traces # Sometimes sensitive values are passed as a function or method argument. If the callee throws an Exception, these values will be part of the Exception\u2019s stack trace and logged, unless the Exception is caught and ignored. WoltLab Suite will automatically suppress the values of parameters named like they might contain sensitive values, namely arguments matching the regular expression /(?:^(?:password|passphrase|secret)|(?:Password|Passphrase|Secret))/ . If you need to suppress additional arguments from appearing in the stack trace, you can add the \\wcf\\SensitiveArgument attribute to such parameters. Arguments are only supported as of PHP 8 and ignored as comments in lower PHP versions. In PHP 7, such arguments will not be suppressed, but the code will continue to work. Make sure to insert a linebreak between the attribute and the parameter name. Example: wcfsetup/install/files/lib/data/user/User.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php namespace wcf\\data\\user ; // \u2026 final class User extends DatabaseObject implements IPopoverObject , IRouteController , IUserContent { // \u2026 public function checkPassword ( #[\\wcf\\SensitiveArgument()] $password ) { // \u2026 } // \u2026 }","title":"Exceptions"},{"location":"php/exceptions/#exceptions","text":"","title":"Exceptions"},{"location":"php/exceptions/#spl-exceptions","text":"The Standard PHP Library (SPL) provides some exceptions that should be used whenever possible.","title":"SPL Exceptions"},{"location":"php/exceptions/#custom-exceptions","text":"Do not use wcf\\system\\exception\\SystemException anymore, use specific exception classes! The following table contains a list of custom exceptions that are commonly used. All of the exceptions are found in the wcf\\system\\exception namespace. Class name (examples) when to use IllegalLinkException access to a page that belongs to a non-existing object, executing actions on specific non-existing objects (is shown as http 404 error to the user) ImplementationException a class does not implement an expected interface InvalidObjectArgument 5.4+ API method support generic objects but specific implementation requires objects of specific (sub)class and different object is given InvalidObjectTypeException object type is not of an expected object type definition InvalidSecurityTokenException given security token does not match the security token of the active user's session ParentClassException a class does not extend an expected (parent) class PermissionDeniedException page access without permission, action execution without permission (is shown as http 403 error to the user) UserInputException user input does not pass validation","title":"Custom Exceptions"},{"location":"php/exceptions/#sensitive-arguments-in-stack-traces","text":"Sometimes sensitive values are passed as a function or method argument. If the callee throws an Exception, these values will be part of the Exception\u2019s stack trace and logged, unless the Exception is caught and ignored. WoltLab Suite will automatically suppress the values of parameters named like they might contain sensitive values, namely arguments matching the regular expression /(?:^(?:password|passphrase|secret)|(?:Password|Passphrase|Secret))/ . If you need to suppress additional arguments from appearing in the stack trace, you can add the \\wcf\\SensitiveArgument attribute to such parameters. Arguments are only supported as of PHP 8 and ignored as comments in lower PHP versions. In PHP 7, such arguments will not be suppressed, but the code will continue to work. Make sure to insert a linebreak between the attribute and the parameter name. Example: wcfsetup/install/files/lib/data/user/User.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php namespace wcf\\data\\user ; // \u2026 final class User extends DatabaseObject implements IPopoverObject , IRouteController , IUserContent { // \u2026 public function checkPassword ( #[\\wcf\\SensitiveArgument()] $password ) { // \u2026 } // \u2026 }","title":"Sensitive Arguments in Stack Traces"},{"location":"php/gdpr/","text":"General Data Protection Regulation (GDPR) # Introduction # The General Data Protection Regulation (GDPR) of the European Union enters into force on May 25, 2018. It comes with a set of restrictions when handling users' personal data as well as to provide an interface to export this data on demand. If you're looking for a guide on the implications of the GDPR and what you will need or consider to do, please read the article Implementation of the GDPR on woltlab.com. Including Data in the Export # The wcf\\acp\\action\\UserExportGdprAction already includes WoltLab Suite Core itself as well as all official apps, but you'll need to include any personal data stored for your plugin or app by yourself. The event export is fired before any data is sent out, but after any Core data has been dumped to the $data property. Example code # files/lib/system/event/listener/MyUserExportGdprActionListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\action\\UserExportGdprAction ; use wcf\\data\\user\\UserProfile ; class MyUserExportGdprActionListener implements IParameterizedEventListener { public function execute ( /** @var UserExportGdprAction $eventObj */ $eventObj , $className , $eventName , array & $parameters ) { /** @var UserProfile $user */ $user = $eventObj -> user ; $eventObj -> data [ 'my.fancy.plugin' ] = [ 'superPersonalData' => \"This text is super personal and should be included in the output\" , 'weirdIpAddresses' => $eventObj -> exportIpAddresses ( 'app' . WCF_N . '_non_standard_column_names_for_ip_addresses' , 'ipAddressColumnName' , 'timeColumnName' , 'userIDColumnName' ) ]; $eventObj -> exportUserProperties [] = 'shouldAlwaysExportThisField' ; $eventObj -> exportUserPropertiesIfNotEmpty [] = 'myFancyField' ; $eventObj -> exportUserOptionSettings [] = 'thisSettingIsAlwaysExported' ; $eventObj -> exportUserOptionSettingsIfNotEmpty [] = 'someSettingContainingPersonalData' ; $eventObj -> ipAddresses [ 'my.fancy.plugin' ] = [ 'wcf' . WCF_N . '_my_fancy_table' , 'wcf' . WCF_N . '_i_also_store_ipaddresses_here' ]; $eventObj -> skipUserOptions [] = 'thisLooksLikePersonalDataButItIsNot' ; $eventObj -> skipUserOptions [] = 'thisIsAlsoNotPersonalDataPleaseIgnoreIt' ; } } $data # Contains the entire data that will be included in the exported JSON file, some fields may already exist (such as 'com.woltlab.wcf' ) and while you may add or edit any fields within, you should restrict yourself to only append data from your plugin or app. $exportUserProperties # Only a whitelist of columns in wcfN_user is exported by default, if your plugin or app adds one or more columns to this table that do hold personal data, then you will have to append it to this array. The listed properties will always be included regardless of their content. $exportUserPropertiesIfNotEmpty # Only a whitelist of columns in wcfN_user is exported by default, if your plugin or app adds one or more columns to this table that do hold personal data, then you will have to append it to this array. Empty values will not be added to the output. $exportUserOptionSettings # Any user option that exists within a settings.* category is automatically excluded from the export, with the notable exception of the timezone option. You can opt-in to include your setting by appending to this array, if it contains any personal data. The listed settings are always included regardless of their content. $exportUserOptionSettingsIfNotEmpty # Any user option that exists within a settings.* category is automatically excluded from the export, with the notable exception of the timezone option. You can opt-in to include your setting by appending to this array, if it contains any personal data. $ipAddresses # List of database table names per package identifier that contain ip addresses. The contained ip addresses will be exported when the ip logging module is enabled. It expects the database table to use the column names ipAddress , time and userID . If your table does not match this pattern for whatever reason, you'll need to manually probe for LOG_IP_ADDRESS and then call exportIpAddresses() to retrieve the list. Afterwards you are responsible to append these ip addresses to the $data array to have it exported. $skipUserOptions # All user options are included in the export by default, unless they start with can* or admin* , or are blacklisted using this array. You should append any of your plugin's or app's user option that should not be exported, for example because it does not contain personal data, such as internal data.","title":"GDPR"},{"location":"php/gdpr/#general-data-protection-regulation-gdpr","text":"","title":"General Data Protection Regulation (GDPR)"},{"location":"php/gdpr/#introduction","text":"The General Data Protection Regulation (GDPR) of the European Union enters into force on May 25, 2018. It comes with a set of restrictions when handling users' personal data as well as to provide an interface to export this data on demand. If you're looking for a guide on the implications of the GDPR and what you will need or consider to do, please read the article Implementation of the GDPR on woltlab.com.","title":"Introduction"},{"location":"php/gdpr/#including-data-in-the-export","text":"The wcf\\acp\\action\\UserExportGdprAction already includes WoltLab Suite Core itself as well as all official apps, but you'll need to include any personal data stored for your plugin or app by yourself. The event export is fired before any data is sent out, but after any Core data has been dumped to the $data property.","title":"Including Data in the Export"},{"location":"php/gdpr/#example-code","text":"files/lib/system/event/listener/MyUserExportGdprActionListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\action\\UserExportGdprAction ; use wcf\\data\\user\\UserProfile ; class MyUserExportGdprActionListener implements IParameterizedEventListener { public function execute ( /** @var UserExportGdprAction $eventObj */ $eventObj , $className , $eventName , array & $parameters ) { /** @var UserProfile $user */ $user = $eventObj -> user ; $eventObj -> data [ 'my.fancy.plugin' ] = [ 'superPersonalData' => \"This text is super personal and should be included in the output\" , 'weirdIpAddresses' => $eventObj -> exportIpAddresses ( 'app' . WCF_N . '_non_standard_column_names_for_ip_addresses' , 'ipAddressColumnName' , 'timeColumnName' , 'userIDColumnName' ) ]; $eventObj -> exportUserProperties [] = 'shouldAlwaysExportThisField' ; $eventObj -> exportUserPropertiesIfNotEmpty [] = 'myFancyField' ; $eventObj -> exportUserOptionSettings [] = 'thisSettingIsAlwaysExported' ; $eventObj -> exportUserOptionSettingsIfNotEmpty [] = 'someSettingContainingPersonalData' ; $eventObj -> ipAddresses [ 'my.fancy.plugin' ] = [ 'wcf' . WCF_N . '_my_fancy_table' , 'wcf' . WCF_N . '_i_also_store_ipaddresses_here' ]; $eventObj -> skipUserOptions [] = 'thisLooksLikePersonalDataButItIsNot' ; $eventObj -> skipUserOptions [] = 'thisIsAlsoNotPersonalDataPleaseIgnoreIt' ; } }","title":"Example code"},{"location":"php/gdpr/#data","text":"Contains the entire data that will be included in the exported JSON file, some fields may already exist (such as 'com.woltlab.wcf' ) and while you may add or edit any fields within, you should restrict yourself to only append data from your plugin or app.","title":"$data"},{"location":"php/gdpr/#exportuserproperties","text":"Only a whitelist of columns in wcfN_user is exported by default, if your plugin or app adds one or more columns to this table that do hold personal data, then you will have to append it to this array. The listed properties will always be included regardless of their content.","title":"$exportUserProperties"},{"location":"php/gdpr/#exportuserpropertiesifnotempty","text":"Only a whitelist of columns in wcfN_user is exported by default, if your plugin or app adds one or more columns to this table that do hold personal data, then you will have to append it to this array. Empty values will not be added to the output.","title":"$exportUserPropertiesIfNotEmpty"},{"location":"php/gdpr/#exportuseroptionsettings","text":"Any user option that exists within a settings.* category is automatically excluded from the export, with the notable exception of the timezone option. You can opt-in to include your setting by appending to this array, if it contains any personal data. The listed settings are always included regardless of their content.","title":"$exportUserOptionSettings"},{"location":"php/gdpr/#exportuseroptionsettingsifnotempty","text":"Any user option that exists within a settings.* category is automatically excluded from the export, with the notable exception of the timezone option. You can opt-in to include your setting by appending to this array, if it contains any personal data.","title":"$exportUserOptionSettingsIfNotEmpty"},{"location":"php/gdpr/#ipaddresses","text":"List of database table names per package identifier that contain ip addresses. The contained ip addresses will be exported when the ip logging module is enabled. It expects the database table to use the column names ipAddress , time and userID . If your table does not match this pattern for whatever reason, you'll need to manually probe for LOG_IP_ADDRESS and then call exportIpAddresses() to retrieve the list. Afterwards you are responsible to append these ip addresses to the $data array to have it exported.","title":"$ipAddresses"},{"location":"php/gdpr/#skipuseroptions","text":"All user options are included in the export by default, unless they start with can* or admin* , or are blacklisted using this array. You should append any of your plugin's or app's user option that should not be exported, for example because it does not contain personal data, such as internal data.","title":"$skipUserOptions"},{"location":"php/pages/","text":"Page Types # AbstractPage # The default implementation for pages to present any sort of content, but are designed to handle GET requests only. They usually follow a fixed method chain that will be invoked one after another, adding logical sections to the request flow. Method Chain # __run() # This is the only method being invoked from the outside and starts the whole chain. readParameters() # Reads and sanitizes request parameters, this should be the only method to ever read user-supplied input. Read data should be stored in class properties to be accessible at a later point, allowing your code to safely assume that the data has been sanitized and is safe to work with. A typical example is the board page from the forum app that reads the id and attempts to identify the request forum. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) $this -> boardID = intval ( $_REQUEST [ 'id' ]); $this -> board = BoardCache :: getInstance () -> getBoard ( $this -> boardID ); if ( $this -> board === null ) { throw new IllegalLinkException (); } // check permissions if ( ! $this -> board -> canEnter ()) { throw new PermissionDeniedException (); } } Events readParameters show() # Used to be the method of choice to handle permissions and module option checks, but has been used almost entirely as an internal method since the introduction of the properties $loginRequired , $neededModules and $neededPermissions . Events checkModules , checkPermissions and show readData() # Central method for data retrieval based on class properties including those populated with user data in readParameters() . It is strongly recommended to use this method to read data in order to properly separate the business logic present in your class. Events readData assignVariables() # Last method call before the template engine kicks in and renders the template. All though some properties are bound to the template automatically, you still need to pass any custom variables and class properties to the engine to make them available in templates. Following the example in readParameters() , the code below adds the board data to the template. 1 2 3 4 5 6 7 8 public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'board' => $this -> board , 'boardID' => $this -> boardID ]); } Events assignVariables AbstractForm # Extends the AbstractPage implementation with additional methods designed to handle form submissions properly. Method Chain # __run() # Inherited from AbstractPage. readParameters() # Inherited from AbstractPage. show() # Inherited from AbstractPage. submit() # The methods submit() up until save() are only invoked if either $_POST or $_FILES are not empty, otherwise they won't be invoked and the execution will continue with readData() . This is an internal method that is responsible of input processing and validation. Events submit readFormParameters() # This method is quite similar to readParameters() that is being called earlier, but is designed around reading form data submitted through POST requests. You should avoid accessing $_GET or $_REQUEST in this context to avoid mixing up parameters evaluated when retrieving the page on first load and when submitting to it. Events readFormParameters validate() # Deals with input validation and automatically catches exceptions deriving from wcf\\system\\exception\\UserInputException , resulting in a clean and consistent error handling for the user. Events validate save() # Saves the processed data to database or any other source of your choice. Please keep in mind to invoke $this->saved() before resetting the form data. Events save saved() # This method is not called automatically and must be invoked manually by executing $this->saved() inside save() . The only purpose of this method is to fire the event saved that signals that the form data has been processed successfully and data has been saved. It is somewhat special as it is dispatched after the data has been saved, but before the data is purged during form reset. This is by default the last event that has access to the processed data. Events saved readData() # Inherited from AbstractPage. assignVariables() # Inherited from AbstractPage.","title":"Pages"},{"location":"php/pages/#page-types","text":"","title":"Page Types"},{"location":"php/pages/#abstractpage","text":"The default implementation for pages to present any sort of content, but are designed to handle GET requests only. They usually follow a fixed method chain that will be invoked one after another, adding logical sections to the request flow.","title":"AbstractPage"},{"location":"php/pages/#method-chain","text":"","title":"Method Chain"},{"location":"php/pages/#__run","text":"This is the only method being invoked from the outside and starts the whole chain.","title":"__run()"},{"location":"php/pages/#readparameters","text":"Reads and sanitizes request parameters, this should be the only method to ever read user-supplied input. Read data should be stored in class properties to be accessible at a later point, allowing your code to safely assume that the data has been sanitized and is safe to work with. A typical example is the board page from the forum app that reads the id and attempts to identify the request forum. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) $this -> boardID = intval ( $_REQUEST [ 'id' ]); $this -> board = BoardCache :: getInstance () -> getBoard ( $this -> boardID ); if ( $this -> board === null ) { throw new IllegalLinkException (); } // check permissions if ( ! $this -> board -> canEnter ()) { throw new PermissionDeniedException (); } } Events readParameters","title":"readParameters()"},{"location":"php/pages/#show","text":"Used to be the method of choice to handle permissions and module option checks, but has been used almost entirely as an internal method since the introduction of the properties $loginRequired , $neededModules and $neededPermissions . Events checkModules , checkPermissions and show","title":"show()"},{"location":"php/pages/#readdata","text":"Central method for data retrieval based on class properties including those populated with user data in readParameters() . It is strongly recommended to use this method to read data in order to properly separate the business logic present in your class. Events readData","title":"readData()"},{"location":"php/pages/#assignvariables","text":"Last method call before the template engine kicks in and renders the template. All though some properties are bound to the template automatically, you still need to pass any custom variables and class properties to the engine to make them available in templates. Following the example in readParameters() , the code below adds the board data to the template. 1 2 3 4 5 6 7 8 public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'board' => $this -> board , 'boardID' => $this -> boardID ]); } Events assignVariables","title":"assignVariables()"},{"location":"php/pages/#abstractform","text":"Extends the AbstractPage implementation with additional methods designed to handle form submissions properly.","title":"AbstractForm"},{"location":"php/pages/#method-chain_1","text":"","title":"Method Chain"},{"location":"php/pages/#__run_1","text":"Inherited from AbstractPage.","title":"__run()"},{"location":"php/pages/#readparameters_1","text":"Inherited from AbstractPage.","title":"readParameters()"},{"location":"php/pages/#show_1","text":"Inherited from AbstractPage.","title":"show()"},{"location":"php/pages/#submit","text":"The methods submit() up until save() are only invoked if either $_POST or $_FILES are not empty, otherwise they won't be invoked and the execution will continue with readData() . This is an internal method that is responsible of input processing and validation. Events submit","title":"submit()"},{"location":"php/pages/#readformparameters","text":"This method is quite similar to readParameters() that is being called earlier, but is designed around reading form data submitted through POST requests. You should avoid accessing $_GET or $_REQUEST in this context to avoid mixing up parameters evaluated when retrieving the page on first load and when submitting to it. Events readFormParameters","title":"readFormParameters()"},{"location":"php/pages/#validate","text":"Deals with input validation and automatically catches exceptions deriving from wcf\\system\\exception\\UserInputException , resulting in a clean and consistent error handling for the user. Events validate","title":"validate()"},{"location":"php/pages/#save","text":"Saves the processed data to database or any other source of your choice. Please keep in mind to invoke $this->saved() before resetting the form data. Events save","title":"save()"},{"location":"php/pages/#saved","text":"This method is not called automatically and must be invoked manually by executing $this->saved() inside save() . The only purpose of this method is to fire the event saved that signals that the form data has been processed successfully and data has been saved. It is somewhat special as it is dispatched after the data has been saved, but before the data is purged during form reset. This is by default the last event that has access to the processed data. Events saved","title":"saved()"},{"location":"php/pages/#readdata_1","text":"Inherited from AbstractPage.","title":"readData()"},{"location":"php/pages/#assignvariables_1","text":"Inherited from AbstractPage.","title":"assignVariables()"},{"location":"php/api/caches/","text":"Caches # WoltLab Suite offers two distinct types of caches: Persistent caches created by cache builders whose data can be stored using different cache sources. Runtime caches store objects for the duration of a single request. Understanding Caching # Every so often, plugins make use of cache builders or runtime caches to store their data, even if there is absolutely no need for them to do so. Usually, this involves a strong opinion about the total number of SQL queries on a page, including but not limited to some magic treshold numbers, which should not be exceeded for \"performance reasons\". This misconception can easily lead into thinking that SQL queries should be avoided or at least written to a cache, so that it doesn't need to be executed so often. Unfortunately, this completely ignores the fact that both a single query can take down your app (e. g. full table scan on millions of rows), but 10 queries using a primary key on a table with a few hundred rows will not slow down your page. There are some queries that should go into caches by design, but most of the cache builders weren't initially there, but instead have been added because they were required to reduce the load significantly . You need to understand that caches always come at a cost, even a runtime cache does! In particular, they will always consume memory that is not released over the duration of the request lifecycle and potentially even leak memory by holding references to objects and data structures that are no longer required. Caching should always be a solution for a problem. When to Use a Cache # It's difficult to provide a definite answer or checklist when to use a cache and why it is required at this point, because the answer is: It depends. The permission cache for user groups is a good example for a valid cache, where we can achieve significant performance improvement compared to processing this data on every request. Its caches are build for each permutation of user group memberships that are encountered for a page request. Building this data is an expensive process that involves both inheritance and specific rules in regards to when a value for a permission overrules another value. The added benefit of this cache is that one cache usually serves a large number of users with the same group memberships and by computing these permissions once, we can serve many different requests. Also, the permissions are rather static values that change very rarely and thus we can expect a very high cache lifetime before it gets rebuild. When not to Use a Cache # I remember, a few years ago, there was a plugin that displayed a user's character from an online video game. The character sheet not only included a list of basic statistics, but also displayed the items that this character was wearing and or holding at the time. The data for these items were downloaded in bulk from the game's vendor servers and stored in a persistent cache file that periodically gets renewed. There is nothing wrong with the idea of caching the data on your own server rather than requesting them everytime from the vendor's servers - not only because they imposed a limit on the number of requests per hour. Unfortunately, the character sheet had a sub-par performance and the users were upset by the significant loading times compared to literally every other page on the same server. The author of the plugin was working hard to resolve this issue and was evaluating all kind of methods to improve the page performance, including deep-diving into the realm of micro-optimizations to squeeze out every last bit of performance that is possible. The real problem was the cache file itself, it turns out that it was holding the data for several thousand items with a total file size of about 13 megabytes. It doesn't look that much at first glance, after all this isn't the '90s anymore, but unserializing a 13 megabyte array is really slow and looking up items in such a large array isn't exactly fast either. The solution was rather simple, the data that was fetched from the vendor's API was instead written into a separate database table. Next, the persistent cache was removed and the character sheet would now request the item data for that specific character straight from the database. Previously, the character sheet took several seconds to load and after the change it was done in a fraction of a second. Although quite extreme, this illustrates a situation where the cache file was introduced in the design process, without evaluating if the cache - at least how it was implemented - was really necessary. Caching should always be a solution for a problem. Not the other way around.","title":"Overview"},{"location":"php/api/caches/#caches","text":"WoltLab Suite offers two distinct types of caches: Persistent caches created by cache builders whose data can be stored using different cache sources. Runtime caches store objects for the duration of a single request.","title":"Caches"},{"location":"php/api/caches/#understanding-caching","text":"Every so often, plugins make use of cache builders or runtime caches to store their data, even if there is absolutely no need for them to do so. Usually, this involves a strong opinion about the total number of SQL queries on a page, including but not limited to some magic treshold numbers, which should not be exceeded for \"performance reasons\". This misconception can easily lead into thinking that SQL queries should be avoided or at least written to a cache, so that it doesn't need to be executed so often. Unfortunately, this completely ignores the fact that both a single query can take down your app (e. g. full table scan on millions of rows), but 10 queries using a primary key on a table with a few hundred rows will not slow down your page. There are some queries that should go into caches by design, but most of the cache builders weren't initially there, but instead have been added because they were required to reduce the load significantly . You need to understand that caches always come at a cost, even a runtime cache does! In particular, they will always consume memory that is not released over the duration of the request lifecycle and potentially even leak memory by holding references to objects and data structures that are no longer required. Caching should always be a solution for a problem.","title":"Understanding Caching"},{"location":"php/api/caches/#when-to-use-a-cache","text":"It's difficult to provide a definite answer or checklist when to use a cache and why it is required at this point, because the answer is: It depends. The permission cache for user groups is a good example for a valid cache, where we can achieve significant performance improvement compared to processing this data on every request. Its caches are build for each permutation of user group memberships that are encountered for a page request. Building this data is an expensive process that involves both inheritance and specific rules in regards to when a value for a permission overrules another value. The added benefit of this cache is that one cache usually serves a large number of users with the same group memberships and by computing these permissions once, we can serve many different requests. Also, the permissions are rather static values that change very rarely and thus we can expect a very high cache lifetime before it gets rebuild.","title":"When to Use a Cache"},{"location":"php/api/caches/#when-not-to-use-a-cache","text":"I remember, a few years ago, there was a plugin that displayed a user's character from an online video game. The character sheet not only included a list of basic statistics, but also displayed the items that this character was wearing and or holding at the time. The data for these items were downloaded in bulk from the game's vendor servers and stored in a persistent cache file that periodically gets renewed. There is nothing wrong with the idea of caching the data on your own server rather than requesting them everytime from the vendor's servers - not only because they imposed a limit on the number of requests per hour. Unfortunately, the character sheet had a sub-par performance and the users were upset by the significant loading times compared to literally every other page on the same server. The author of the plugin was working hard to resolve this issue and was evaluating all kind of methods to improve the page performance, including deep-diving into the realm of micro-optimizations to squeeze out every last bit of performance that is possible. The real problem was the cache file itself, it turns out that it was holding the data for several thousand items with a total file size of about 13 megabytes. It doesn't look that much at first glance, after all this isn't the '90s anymore, but unserializing a 13 megabyte array is really slow and looking up items in such a large array isn't exactly fast either. The solution was rather simple, the data that was fetched from the vendor's API was instead written into a separate database table. Next, the persistent cache was removed and the character sheet would now request the item data for that specific character straight from the database. Previously, the character sheet took several seconds to load and after the change it was done in a fraction of a second. Although quite extreme, this illustrates a situation where the cache file was introduced in the design process, without evaluating if the cache - at least how it was implemented - was really necessary. Caching should always be a solution for a problem. Not the other way around.","title":"When not to Use a Cache"},{"location":"php/api/caches_persistent-caches/","text":"Persistent Caches # Relational databases are designed around the principle of normalized data that is organized across clearly separated tables with defined releations between data rows. While this enables you to quickly access and modify individual rows and columns, it can create the problem that re-assembling this data into a more complex structure can be quite expensive. For example, the user group permissions are stored for each user group and each permissions separately, but in order to be applied, they need to be fetched and the cumulative values across all user groups of an user have to be calculated. These repetitive tasks on barely ever changing data make them an excellent target for caching, where all sub-sequent requests are accelerated because they no longer have to perform the same expensive calculations every time. It is easy to get lost in the realm of caching, especially when it comes to the decision if you should use a cache or not. When in doubt, you should opt to not use them, because they also come at a hidden cost that cannot be expressed through simple SQL query counts. If you haven't already, it is recommended that you read the introduction article on caching first, it provides a bit of background on caches and examples that should help you in your decision. AbstractCacheBuilder # Every cache builder should derive from the base class AbstractCacheBuilder that already implements the mandatory interface ICacheBuilder . files/lib/system/cache/builder/ExampleCacheBuilder.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php namespace wcf\\system\\cache\\builder ; class ExampleCacheBuilder extends AbstractCacheBuilder { // 3600 = 1hr protected $maxLifetime = 3600 ; public function rebuild ( array $parameters ) { $data = []; // fetch and process your data and assign it to `$data` return $data ; } } Reading data from your cache builder is quite simple and follows a consistent pattern. The callee only needs to know the name of the cache builder, which parameters it requires and how the returned data looks like. It does not need to know how the data is retrieve, where it was stored, nor if it had to be rebuild due to the maximum lifetime. 1 2 3 4 <? php use wcf\\system\\cache\\builder\\ExampleCacheBuilder ; $data = ExampleCacheBuilder :: getInstance () -> getData ( $parameters ); getData(array $parameters = [], string $arrayIndex = ''): array # Retrieves the data from the cache builder, the $parameters array is automatically sorted to allow sub-sequent requests for the same parameters to be recognized, even if their parameters are mixed. For example, getData([1, 2]) and getData([2, 1]) will have the same exact result. The optional $arrayIndex will instruct the cache builder to retrieve the data and examine if the returned data is an array that has the index $arrayIndex . If it is set, the potion below this index is returned instead. getMaxLifetime(): int # Returns the maximum lifetime of a cache in seconds. It can be controlled through the protected $maxLifetime property which defaults to 0 . Any cache that has a lifetime greater than 0 is automatically discarded when exceeding this age, otherwise it will remain forever until it is explicitly removed or invalidated. reset(array $parameters = []): void # Invalidates a cache, the $parameters array will again be ordered using the same rules that are applied for getData() . rebuild(array $parameters): array # This method is protected. This is the only method that a cache builder deriving from AbstractCacheBuilder has to implement and it will be invoked whenever the cache is required to be rebuild for whatever reason.","title":"Persistent Caches"},{"location":"php/api/caches_persistent-caches/#persistent-caches","text":"Relational databases are designed around the principle of normalized data that is organized across clearly separated tables with defined releations between data rows. While this enables you to quickly access and modify individual rows and columns, it can create the problem that re-assembling this data into a more complex structure can be quite expensive. For example, the user group permissions are stored for each user group and each permissions separately, but in order to be applied, they need to be fetched and the cumulative values across all user groups of an user have to be calculated. These repetitive tasks on barely ever changing data make them an excellent target for caching, where all sub-sequent requests are accelerated because they no longer have to perform the same expensive calculations every time. It is easy to get lost in the realm of caching, especially when it comes to the decision if you should use a cache or not. When in doubt, you should opt to not use them, because they also come at a hidden cost that cannot be expressed through simple SQL query counts. If you haven't already, it is recommended that you read the introduction article on caching first, it provides a bit of background on caches and examples that should help you in your decision.","title":"Persistent Caches"},{"location":"php/api/caches_persistent-caches/#abstractcachebuilder","text":"Every cache builder should derive from the base class AbstractCacheBuilder that already implements the mandatory interface ICacheBuilder . files/lib/system/cache/builder/ExampleCacheBuilder.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <? php namespace wcf\\system\\cache\\builder ; class ExampleCacheBuilder extends AbstractCacheBuilder { // 3600 = 1hr protected $maxLifetime = 3600 ; public function rebuild ( array $parameters ) { $data = []; // fetch and process your data and assign it to `$data` return $data ; } } Reading data from your cache builder is quite simple and follows a consistent pattern. The callee only needs to know the name of the cache builder, which parameters it requires and how the returned data looks like. It does not need to know how the data is retrieve, where it was stored, nor if it had to be rebuild due to the maximum lifetime. 1 2 3 4 <? php use wcf\\system\\cache\\builder\\ExampleCacheBuilder ; $data = ExampleCacheBuilder :: getInstance () -> getData ( $parameters );","title":"AbstractCacheBuilder"},{"location":"php/api/caches_persistent-caches/#getdataarray-parameters-string-arrayindex-array","text":"Retrieves the data from the cache builder, the $parameters array is automatically sorted to allow sub-sequent requests for the same parameters to be recognized, even if their parameters are mixed. For example, getData([1, 2]) and getData([2, 1]) will have the same exact result. The optional $arrayIndex will instruct the cache builder to retrieve the data and examine if the returned data is an array that has the index $arrayIndex . If it is set, the potion below this index is returned instead.","title":"getData(array $parameters = [], string $arrayIndex = ''): array"},{"location":"php/api/caches_persistent-caches/#getmaxlifetime-int","text":"Returns the maximum lifetime of a cache in seconds. It can be controlled through the protected $maxLifetime property which defaults to 0 . Any cache that has a lifetime greater than 0 is automatically discarded when exceeding this age, otherwise it will remain forever until it is explicitly removed or invalidated.","title":"getMaxLifetime(): int"},{"location":"php/api/caches_persistent-caches/#resetarray-parameters-void","text":"Invalidates a cache, the $parameters array will again be ordered using the same rules that are applied for getData() .","title":"reset(array $parameters = []): void"},{"location":"php/api/caches_persistent-caches/#rebuildarray-parameters-array","text":"This method is protected. This is the only method that a cache builder deriving from AbstractCacheBuilder has to implement and it will be invoked whenever the cache is required to be rebuild for whatever reason.","title":"rebuild(array $parameters): array"},{"location":"php/api/caches_runtime-caches/","text":"Runtime Caches # Runtime caches store objects created during the runtime of the script and are automatically discarded after the script terminates. Runtime caches are especially useful when objects are fetched by different APIs, each requiring separate requests. By using a runtime cache, you have two advantages: If the API allows it, you can delay fetching the actual objects and initially only tell the runtime cache that at some point in the future of the current request, you need the objects with the given ids. If multiple APIs do this one after another, all objects can be fetched using only one query instead of each API querying the database on its own. If an object with the same ID has already been fetched from database, this object is simply returned and can be reused instead of being fetched from database again. IRuntimeCache # Every runtime cache has to implement the IRuntimeCache interface. It is recommended, however, that you extend AbstractRuntimeCache , the default implementation of the runtime cache interface. In most instances, you only need to set the AbstractRuntimeCache::$listClassName property to the name of database object list class which fetches the cached objects from database (see example ). Usage # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <? php use wcf\\system\\cache\\runtime\\UserRuntimeCache ; $userIDs = [ 1 , 2 ]; // first (optional) step: tell runtime cache to remember user ids UserRuntimeCache :: getInstance () -> cacheObjectIDs ( $userIDs ); // [\u2026] // second step: fetch the objects from database $users = UserRuntimeCache :: getInstance () -> getObjects ( $userIDs ); // somewhere else: fetch only one user $userID = 1 ; UserRuntimeCache :: getInstance () -> cacheObjectID ( $userID ); // [\u2026] // get user without the cache actually fetching it from database because it has already been loaded $user = UserRuntimeCache :: getInstance () -> getObject ( $userID ); // somewhere else: fetch users directly without caching user ids first $users = UserRuntimeCache :: getInstance () -> getObjects ([ 3 , 4 ]); Example # files/lib/system/cache/runtime/UserRuntimeCache.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? php namespace wcf\\system\\cache\\runtime ; use wcf\\data\\user\\User ; use wcf\\data\\user\\UserList ; /** * Runtime cache implementation for users. * * @author Matthias Schmidt * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cache\\Runtime * @since 3.0 * * @method User[] getCachedObjects() * @method User getObject($objectID) * @method User[] getObjects(array $objectIDs) */ class UserRuntimeCache extends AbstractRuntimeCache { /** * @inheritDoc */ protected $listClassName = UserList :: class ; }","title":"Runtime Caches"},{"location":"php/api/caches_runtime-caches/#runtime-caches","text":"Runtime caches store objects created during the runtime of the script and are automatically discarded after the script terminates. Runtime caches are especially useful when objects are fetched by different APIs, each requiring separate requests. By using a runtime cache, you have two advantages: If the API allows it, you can delay fetching the actual objects and initially only tell the runtime cache that at some point in the future of the current request, you need the objects with the given ids. If multiple APIs do this one after another, all objects can be fetched using only one query instead of each API querying the database on its own. If an object with the same ID has already been fetched from database, this object is simply returned and can be reused instead of being fetched from database again.","title":"Runtime Caches"},{"location":"php/api/caches_runtime-caches/#iruntimecache","text":"Every runtime cache has to implement the IRuntimeCache interface. It is recommended, however, that you extend AbstractRuntimeCache , the default implementation of the runtime cache interface. In most instances, you only need to set the AbstractRuntimeCache::$listClassName property to the name of database object list class which fetches the cached objects from database (see example ).","title":"IRuntimeCache"},{"location":"php/api/caches_runtime-caches/#usage","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <? php use wcf\\system\\cache\\runtime\\UserRuntimeCache ; $userIDs = [ 1 , 2 ]; // first (optional) step: tell runtime cache to remember user ids UserRuntimeCache :: getInstance () -> cacheObjectIDs ( $userIDs ); // [\u2026] // second step: fetch the objects from database $users = UserRuntimeCache :: getInstance () -> getObjects ( $userIDs ); // somewhere else: fetch only one user $userID = 1 ; UserRuntimeCache :: getInstance () -> cacheObjectID ( $userID ); // [\u2026] // get user without the cache actually fetching it from database because it has already been loaded $user = UserRuntimeCache :: getInstance () -> getObject ( $userID ); // somewhere else: fetch users directly without caching user ids first $users = UserRuntimeCache :: getInstance () -> getObjects ([ 3 , 4 ]);","title":"Usage"},{"location":"php/api/caches_runtime-caches/#example","text":"files/lib/system/cache/runtime/UserRuntimeCache.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? php namespace wcf\\system\\cache\\runtime ; use wcf\\data\\user\\User ; use wcf\\data\\user\\UserList ; /** * Runtime cache implementation for users. * * @author Matthias Schmidt * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cache\\Runtime * @since 3.0 * * @method User[] getCachedObjects() * @method User getObject($objectID) * @method User[] getObjects(array $objectIDs) */ class UserRuntimeCache extends AbstractRuntimeCache { /** * @inheritDoc */ protected $listClassName = UserList :: class ; }","title":"Example"},{"location":"php/api/comments/","text":"Comments # User Group Options # You need to create the following permissions: user group type permission type naming user creating comments user.foo.canAddComment user editing own comments user.foo.canEditComment user deleting own comments user.foo.canDeleteComment moderator moderating comments mod.foo.canModerateComment moderator editing comments mod.foo.canEditComment moderator deleting comments mod.foo.canDeleteComment Within their respective user group option category, the options should be listed in the same order as in the table above. Language Items # User Group Options # The language items for the comment-related user group options generally have the same values: wcf.acp.group.option.user.foo.canAddComment German: Kann Kommentare erstellen English: Can create comments wcf.acp.group.option.user.foo.canEditComment German: Kann eigene Kommentare bearbeiten English: Can edit their comments wcf.acp.group.option.user.foo.canDeleteComment German: Kann eigene Kommentare l\u00f6schen English: Can delete their comments wcf.acp.group.option.mod.foo.canModerateComment German: Kann Kommentare moderieren English: Can moderate comments wcf.acp.group.option.mod.foo.canEditComment German: Kann Kommentare bearbeiten English: Can edit comments wcf.acp.group.option.mod.foo.canDeleteComment German: Kann Kommentare l\u00f6schen English: Can delete comments","title":"Comments"},{"location":"php/api/comments/#comments","text":"","title":"Comments"},{"location":"php/api/comments/#user-group-options","text":"You need to create the following permissions: user group type permission type naming user creating comments user.foo.canAddComment user editing own comments user.foo.canEditComment user deleting own comments user.foo.canDeleteComment moderator moderating comments mod.foo.canModerateComment moderator editing comments mod.foo.canEditComment moderator deleting comments mod.foo.canDeleteComment Within their respective user group option category, the options should be listed in the same order as in the table above.","title":"User Group Options"},{"location":"php/api/comments/#language-items","text":"","title":"Language Items"},{"location":"php/api/comments/#user-group-options_1","text":"The language items for the comment-related user group options generally have the same values: wcf.acp.group.option.user.foo.canAddComment German: Kann Kommentare erstellen English: Can create comments wcf.acp.group.option.user.foo.canEditComment German: Kann eigene Kommentare bearbeiten English: Can edit their comments wcf.acp.group.option.user.foo.canDeleteComment German: Kann eigene Kommentare l\u00f6schen English: Can delete their comments wcf.acp.group.option.mod.foo.canModerateComment German: Kann Kommentare moderieren English: Can moderate comments wcf.acp.group.option.mod.foo.canEditComment German: Kann Kommentare bearbeiten English: Can edit comments wcf.acp.group.option.mod.foo.canDeleteComment German: Kann Kommentare l\u00f6schen English: Can delete comments","title":"User Group Options"},{"location":"php/api/cronjobs/","text":"Cronjobs # Cronjobs offer an easy way to execute actions periodically, like cleaning up the database. The execution of cronjobs is not guaranteed but requires someone to access the page with JavaScript enabled. This page focuses on the technical aspects of cronjobs, the cronjob package installation plugin page covers how you can actually register a cronjob. Example # files/lib/system/cronjob/LastActivityCronjob.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <? php namespace wcf\\system\\cronjob ; use wcf\\data\\cronjob\\Cronjob ; use wcf\\system\\WCF ; /** * Updates the last activity timestamp in the user table. * * @author Marcel Werk * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cronjob */ class LastActivityCronjob extends AbstractCronjob { /** * @inheritDoc */ public function execute ( Cronjob $cronjob ) { parent :: execute ( $cronjob ); $sql = \"UPDATE wcf\" . WCF_N . \"_user user_table, wcf\" . WCF_N . \"_session session SET user_table.lastActivityTime = session.lastActivityTime WHERE user_table.userID = session.userID AND session.userID <> 0\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); } } ICronjob Interface # Every cronjob needs to implement the wcf\\system\\cronjob\\ICronjob interface which requires the execute(Cronjob $cronjob) method to be implemented. This method is called by wcf\\system\\cronjob\\CronjobScheduler when executing the cronjobs. In practice, however, you should extend the AbstractCronjob class and also call the AbstractCronjob::execute() method as it fires an event which makes cronjobs extendable by plugins (see event documentation ). Executing Cronjobs Through CLI # Cronjobs can be executed through the command-line interface (CLI): 1 2 3 4 5 php /path/to/wcf/cli.php << 'EOT' USERNAME PASSWORD cronjob execute EOT","title":"Cronjobs"},{"location":"php/api/cronjobs/#cronjobs","text":"Cronjobs offer an easy way to execute actions periodically, like cleaning up the database. The execution of cronjobs is not guaranteed but requires someone to access the page with JavaScript enabled. This page focuses on the technical aspects of cronjobs, the cronjob package installation plugin page covers how you can actually register a cronjob.","title":"Cronjobs"},{"location":"php/api/cronjobs/#example","text":"files/lib/system/cronjob/LastActivityCronjob.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <? php namespace wcf\\system\\cronjob ; use wcf\\data\\cronjob\\Cronjob ; use wcf\\system\\WCF ; /** * Updates the last activity timestamp in the user table. * * @author Marcel Werk * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cronjob */ class LastActivityCronjob extends AbstractCronjob { /** * @inheritDoc */ public function execute ( Cronjob $cronjob ) { parent :: execute ( $cronjob ); $sql = \"UPDATE wcf\" . WCF_N . \"_user user_table, wcf\" . WCF_N . \"_session session SET user_table.lastActivityTime = session.lastActivityTime WHERE user_table.userID = session.userID AND session.userID <> 0\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute (); } }","title":"Example"},{"location":"php/api/cronjobs/#icronjob-interface","text":"Every cronjob needs to implement the wcf\\system\\cronjob\\ICronjob interface which requires the execute(Cronjob $cronjob) method to be implemented. This method is called by wcf\\system\\cronjob\\CronjobScheduler when executing the cronjobs. In practice, however, you should extend the AbstractCronjob class and also call the AbstractCronjob::execute() method as it fires an event which makes cronjobs extendable by plugins (see event documentation ).","title":"ICronjob Interface"},{"location":"php/api/cronjobs/#executing-cronjobs-through-cli","text":"Cronjobs can be executed through the command-line interface (CLI): 1 2 3 4 5 php /path/to/wcf/cli.php << 'EOT' USERNAME PASSWORD cronjob execute EOT","title":"Executing Cronjobs Through CLI"},{"location":"php/api/event_list/","text":"Event List # Events whose name is marked with an asterisk are called from a static method and thus do not provide any object, just the class name. WoltLab Suite Core # Class Event Name wcf\\acp\\action\\UserExportGdprAction export wcf\\acp\\form\\StyleAddForm setVariables wcf\\acp\\form\\UserSearchForm search wcf\\action\\AbstractAction checkModules wcf\\action\\AbstractAction checkPermissions wcf\\action\\AbstractAction execute wcf\\action\\AbstractAction executed wcf\\action\\AbstractAction readParameters wcf\\data\\attachment\\AttachmentAction generateThumbnail wcf\\data\\session\\SessionAction keepAlive wcf\\data\\session\\SessionAction poll wcf\\data\\trophy\\Trophy renderTrophy wcf\\data\\user\\online\\UserOnline getBrowser wcf\\data\\user\\online\\UserOnlineList isVisible wcf\\data\\user\\trophy\\UserTrophy getReplacements wcf\\data\\user\\UserAction beforeFindUsers wcf\\data\\user\\UserAction rename wcf\\data\\user\\UserProfile getAvatar wcf\\data\\user\\UserProfile isAccessible wcf\\data\\AbstractDatabaseObjectAction finalizeAction wcf\\data\\AbstractDatabaseObjectAction initializeAction wcf\\data\\AbstractDatabaseObjectAction validateAction wcf\\data\\DatabaseObjectList init wcf\\form\\AbstractForm readFormParameters wcf\\form\\AbstractForm save wcf\\form\\AbstractForm saved wcf\\form\\AbstractForm submit wcf\\form\\AbstractForm validate wcf\\form\\AbstractModerationForm prepareSave wcf\\page\\AbstractPage assignVariables wcf\\page\\AbstractPage checkModules wcf\\page\\AbstractPage checkPermissions wcf\\page\\AbstractPage readData wcf\\page\\AbstractPage readParameters wcf\\page\\AbstractPage show wcf\\page\\MultipleLinkPage beforeReadObjects wcf\\page\\MultipleLinkPage calculateNumberOfPages wcf\\page\\MultipleLinkPage countItems wcf\\page\\SortablePage validateSortField wcf\\page\\SortablePage validateSortOrder wcf\\system\\bbcode\\MessageParser afterParsing wcf\\system\\bbcode\\MessageParser beforeParsing wcf\\system\\bbcode\\SimpleMessageParser afterParsing wcf\\system\\bbcode\\SimpleMessageParser beforeParsing wcf\\system\\box\\AbstractBoxController __construct wcf\\system\\box\\AbstractBoxController afterLoadContent wcf\\system\\box\\AbstractBoxController beforeLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController afterLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController beforeLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController hasContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController readObjects wcf\\system\\cronjob\\AbstractCronjob execute wcf\\system\\email\\Email getJobs wcf\\system\\form\\builder\\container\\wysiwyg\\WysiwygFormContainer populate wcf\\system\\html\\input\\filter\\MessageHtmlInputFilter setAttributeDefinitions wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor afterProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor beforeEmbeddedProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor beforeProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor convertPlainLinks wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor getTextContent wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor parseEmbeddedContent wcf\\system\\html\\input\\node\\HtmlInputNodeWoltlabMetacodeMarker filterGroups wcf\\system\\html\\output\\node\\HtmlOutputNodePre selectHighlighter wcf\\system\\html\\output\\node\\HtmlOutputNodeProcessor beforeProcess wcf\\system\\image\\adapter\\ImagickImageAdapter getResizeFilter wcf\\system\\menu\\user\\profile\\UserProfileMenu init wcf\\system\\menu\\user\\profile\\UserProfileMenu loadCache wcf\\system\\menu\\TreeMenu init wcf\\system\\menu\\TreeMenu loadCache wcf\\system\\message\\QuickReplyManager addFullQuote wcf\\system\\message\\QuickReplyManager allowedDataParameters wcf\\system\\message\\QuickReplyManager beforeRenderQuote wcf\\system\\message\\QuickReplyManager createMessage wcf\\system\\message\\QuickReplyManager createdMessage wcf\\system\\message\\QuickReplyManager getMessage wcf\\system\\message\\QuickReplyManager validateParameters wcf\\system\\option\\OptionHandler afterReadCache wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin construct wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin hasUninstall wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin install wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin uninstall wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin update wcf\\system\\package\\plugin\\ObjectTypePackageInstallationPlugin addConditionFields wcf\\system\\package\\PackageInstallationDispatcher postInstall wcf\\system\\package\\PackageUninstallationDispatcher postUninstall wcf\\system\\reaction\\ReactionHandler getDataAttributes wcf\\system\\request\\RouteHandler didInit wcf\\system\\session\\ACPSessionFactory afterInit wcf\\system\\session\\ACPSessionFactory beforeInit wcf\\system\\session\\SessionHandler afterChangeUser wcf\\system\\session\\SessionHandler beforeChangeUser wcf\\system\\style\\StyleCompiler compile wcf\\system\\template\\TemplateEngine afterDisplay wcf\\system\\template\\TemplateEngine beforeDisplay wcf\\system\\upload\\DefaultUploadFileSaveStrategy generateThumbnails wcf\\system\\upload\\DefaultUploadFileSaveStrategy save wcf\\system\\user\\authentication\\UserAuthenticationFactory init wcf\\system\\user\\notification\\UserNotificationHandler createdNotification wcf\\system\\user\\notification\\UserNotificationHandler fireEvent wcf\\system\\user\\notification\\UserNotificationHandler markAsConfirmed wcf\\system\\user\\notification\\UserNotificationHandler markAsConfirmedByIDs wcf\\system\\user\\notification\\UserNotificationHandler removeNotifications wcf\\system\\user\\notification\\UserNotificationHandler updateTriggerCount wcf\\system\\user\\UserBirthdayCache loadMonth wcf\\system\\worker\\AbstractRebuildDataWorker execute wcf\\system\\CLIWCF afterArgumentParsing wcf\\system\\CLIWCF beforeArgumentParsing wcf\\system\\WCF initialized wcf\\util\\HeaderUtil parseOutput * WoltLab Suite Forum # Class Event Name wbb\\data\\board\\BoardAction cloneBoard wbb\\data\\post\\PostAction quickReplyShouldMerge wbb\\system\\thread\\ThreadHandler didInit","title":"Event List"},{"location":"php/api/event_list/#event-list","text":"Events whose name is marked with an asterisk are called from a static method and thus do not provide any object, just the class name.","title":"Event List"},{"location":"php/api/event_list/#woltlab-suite-core","text":"Class Event Name wcf\\acp\\action\\UserExportGdprAction export wcf\\acp\\form\\StyleAddForm setVariables wcf\\acp\\form\\UserSearchForm search wcf\\action\\AbstractAction checkModules wcf\\action\\AbstractAction checkPermissions wcf\\action\\AbstractAction execute wcf\\action\\AbstractAction executed wcf\\action\\AbstractAction readParameters wcf\\data\\attachment\\AttachmentAction generateThumbnail wcf\\data\\session\\SessionAction keepAlive wcf\\data\\session\\SessionAction poll wcf\\data\\trophy\\Trophy renderTrophy wcf\\data\\user\\online\\UserOnline getBrowser wcf\\data\\user\\online\\UserOnlineList isVisible wcf\\data\\user\\trophy\\UserTrophy getReplacements wcf\\data\\user\\UserAction beforeFindUsers wcf\\data\\user\\UserAction rename wcf\\data\\user\\UserProfile getAvatar wcf\\data\\user\\UserProfile isAccessible wcf\\data\\AbstractDatabaseObjectAction finalizeAction wcf\\data\\AbstractDatabaseObjectAction initializeAction wcf\\data\\AbstractDatabaseObjectAction validateAction wcf\\data\\DatabaseObjectList init wcf\\form\\AbstractForm readFormParameters wcf\\form\\AbstractForm save wcf\\form\\AbstractForm saved wcf\\form\\AbstractForm submit wcf\\form\\AbstractForm validate wcf\\form\\AbstractModerationForm prepareSave wcf\\page\\AbstractPage assignVariables wcf\\page\\AbstractPage checkModules wcf\\page\\AbstractPage checkPermissions wcf\\page\\AbstractPage readData wcf\\page\\AbstractPage readParameters wcf\\page\\AbstractPage show wcf\\page\\MultipleLinkPage beforeReadObjects wcf\\page\\MultipleLinkPage calculateNumberOfPages wcf\\page\\MultipleLinkPage countItems wcf\\page\\SortablePage validateSortField wcf\\page\\SortablePage validateSortOrder wcf\\system\\bbcode\\MessageParser afterParsing wcf\\system\\bbcode\\MessageParser beforeParsing wcf\\system\\bbcode\\SimpleMessageParser afterParsing wcf\\system\\bbcode\\SimpleMessageParser beforeParsing wcf\\system\\box\\AbstractBoxController __construct wcf\\system\\box\\AbstractBoxController afterLoadContent wcf\\system\\box\\AbstractBoxController beforeLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController afterLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController beforeLoadContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController hasContent wcf\\system\\box\\AbstractDatabaseObjectListBoxController readObjects wcf\\system\\cronjob\\AbstractCronjob execute wcf\\system\\email\\Email getJobs wcf\\system\\form\\builder\\container\\wysiwyg\\WysiwygFormContainer populate wcf\\system\\html\\input\\filter\\MessageHtmlInputFilter setAttributeDefinitions wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor afterProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor beforeEmbeddedProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor beforeProcess wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor convertPlainLinks wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor getTextContent wcf\\system\\html\\input\\node\\HtmlInputNodeProcessor parseEmbeddedContent wcf\\system\\html\\input\\node\\HtmlInputNodeWoltlabMetacodeMarker filterGroups wcf\\system\\html\\output\\node\\HtmlOutputNodePre selectHighlighter wcf\\system\\html\\output\\node\\HtmlOutputNodeProcessor beforeProcess wcf\\system\\image\\adapter\\ImagickImageAdapter getResizeFilter wcf\\system\\menu\\user\\profile\\UserProfileMenu init wcf\\system\\menu\\user\\profile\\UserProfileMenu loadCache wcf\\system\\menu\\TreeMenu init wcf\\system\\menu\\TreeMenu loadCache wcf\\system\\message\\QuickReplyManager addFullQuote wcf\\system\\message\\QuickReplyManager allowedDataParameters wcf\\system\\message\\QuickReplyManager beforeRenderQuote wcf\\system\\message\\QuickReplyManager createMessage wcf\\system\\message\\QuickReplyManager createdMessage wcf\\system\\message\\QuickReplyManager getMessage wcf\\system\\message\\QuickReplyManager validateParameters wcf\\system\\option\\OptionHandler afterReadCache wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin construct wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin hasUninstall wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin install wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin uninstall wcf\\system\\package\\plugin\\AbstractPackageInstallationPlugin update wcf\\system\\package\\plugin\\ObjectTypePackageInstallationPlugin addConditionFields wcf\\system\\package\\PackageInstallationDispatcher postInstall wcf\\system\\package\\PackageUninstallationDispatcher postUninstall wcf\\system\\reaction\\ReactionHandler getDataAttributes wcf\\system\\request\\RouteHandler didInit wcf\\system\\session\\ACPSessionFactory afterInit wcf\\system\\session\\ACPSessionFactory beforeInit wcf\\system\\session\\SessionHandler afterChangeUser wcf\\system\\session\\SessionHandler beforeChangeUser wcf\\system\\style\\StyleCompiler compile wcf\\system\\template\\TemplateEngine afterDisplay wcf\\system\\template\\TemplateEngine beforeDisplay wcf\\system\\upload\\DefaultUploadFileSaveStrategy generateThumbnails wcf\\system\\upload\\DefaultUploadFileSaveStrategy save wcf\\system\\user\\authentication\\UserAuthenticationFactory init wcf\\system\\user\\notification\\UserNotificationHandler createdNotification wcf\\system\\user\\notification\\UserNotificationHandler fireEvent wcf\\system\\user\\notification\\UserNotificationHandler markAsConfirmed wcf\\system\\user\\notification\\UserNotificationHandler markAsConfirmedByIDs wcf\\system\\user\\notification\\UserNotificationHandler removeNotifications wcf\\system\\user\\notification\\UserNotificationHandler updateTriggerCount wcf\\system\\user\\UserBirthdayCache loadMonth wcf\\system\\worker\\AbstractRebuildDataWorker execute wcf\\system\\CLIWCF afterArgumentParsing wcf\\system\\CLIWCF beforeArgumentParsing wcf\\system\\WCF initialized wcf\\util\\HeaderUtil parseOutput *","title":"WoltLab Suite Core"},{"location":"php/api/event_list/#woltlab-suite-forum","text":"Class Event Name wbb\\data\\board\\BoardAction cloneBoard wbb\\data\\post\\PostAction quickReplyShouldMerge wbb\\system\\thread\\ThreadHandler didInit","title":"WoltLab Suite Forum"},{"location":"php/api/events/","text":"Events # WoltLab Suite's event system allows manipulation of program flows and data without having to change any of the original source code. At many locations throughout the PHP code of WoltLab Suite Core and mainly through inheritance also in the applications and plugins, so called events are fired which trigger registered event listeners that get access to the object firing the event (or at least the class name if the event has been fired in a static method). This page focuses on the technical aspects of events and event listeners, the eventListener package installation plugin page covers how you can actually register an event listener. A comprehensive list of all available events is provided here . Introductory Example # Let's start with a simple example to illustrate how the event system works. Consider this pre-existing class: files/lib/system/example/ExampleComponent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleComponent { public $var = 1 ; public function getVar () { EventHandler :: getInstance () -> fireAction ( $this , 'getVar' ); return $this -> var ; } } where an event with event name getVar is fired in the getVar() method. If you create an object of this class and call the getVar() method, the return value will be 1 , of course: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php $example = new wcf\\system\\example\\ExampleComponent (); if ( $example -> getVar () == 1 ) { echo \"var is 1!\" ; } else if ( $example -> getVar () == 2 ) { echo \"var is 2!\" ; } else { echo \"No, var is neither 1 nor 2.\" ; } // output: var is 1! Now, consider that we have registered the following event listener to this event: files/lib/system/event/listener/ExampleEventListener.class.php 1 2 3 4 5 6 7 8 <? php namespace wcf\\system\\event\\listener ; class ExampleEventListener implements IParameterizedEventListener { public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $eventObj -> var = 2 ; } } Whenever the event in the getVar() method is called, this method (of the same event listener object) is called. In this case, the value of the method's first parameter is the ExampleComponent object passed as the first argument of the EventHandler::fireAction() call in ExampleComponent::getVar() . As ExampleComponent::$var is a public property, the event listener code can change it and set it to 2 . If you now execute the example code from above again, the output will change from var is 1! to var is 2! because prior to returning the value, the event listener code changes the value from 1 to 2 . This introductory example illustrates how event listeners can change data in a non-intrusive way. Program flow can be changed, for example, by throwing a wcf\\system\\exception\\PermissionDeniedException if some additional constraint to access a page is not fulfilled. Listening to Events # In order to listen to events, you need to register the event listener and the event listener itself needs to implement the interface wcf\\system\\event\\listener\\IParameterizedEventListener which only contains the execute method (see example above). The first parameter $eventObj of the method contains the passed object where the event is fired or the name of the class in which the event is fired if it is fired from a static method. The second parameter $className always contains the name of the class where the event has been fired. The third parameter $eventName provides the name of the event within a class to uniquely identify the exact location in the class where the event has been fired. The last parameter $parameters is a reference to the array which contains additional data passed by the method firing the event. If no additional data is passed, $parameters is empty. Firing Events # If you write code and want plugins to have access at certain points, you can fire an event on your own. The only thing to do is to call the wcf\\system\\event\\EventHandler::fireAction($eventObj, $eventName, array &$parameters = []) method and pass the following parameters: $eventObj should be $this if you fire from an object context, otherwise pass the class name static::class . $eventName identifies the event within the class and generally has the same name as the method. In cases, were you might fire more than one event in a method, for example before and after a certain piece of code, you can use the prefixes before* and after* in your event names. $parameters is an optional array which allows you to pass additional data to the event listeners without having to make this data accessible via a property explicitly only created for this purpose. This additional data can either be just additional information for the event listeners about the context of the method call or allow the event listener to manipulate local data if the code, where the event has been fired, uses the passed data afterwards. Example: Using $parameters argument # Consider the following method which gets some text that the methods parses. files/lib/system/example/ExampleParser.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleParser { public function parse ( $text ) { // [some parsing done by default] $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'parse' , $parameters ); return $parameters [ 'text' ]; } } After the default parsing by the method itself, the author wants to enable plugins to do additional parsing and thus fires an event and passes the parsed text as an additional parameter. Then, a plugin can deliver the following event listener files/lib/system/event/listener/ExampleParserEventListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 <? php namespace wcf\\system\\event\\listener ; class ExampleParserEventListener implements IParameterizedEventListener { public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $text = $parameters [ 'text' ]; // [some additional parsing which changes $text] $parameters [ 'text' ] = $text ; } } which can access the text via $parameters['text'] . This example can also be perfectly used to illustrate how to name multiple events in the same method. Let's assume that the author wants to enable plugins to change the text before and after the method does its own parsing and thus fires two events: files/lib/system/example/ExampleParser.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleParser { public function parse ( $text ) { $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'beforeParsing' , $parameters ); $text = $parameters [ 'text' ]; // [some parsing done by default] $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'afterParsing' , $parameters ); return $parameters [ 'text' ]; } } Advanced Example: Additional Form Field # One common reason to use event listeners is to add an additional field to a pre-existing form (in combination with template listeners, which we will not cover here). We will assume that users are able to do both, create and edit the objects via this form. The points in the program flow of AbstractForm that are relevant here are: adding object (after the form has been submitted): reading the value of the field validating the read value saving the additional value after successful validation and resetting locally stored value or assigning the current value of the field to the template after unsuccessful validation editing object: on initial form request: reading the pre-existing value of the edited object assigning the field value to the template after the form has been submitted: reading the value of the field validating the read value saving the additional value after successful validation assigning the current value of the field to the template All of these cases can be covered the by following code in which we assume that wcf\\form\\ExampleAddForm is the form to create example objects and that wcf\\form\\ExampleEditForm extends wcf\\form\\ExampleAddForm and is used for editing existing example objects. files/lib/system/event/listener/ExampleAddFormListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <? php namespace wcf\\system\\event\\listener ; use wcf\\form\\ExampleAddForm ; use wcf\\form\\ExampleEditForm ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\WCF ; class ExampleAddFormListener implements IParameterizedEventListener { protected $var = 0 ; public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $this -> $eventName ( $eventObj ); } protected function assignVariables () { WCF :: getTPL () -> assign ( 'var' , $this -> var ); } protected function readData ( ExampleEditForm $eventObj ) { if ( empty ( $_POST )) { $this -> var = $eventObj -> example -> var ; } } protected function readFormParameters () { if ( isset ( $_POST [ 'var' ])) $this -> var = intval ( $_POST [ 'var' ]); } protected function save ( ExampleAddForm $eventObj ) { $eventObj -> additionalFields = array_merge ( $eventObj -> additionalFields , [ 'var' => $this -> var ]); } protected function saved () { $this -> var = 0 ; } protected function validate () { if ( $this -> var < 0 ) { throw new UserInputException ( 'var' , 'isNegative' ); } } } The execute method in this example just delegates the call to a method with the same name as the event so that this class mimics the structure of a form class itself. The form object is passed to the methods but is only given in the method signatures as a parameter here whenever the form object is actually used. Furthermore, the type-hinting of the parameter illustrates in which contexts the method is actually called which will become clear in the following discussion of the individual methods: assignVariables() is called for the add and the edit form and simply assigns the current value of the variable to the template. readData() reads the pre-existing value of $var if the form has not been submitted and thus is only relevant when editing objects which is illustrated by the explicit type-hint of ExampleEditForm . readFormParameters() reads the value for both, the add and the edit form. save() is, of course, also relevant in both cases but requires the form object to store the additional value in the wcf\\form\\AbstractForm::$additionalFields array which can be used if a var column has been added to the database table in which the example objects are stored. saved() is only called for the add form as it clears the internal value so that in the assignVariables() call, the default value will be assigned to the template to create an \"empty\" form. During edits, this current value is the actual value that should be shown. validate() also needs to be called in both cases as the input data always has to be validated. Lastly, the following XML file has to be used to register the event listeners (you can find more information about how to register event listeners on the eventListener package installation plugin page ): eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/eventListener.xsd\" > <import> <eventlistener name= \"exampleAddInherited\" > <eventclassname> wcf\\form\\ExampleAddForm </eventclassname> <eventname> assignVariables,readFormParameters,save,validate </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> <eventlistener name= \"exampleAdd\" > <eventclassname> wcf\\form\\ExampleAddForm </eventclassname> <eventname> saved </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> </eventlistener> <eventlistener name= \"exampleEdit\" > <eventclassname> wcf\\form\\ExampleEditForm </eventclassname> <eventname> readData </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> </eventlistener> </import> </data>","title":"Events"},{"location":"php/api/events/#events","text":"WoltLab Suite's event system allows manipulation of program flows and data without having to change any of the original source code. At many locations throughout the PHP code of WoltLab Suite Core and mainly through inheritance also in the applications and plugins, so called events are fired which trigger registered event listeners that get access to the object firing the event (or at least the class name if the event has been fired in a static method). This page focuses on the technical aspects of events and event listeners, the eventListener package installation plugin page covers how you can actually register an event listener. A comprehensive list of all available events is provided here .","title":"Events"},{"location":"php/api/events/#introductory-example","text":"Let's start with a simple example to illustrate how the event system works. Consider this pre-existing class: files/lib/system/example/ExampleComponent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleComponent { public $var = 1 ; public function getVar () { EventHandler :: getInstance () -> fireAction ( $this , 'getVar' ); return $this -> var ; } } where an event with event name getVar is fired in the getVar() method. If you create an object of this class and call the getVar() method, the return value will be 1 , of course: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php $example = new wcf\\system\\example\\ExampleComponent (); if ( $example -> getVar () == 1 ) { echo \"var is 1!\" ; } else if ( $example -> getVar () == 2 ) { echo \"var is 2!\" ; } else { echo \"No, var is neither 1 nor 2.\" ; } // output: var is 1! Now, consider that we have registered the following event listener to this event: files/lib/system/event/listener/ExampleEventListener.class.php 1 2 3 4 5 6 7 8 <? php namespace wcf\\system\\event\\listener ; class ExampleEventListener implements IParameterizedEventListener { public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $eventObj -> var = 2 ; } } Whenever the event in the getVar() method is called, this method (of the same event listener object) is called. In this case, the value of the method's first parameter is the ExampleComponent object passed as the first argument of the EventHandler::fireAction() call in ExampleComponent::getVar() . As ExampleComponent::$var is a public property, the event listener code can change it and set it to 2 . If you now execute the example code from above again, the output will change from var is 1! to var is 2! because prior to returning the value, the event listener code changes the value from 1 to 2 . This introductory example illustrates how event listeners can change data in a non-intrusive way. Program flow can be changed, for example, by throwing a wcf\\system\\exception\\PermissionDeniedException if some additional constraint to access a page is not fulfilled.","title":"Introductory Example"},{"location":"php/api/events/#listening-to-events","text":"In order to listen to events, you need to register the event listener and the event listener itself needs to implement the interface wcf\\system\\event\\listener\\IParameterizedEventListener which only contains the execute method (see example above). The first parameter $eventObj of the method contains the passed object where the event is fired or the name of the class in which the event is fired if it is fired from a static method. The second parameter $className always contains the name of the class where the event has been fired. The third parameter $eventName provides the name of the event within a class to uniquely identify the exact location in the class where the event has been fired. The last parameter $parameters is a reference to the array which contains additional data passed by the method firing the event. If no additional data is passed, $parameters is empty.","title":"Listening to Events"},{"location":"php/api/events/#firing-events","text":"If you write code and want plugins to have access at certain points, you can fire an event on your own. The only thing to do is to call the wcf\\system\\event\\EventHandler::fireAction($eventObj, $eventName, array &$parameters = []) method and pass the following parameters: $eventObj should be $this if you fire from an object context, otherwise pass the class name static::class . $eventName identifies the event within the class and generally has the same name as the method. In cases, were you might fire more than one event in a method, for example before and after a certain piece of code, you can use the prefixes before* and after* in your event names. $parameters is an optional array which allows you to pass additional data to the event listeners without having to make this data accessible via a property explicitly only created for this purpose. This additional data can either be just additional information for the event listeners about the context of the method call or allow the event listener to manipulate local data if the code, where the event has been fired, uses the passed data afterwards.","title":"Firing Events"},{"location":"php/api/events/#example-using-parameters-argument","text":"Consider the following method which gets some text that the methods parses. files/lib/system/example/ExampleParser.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleParser { public function parse ( $text ) { // [some parsing done by default] $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'parse' , $parameters ); return $parameters [ 'text' ]; } } After the default parsing by the method itself, the author wants to enable plugins to do additional parsing and thus fires an event and passes the parsed text as an additional parameter. Then, a plugin can deliver the following event listener files/lib/system/event/listener/ExampleParserEventListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 <? php namespace wcf\\system\\event\\listener ; class ExampleParserEventListener implements IParameterizedEventListener { public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $text = $parameters [ 'text' ]; // [some additional parsing which changes $text] $parameters [ 'text' ] = $text ; } } which can access the text via $parameters['text'] . This example can also be perfectly used to illustrate how to name multiple events in the same method. Let's assume that the author wants to enable plugins to change the text before and after the method does its own parsing and thus fires two events: files/lib/system/example/ExampleParser.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <? php namespace wcf\\system\\example ; use wcf\\system\\event\\EventHandler ; class ExampleParser { public function parse ( $text ) { $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'beforeParsing' , $parameters ); $text = $parameters [ 'text' ]; // [some parsing done by default] $parameters = [ 'text' => $text ]; EventHandler :: getInstance () -> fireAction ( $this , 'afterParsing' , $parameters ); return $parameters [ 'text' ]; } }","title":"Example: Using $parameters argument"},{"location":"php/api/events/#advanced-example-additional-form-field","text":"One common reason to use event listeners is to add an additional field to a pre-existing form (in combination with template listeners, which we will not cover here). We will assume that users are able to do both, create and edit the objects via this form. The points in the program flow of AbstractForm that are relevant here are: adding object (after the form has been submitted): reading the value of the field validating the read value saving the additional value after successful validation and resetting locally stored value or assigning the current value of the field to the template after unsuccessful validation editing object: on initial form request: reading the pre-existing value of the edited object assigning the field value to the template after the form has been submitted: reading the value of the field validating the read value saving the additional value after successful validation assigning the current value of the field to the template All of these cases can be covered the by following code in which we assume that wcf\\form\\ExampleAddForm is the form to create example objects and that wcf\\form\\ExampleEditForm extends wcf\\form\\ExampleAddForm and is used for editing existing example objects. files/lib/system/event/listener/ExampleAddFormListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <? php namespace wcf\\system\\event\\listener ; use wcf\\form\\ExampleAddForm ; use wcf\\form\\ExampleEditForm ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\WCF ; class ExampleAddFormListener implements IParameterizedEventListener { protected $var = 0 ; public function execute ( $eventObj , $className , $eventName , array & $parameters ) { $this -> $eventName ( $eventObj ); } protected function assignVariables () { WCF :: getTPL () -> assign ( 'var' , $this -> var ); } protected function readData ( ExampleEditForm $eventObj ) { if ( empty ( $_POST )) { $this -> var = $eventObj -> example -> var ; } } protected function readFormParameters () { if ( isset ( $_POST [ 'var' ])) $this -> var = intval ( $_POST [ 'var' ]); } protected function save ( ExampleAddForm $eventObj ) { $eventObj -> additionalFields = array_merge ( $eventObj -> additionalFields , [ 'var' => $this -> var ]); } protected function saved () { $this -> var = 0 ; } protected function validate () { if ( $this -> var < 0 ) { throw new UserInputException ( 'var' , 'isNegative' ); } } } The execute method in this example just delegates the call to a method with the same name as the event so that this class mimics the structure of a form class itself. The form object is passed to the methods but is only given in the method signatures as a parameter here whenever the form object is actually used. Furthermore, the type-hinting of the parameter illustrates in which contexts the method is actually called which will become clear in the following discussion of the individual methods: assignVariables() is called for the add and the edit form and simply assigns the current value of the variable to the template. readData() reads the pre-existing value of $var if the form has not been submitted and thus is only relevant when editing objects which is illustrated by the explicit type-hint of ExampleEditForm . readFormParameters() reads the value for both, the add and the edit form. save() is, of course, also relevant in both cases but requires the form object to store the additional value in the wcf\\form\\AbstractForm::$additionalFields array which can be used if a var column has been added to the database table in which the example objects are stored. saved() is only called for the add form as it clears the internal value so that in the assignVariables() call, the default value will be assigned to the template to create an \"empty\" form. During edits, this current value is the actual value that should be shown. validate() also needs to be called in both cases as the input data always has to be validated. Lastly, the following XML file has to be used to register the event listeners (you can find more information about how to register event listeners on the eventListener package installation plugin page ): eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/eventListener.xsd\" > <import> <eventlistener name= \"exampleAddInherited\" > <eventclassname> wcf\\form\\ExampleAddForm </eventclassname> <eventname> assignVariables,readFormParameters,save,validate </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> <eventlistener name= \"exampleAdd\" > <eventclassname> wcf\\form\\ExampleAddForm </eventclassname> <eventname> saved </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> </eventlistener> <eventlistener name= \"exampleEdit\" > <eventclassname> wcf\\form\\ExampleEditForm </eventclassname> <eventname> readData </eventname> <listenerclassname> wcf\\system\\event\\listener\\ExampleAddFormListener </listenerclassname> </eventlistener> </import> </data>","title":"Advanced Example: Additional Form Field"},{"location":"php/api/package_installation_plugins/","text":"Package Installation Plugins # A package installation plugin (PIP) defines the behavior to handle a specific instruction during package installation, update or uninstallation. AbstractPackageInstallationPlugin # Any package installation plugin has to implement the IPackageInstallationPlugin interface. It is recommended however, to extend the abstract implementation AbstractPackageInstallationPlugin of this interface instead of directly implementing the interface. The abstract implementation will always provide sane methods in case of any API changes. Class Members # Package Installation Plugins have a few notable class members easing your work: $installation # This member contains an instance of PackageInstallationDispatcher which provides you with all meta data related to the current package being processed. The most common usage is the retrieval of the package ID via $this->installation->getPackageID() . $application # Represents the abbreviation of the target application, e.g. wbb (default value: wcf ), used for the name of database table in which the installed data is stored. AbstractXMLPackageInstallationPlugin # AbstractPackageInstallationPlugin is the default implementation for all package installation plugins based upon a single XML document. It handles the evaluation of the document and provide you an object-orientated approach to handle its data. Class Members # $className # Value must be the qualified name of a class deriving from DatabaseObjectEditor which is used to create and update objects. $tagName # Specifies the tag name within a <import> or <delete> section of the XML document used for each installed object. prepareImport(array $data) # The passed array $data contains the parsed value from each evaluated tag in the <import> section: $data['elements'] contains a list of tag names and their value. $data['attributes'] contains a list of attributes present on the tag identified by $tagName . This method should return an one-dimensional array, where each key maps to the corresponding database column name (key names are case-sensitive). It will be passed to either DatabaseObjectEditor::create() or DatabaseObjectEditor::update() . Example: 1 2 3 4 5 6 <? php return [ 'environment' => $data [ 'elements' ][ 'environment' ], 'eventName' => $data [ 'elements' ][ 'eventname' ], 'name' => $data [ 'attributes' ][ 'name' ] ]; validateImport(array $data) # The passed array $data equals the data returned by prepareImport() . This method has no return value, instead you should throw an exception if the passed data is invalid. findExistingItem(array $data) # The passed array $data equals the data returned by prepareImport() . This method is expected to return an array with two keys: sql contains the SQL query with placeholders. parameters contains an array with values used for the SQL query. Example # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_\" . $this -> tableName . \" WHERE packageID = ? AND name = ? AND templateName = ? AND eventName = ? AND environment = ?\" ; $parameters = [ $this -> installation -> getPackageID (), $data [ 'name' ], $data [ 'templateName' ], $data [ 'eventName' ], $data [ 'environment' ] ]; return [ 'sql' => $sql , 'parameters' => $parameters ]; handleDelete(array $items) # The passed array $items contains the original node data, similar to prepareImport() . You should make use of this data to remove the matching element from database. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php $sql = \"DELETE FROM wcf\" . WCF_N . \"_\" . $this -> tableName . \" WHERE packageID = ? AND environment = ? AND eventName = ? AND name = ? AND templateName = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); foreach ( $items as $item ) { $statement -> execute ([ $this -> installation -> getPackageID (), $item [ 'elements' ][ 'environment' ], $item [ 'elements' ][ 'eventname' ], $item [ 'attributes' ][ 'name' ], $item [ 'elements' ][ 'templatename' ] ]); } postImport() # Allows you to (optionally) run additionally actions after all elements were processed. AbstractOptionPackageInstallationPlugin # AbstractOptionPackageInstallationPlugin is an abstract implementation for options, used for: ACL Options Options User Options User Group Options Differences to AbstractXMLPackageInstallationPlugin # $reservedTags # $reservedTags is a list of reserved tag names so that any tag encountered but not listed here will be added to the database column additionalData . This allows options to store arbitrary data which can be accessed but were not initially part of the PIP specifications.","title":"Package Installation Plugins"},{"location":"php/api/package_installation_plugins/#package-installation-plugins","text":"A package installation plugin (PIP) defines the behavior to handle a specific instruction during package installation, update or uninstallation.","title":"Package Installation Plugins"},{"location":"php/api/package_installation_plugins/#abstractpackageinstallationplugin","text":"Any package installation plugin has to implement the IPackageInstallationPlugin interface. It is recommended however, to extend the abstract implementation AbstractPackageInstallationPlugin of this interface instead of directly implementing the interface. The abstract implementation will always provide sane methods in case of any API changes.","title":"AbstractPackageInstallationPlugin"},{"location":"php/api/package_installation_plugins/#class-members","text":"Package Installation Plugins have a few notable class members easing your work:","title":"Class Members"},{"location":"php/api/package_installation_plugins/#installation","text":"This member contains an instance of PackageInstallationDispatcher which provides you with all meta data related to the current package being processed. The most common usage is the retrieval of the package ID via $this->installation->getPackageID() .","title":"$installation"},{"location":"php/api/package_installation_plugins/#application","text":"Represents the abbreviation of the target application, e.g. wbb (default value: wcf ), used for the name of database table in which the installed data is stored.","title":"$application"},{"location":"php/api/package_installation_plugins/#abstractxmlpackageinstallationplugin","text":"AbstractPackageInstallationPlugin is the default implementation for all package installation plugins based upon a single XML document. It handles the evaluation of the document and provide you an object-orientated approach to handle its data.","title":"AbstractXMLPackageInstallationPlugin"},{"location":"php/api/package_installation_plugins/#class-members_1","text":"","title":"Class Members"},{"location":"php/api/package_installation_plugins/#classname","text":"Value must be the qualified name of a class deriving from DatabaseObjectEditor which is used to create and update objects.","title":"$className"},{"location":"php/api/package_installation_plugins/#tagname","text":"Specifies the tag name within a <import> or <delete> section of the XML document used for each installed object.","title":"$tagName"},{"location":"php/api/package_installation_plugins/#prepareimportarray-data","text":"The passed array $data contains the parsed value from each evaluated tag in the <import> section: $data['elements'] contains a list of tag names and their value. $data['attributes'] contains a list of attributes present on the tag identified by $tagName . This method should return an one-dimensional array, where each key maps to the corresponding database column name (key names are case-sensitive). It will be passed to either DatabaseObjectEditor::create() or DatabaseObjectEditor::update() . Example: 1 2 3 4 5 6 <? php return [ 'environment' => $data [ 'elements' ][ 'environment' ], 'eventName' => $data [ 'elements' ][ 'eventname' ], 'name' => $data [ 'attributes' ][ 'name' ] ];","title":"prepareImport(array $data)"},{"location":"php/api/package_installation_plugins/#validateimportarray-data","text":"The passed array $data equals the data returned by prepareImport() . This method has no return value, instead you should throw an exception if the passed data is invalid.","title":"validateImport(array $data)"},{"location":"php/api/package_installation_plugins/#findexistingitemarray-data","text":"The passed array $data equals the data returned by prepareImport() . This method is expected to return an array with two keys: sql contains the SQL query with placeholders. parameters contains an array with values used for the SQL query.","title":"findExistingItem(array $data)"},{"location":"php/api/package_installation_plugins/#example","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <? php $sql = \"SELECT * FROM wcf\" . WCF_N . \"_\" . $this -> tableName . \" WHERE packageID = ? AND name = ? AND templateName = ? AND eventName = ? AND environment = ?\" ; $parameters = [ $this -> installation -> getPackageID (), $data [ 'name' ], $data [ 'templateName' ], $data [ 'eventName' ], $data [ 'environment' ] ]; return [ 'sql' => $sql , 'parameters' => $parameters ];","title":"Example"},{"location":"php/api/package_installation_plugins/#handledeletearray-items","text":"The passed array $items contains the original node data, similar to prepareImport() . You should make use of this data to remove the matching element from database. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <? php $sql = \"DELETE FROM wcf\" . WCF_N . \"_\" . $this -> tableName . \" WHERE packageID = ? AND environment = ? AND eventName = ? AND name = ? AND templateName = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); foreach ( $items as $item ) { $statement -> execute ([ $this -> installation -> getPackageID (), $item [ 'elements' ][ 'environment' ], $item [ 'elements' ][ 'eventname' ], $item [ 'attributes' ][ 'name' ], $item [ 'elements' ][ 'templatename' ] ]); }","title":"handleDelete(array $items)"},{"location":"php/api/package_installation_plugins/#postimport","text":"Allows you to (optionally) run additionally actions after all elements were processed.","title":"postImport()"},{"location":"php/api/package_installation_plugins/#abstractoptionpackageinstallationplugin","text":"AbstractOptionPackageInstallationPlugin is an abstract implementation for options, used for: ACL Options Options User Options User Group Options","title":"AbstractOptionPackageInstallationPlugin"},{"location":"php/api/package_installation_plugins/#differences-to-abstractxmlpackageinstallationplugin","text":"","title":"Differences to AbstractXMLPackageInstallationPlugin"},{"location":"php/api/package_installation_plugins/#reservedtags","text":"$reservedTags is a list of reserved tag names so that any tag encountered but not listed here will be added to the database column additionalData . This allows options to store arbitrary data which can be accessed but were not initially part of the PIP specifications.","title":"$reservedTags"},{"location":"php/api/sitemaps/","text":"Sitemaps # WoltLab Suite is capable of automatically creating a sitemap. This sitemap contains all static pages registered via the page package installation plugin and which may be indexed by search engines (checking the allowSpidersToIndex parameter and page permissions) and do not expect an object ID. Other pages have to be added to the sitemap as a separate object. The only prerequisite for sitemap objects is that the objects are instances of wcf\\data\\DatabaseObject and that there is a wcf\\data\\DatabaseObjectList implementation. First, we implement the PHP class, which provides us all database objects and optionally checks the permissions for a single object. The class must implement the interface wcf\\system\\sitemap\\object\\ISitemapObjectObjectType . However, in order to have some methods already implemented and ensure backwards compatibility, you should use the abstract class wcf\\system\\sitemap\\object\\AbstractSitemapObjectObjectType . The abstract class takes care of generating the DatabaseObjectList class name and list directly and implements optional methods with the default values. The only method that you have to implement yourself is the getObjectClass() method which returns the fully qualified name of the DatabaseObject class. The DatabaseObject class must implement the interface wcf\\data\\ILinkableObject . Other optional methods are: The getLastModifiedColumn() method returns the name of the column in the database where the last modification date is stored. If there is none, this method must return null . The canView() method checks whether the passed DatabaseObject is visible to the current user with the current user always being a guest. The getObjectListClass() method returns a non-standard DatabaseObjectList class name. The getObjectList() method returns the DatabaseObjectList instance. You can, for example, specify additional query conditions in the method. As an example, the implementation for users looks like this: files/lib/system/sitemap/object/UserSitemapObject.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\system\\sitemap\\object ; use wcf\\data\\user\\User ; use wcf\\data\\DatabaseObject ; use wcf\\system\\WCF ; /** * User sitemap implementation. * * @author Joshua Ruesweg * @copyright 2001-2017 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Sitemap\\Object * @since 3.1 */ class UserSitemapObject extends AbstractSitemapObjectObjectType { /** * @inheritDoc */ public function getObjectClass () { return User :: class ; } /** * @inheritDoc */ public function getLastModifiedColumn () { return 'lastActivityTime' ; } /** * @inheritDoc */ public function canView ( DatabaseObject $object ) { return WCF :: getSession () -> getPermission ( 'user.profile.canViewUserProfile' ); } } Next, the sitemap object must be registered as an object type: 1 2 3 4 5 6 7 8 <type> <name> com.example.plugin.sitemap.object.user </name> <definitionname> com.woltlab.wcf.sitemap.object </definitionname> <classname> wcf\\system\\sitemap\\object\\UserSitemapObject </classname> <priority> 0.5 </priority> <changeFreq> monthly </changeFreq> <rebuildTime> 259200 </rebuildTime> </type> In addition to the fully qualified class name, the object type definition com.woltlab.wcf.sitemap.object and the object type name, the parameters priority , changeFreq and rebuildTime must also be specified. priority ( https://www.sitemaps.org/protocol.html#prioritydef ) and changeFreq ( https://www.sitemaps.org/protocol.html#changefreqdef ) are specifications in the sitemaps protocol and can be changed by the user in the ACP. The priority should be 0.5 by default, unless there is an important reason to change it. The parameter rebuildTime specifies the number of seconds after which the sitemap should be regenerated. Finally, you have to create the language variable for the sitemap object. The language variable follows the pattern wcf.acp.sitemap.objectType.{objectTypeName} and is in the category wcf.acp.sitemap .","title":"Sitemaps"},{"location":"php/api/sitemaps/#sitemaps","text":"WoltLab Suite is capable of automatically creating a sitemap. This sitemap contains all static pages registered via the page package installation plugin and which may be indexed by search engines (checking the allowSpidersToIndex parameter and page permissions) and do not expect an object ID. Other pages have to be added to the sitemap as a separate object. The only prerequisite for sitemap objects is that the objects are instances of wcf\\data\\DatabaseObject and that there is a wcf\\data\\DatabaseObjectList implementation. First, we implement the PHP class, which provides us all database objects and optionally checks the permissions for a single object. The class must implement the interface wcf\\system\\sitemap\\object\\ISitemapObjectObjectType . However, in order to have some methods already implemented and ensure backwards compatibility, you should use the abstract class wcf\\system\\sitemap\\object\\AbstractSitemapObjectObjectType . The abstract class takes care of generating the DatabaseObjectList class name and list directly and implements optional methods with the default values. The only method that you have to implement yourself is the getObjectClass() method which returns the fully qualified name of the DatabaseObject class. The DatabaseObject class must implement the interface wcf\\data\\ILinkableObject . Other optional methods are: The getLastModifiedColumn() method returns the name of the column in the database where the last modification date is stored. If there is none, this method must return null . The canView() method checks whether the passed DatabaseObject is visible to the current user with the current user always being a guest. The getObjectListClass() method returns a non-standard DatabaseObjectList class name. The getObjectList() method returns the DatabaseObjectList instance. You can, for example, specify additional query conditions in the method. As an example, the implementation for users looks like this: files/lib/system/sitemap/object/UserSitemapObject.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\system\\sitemap\\object ; use wcf\\data\\user\\User ; use wcf\\data\\DatabaseObject ; use wcf\\system\\WCF ; /** * User sitemap implementation. * * @author Joshua Ruesweg * @copyright 2001-2017 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Sitemap\\Object * @since 3.1 */ class UserSitemapObject extends AbstractSitemapObjectObjectType { /** * @inheritDoc */ public function getObjectClass () { return User :: class ; } /** * @inheritDoc */ public function getLastModifiedColumn () { return 'lastActivityTime' ; } /** * @inheritDoc */ public function canView ( DatabaseObject $object ) { return WCF :: getSession () -> getPermission ( 'user.profile.canViewUserProfile' ); } } Next, the sitemap object must be registered as an object type: 1 2 3 4 5 6 7 8 <type> <name> com.example.plugin.sitemap.object.user </name> <definitionname> com.woltlab.wcf.sitemap.object </definitionname> <classname> wcf\\system\\sitemap\\object\\UserSitemapObject </classname> <priority> 0.5 </priority> <changeFreq> monthly </changeFreq> <rebuildTime> 259200 </rebuildTime> </type> In addition to the fully qualified class name, the object type definition com.woltlab.wcf.sitemap.object and the object type name, the parameters priority , changeFreq and rebuildTime must also be specified. priority ( https://www.sitemaps.org/protocol.html#prioritydef ) and changeFreq ( https://www.sitemaps.org/protocol.html#changefreqdef ) are specifications in the sitemaps protocol and can be changed by the user in the ACP. The priority should be 0.5 by default, unless there is an important reason to change it. The parameter rebuildTime specifies the number of seconds after which the sitemap should be regenerated. Finally, you have to create the language variable for the sitemap object. The language variable follows the pattern wcf.acp.sitemap.objectType.{objectTypeName} and is in the category wcf.acp.sitemap .","title":"Sitemaps"},{"location":"php/api/user_activity_points/","text":"User Activity Points # Users get activity points whenever they create content to award them for their contribution. Activity points are used to determine the rank of a user and can also be used for user conditions, for example for automatic user group assignments. To integrate activity points into your package, you have to register an object type for the defintion com.woltlab.wcf.user.activityPointEvent and specify a default number of points: 1 2 3 4 5 <type> <name> com.example.foo.activityPointEvent.bar </name> <definitionname> com.woltlab.wcf.user.activityPointEvent </definitionname> <points> 10 </points> </type> The number of points awarded for this type of activity point event can be changed by the administrator in the admin control panel. For this form and the user activity point list shown in the frontend, you have to provide the language item 1 wcf.user.activityPoint.objectType.com.example.foo.activityPointEvent.bar that contains the name of the content for which the activity points are awarded. If a relevant object is created, you have to use UserActivityPointHandler::fireEvent() which expects the name of the activity point event object type, the id of the object for which the points are awarded (though the object id is not used at the moment) and the user who gets the points: 1 2 3 4 5 UserActivityPointHandler :: getInstance () -> fireEvent ( 'com.example.foo.activityPointEvent.bar' , $bar -> barID , $bar -> userID ); To remove activity points once objects are deleted, you have to use UserActivityPointHandler::removeEvents() which also expects the name of the activity point event object type and additionally an array mapping the id of the user whose activity points will be reduced to the number of objects that are removed for the relevant user: 1 2 3 4 5 6 7 UserActivityPointHandler :: getInstance () -> removeEvents ( 'com.example.foo.activityPointEvent.bar' , [ 1 => 1 , // remove points for one object for user with id `1` 4 => 2 // remove points for two objects for user with id `4` ] );","title":"User Activity Points"},{"location":"php/api/user_activity_points/#user-activity-points","text":"Users get activity points whenever they create content to award them for their contribution. Activity points are used to determine the rank of a user and can also be used for user conditions, for example for automatic user group assignments. To integrate activity points into your package, you have to register an object type for the defintion com.woltlab.wcf.user.activityPointEvent and specify a default number of points: 1 2 3 4 5 <type> <name> com.example.foo.activityPointEvent.bar </name> <definitionname> com.woltlab.wcf.user.activityPointEvent </definitionname> <points> 10 </points> </type> The number of points awarded for this type of activity point event can be changed by the administrator in the admin control panel. For this form and the user activity point list shown in the frontend, you have to provide the language item 1 wcf.user.activityPoint.objectType.com.example.foo.activityPointEvent.bar that contains the name of the content for which the activity points are awarded. If a relevant object is created, you have to use UserActivityPointHandler::fireEvent() which expects the name of the activity point event object type, the id of the object for which the points are awarded (though the object id is not used at the moment) and the user who gets the points: 1 2 3 4 5 UserActivityPointHandler :: getInstance () -> fireEvent ( 'com.example.foo.activityPointEvent.bar' , $bar -> barID , $bar -> userID ); To remove activity points once objects are deleted, you have to use UserActivityPointHandler::removeEvents() which also expects the name of the activity point event object type and additionally an array mapping the id of the user whose activity points will be reduced to the number of objects that are removed for the relevant user: 1 2 3 4 5 6 7 UserActivityPointHandler :: getInstance () -> removeEvents ( 'com.example.foo.activityPointEvent.bar' , [ 1 => 1 , // remove points for one object for user with id `1` 4 => 2 // remove points for two objects for user with id `4` ] );","title":"User Activity Points"},{"location":"php/api/user_notifications/","text":"User Notifications # WoltLab Suite includes a powerful user notification system that supports notifications directly shown on the website and emails sent immediately or on a daily basis. objectType.xml # For any type of object related to events, you have to define an object type for the object type definition com.woltlab.wcf.notification.objectType : objectType.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectType.xsd\" > <import> <type> <name> com.woltlab.example.foo </name> <definitionname> com.woltlab.wcf.notification.objectType </definitionname> <classname> example\\system\\user\\notification\\object\\type\\FooUserNotificationObjectType </classname> <category> com.woltlab.example </category> </type> </import> </data> The referenced class FooUserNotificationObjectType has to implement the IUserNotificationObjectType interface, which should be done by extending AbstractUserNotificationObjectType . files/lib/system/user/notification/object/type/FooUserNotificationObjectType.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <? php namespace example\\system\\user\\notification\\object\\type ; use example\\data\\foo\\Foo ; use example\\data\\foo\\FooList ; use example\\system\\user\\notification\\object\\FooUserNotificationObject ; use wcf\\system\\user\\notification\\object\\type\\AbstractUserNotificationObjectType ; /** * Represents a foo as a notification object type. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Object\\Type */ class FooUserNotificationObjectType extends AbstractUserNotificationObjectType { /** * @inheritDoc */ protected static $decoratorClassName = FooUserNotificationObject :: class ; /** * @inheritDoc */ protected static $objectClassName = Foo :: class ; /** * @inheritDoc */ protected static $objectListClassName = FooList :: class ; } You have to set the class names of the database object ( $objectClassName ) and the related list ( $objectListClassName ). Additionally, you have to create a class that implements the IUserNotificationObject whose name you have to set as the value of the $decoratorClassName property. files/lib/system/user/notification/object/FooUserNotificationObject.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <? php namespace example\\system\\user\\notification\\object ; use example\\data\\foo\\Foo ; use wcf\\data\\DatabaseObjectDecorator ; use wcf\\system\\user\\notification\\object\\IUserNotificationObject ; /** * Represents a foo as a notification object. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Object * * @method Foo getDecoratedObject() * @mixin Foo */ class FooUserNotificationObject extends DatabaseObjectDecorator implements IUserNotificationObject { /** * @inheritDoc */ protected static $baseClass = Foo :: class ; /** * @inheritDoc */ public function getTitle () { return $this -> getDecoratedObject () -> getTitle (); } /** * @inheritDoc */ public function getURL () { return $this -> getDecoratedObject () -> getLink (); } /** * @inheritDoc */ public function getAuthorID () { return $this -> getDecoratedObject () -> userID ; } } The getTitle() method returns the title of the object. In this case, we assume that the Foo class has implemented the ITitledObject interface so that the decorated Foo can handle this method call itself. The getURL() method returns the link to the object. As for the getTitle() , we assume that the Foo class has implemented the ILinkableObject interface so that the decorated Foo can also handle this method call itself. The getAuthorID() method returns the id of the user who created the decorated Foo object. We assume that Foo objects have a userID property that contains this id. userNotificationEvent.xml # Each event that you fire in your package needs to be registered using the user notification event package installation plugin . An example file might look like this: userNotificationEvent.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userNotificationEvent.xsd\" > <import> <event> <name> bar </name> <objecttype> com.woltlab.example.foo </objecttype> <classname> example\\system\\user\\notification\\event\\FooUserNotificationEvent </classname> <preset> 1 </preset> </event> </import> </data> Here, you reference the user notification object type created via objectType.xml . The referenced class in the <classname> element has to implement the IUserNotificationEvent interface by extending the AbstractUserNotificationEvent class or the AbstractSharedUserNotificationEvent class if you want to pre-load additional data before processing notifications. In AbstractSharedUserNotificationEvent::prepare() , you can, for example, tell runtime caches to prepare to load certain objects which then are loaded all at once when the objects are needed. files/lib/system/user/notification/event/FooUserNotificationEvent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 <? php namespace example\\system\\user\\notification\\event ; use example\\system\\cache\\runtime\\BazRuntimeCache ; use example\\system\\user\\notification\\object\\FooUserNotificationObject ; use wcf\\system\\email\\Email ; use wcf\\system\\request\\LinkHandler ; use wcf\\system\\user\\notification\\event\\AbstractSharedUserNotificationEvent ; /** * Notification event for foos. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Event * * @method FooUserNotificationObject getUserNotificationObject() */ class FooUserNotificationEvent extends AbstractSharedUserNotificationEvent { /** * @inheritDoc */ protected $stackable = true ; /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function checkAccess () { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); if ( ! $this -> getUserNotificationObject () -> isAccessible ()) { // do some cleanup, if necessary return false ; } return true ; } /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function getEmailMessage ( $notificationType = 'instant' ) { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); $messageID = '<com.woltlab.example.baz/' . $this -> getUserNotificationObject () -> bazID . '@' . Email :: getHost () . '>' ; return [ 'application' => 'example' , 'in-reply-to' => [ $messageID ], 'message-id' => 'com.woltlab.example.foo/' . $this -> getUserNotificationObject () -> fooID , 'references' => [ $messageID ], 'template' => 'email_notification_foo' ]; } /** * @inheritDoc * @since 5.0 */ public function getEmailTitle () { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.mail.title' , [ 'userNotificationObject' => $this -> getUserNotificationObject () ]); } /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function getEventHash () { return sha1 ( $this -> eventID . '-' . $this -> getUserNotificationObject () -> bazID ); } /** * @inheritDoc */ public function getLink () { return LinkHandler :: getInstance () -> getLink ( 'Foo' , [ 'application' => 'example' , 'object' => $this -> getUserNotificationObject () -> getDecoratedObject () ]); } /** * @inheritDoc */ public function getMessage () { $authors = $this -> getAuthors (); $count = count ( $authors ); if ( $count > 1 ) { if ( isset ( $authors [ 0 ])) { unset ( $authors [ 0 ]); } $count = count ( $authors ); return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.message.stacked' , [ 'author' => $this -> author , 'authors' => array_values ( $authors ), 'count' => $count , 'guestTimesTriggered' => $this -> notification -> guestTimesTriggered , 'message' => $this -> getUserNotificationObject (), 'others' => $count - 1 ]); } return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.message' , [ 'author' => $this -> author , 'userNotificationObject' => $this -> getUserNotificationObject () ]); } /** * @inheritDoc */ public function getTitle () { $count = count ( $this -> getAuthors ()); if ( $count > 1 ) { return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.title.stacked' , [ 'count' => $count , 'timesTriggered' => $this -> notification -> timesTriggered ]); } return $this -> getLanguage () -> get ( 'example.foo.notification.title' ); } /** * @inheritDoc */ protected function prepare () { BazRuntimeCache :: getInstance () -> cacheObjectID ( $this -> getUserNotificationObject () -> bazID ); } } The $stackable property is false by default and has to be explicitly set to true if stacking of notifications should be enabled. Stacking of notification does not create new notifications for the same event for a certain object if the related action as been triggered by different users. For example, if something is liked by one user and then liked again by another user before the recipient of the notification has confirmed it, the existing notification will be amended to include both users who liked the content. Stacking can thus be used to avoid cluttering the notification list of users. The checkAccess() method makes sure that the active user still has access to the object related to the notification. If that is not the case, the user notification system will automatically deleted the user notification based on the return value of the method. If you have any cached values related to notifications, you should also reset these values here. The getEmailMessage() method return data to create the instant email or the daily summary email. For instant emails ( $notificationType = 'instant' ), you have to return an array like the one shown in the code above with the following components: application : abbreviation of application in-reply-to (optional): message id of the notification for the parent item and used to improve the ordering in threaded email clients message-id (optional): message id of the notification mail and has to be used in in-reply-to and references for follow up mails references (optional): all of the message ids of parent items (i.e. recursive in-reply-to) template : name of the template used to render the email body, should start with email_ variables (optional): template variables passed to the email template where they can be accessed via $notificationContent[variables] For daily emails ( $notificationType = 'daily' ), only application , template , and variables are supported. - The getEmailTitle() returns the title of the instant email sent to the user. By default, getEmailTitle() simply calls getTitle() . - The getEventHash() method returns a hash by which user notifications are grouped. Here, we want to group them not by the actual Foo object but by its parent Baz object and thus overwrite the default implementation provided by AbstractUserNotificationEvent . - The getLink() returns the link to the Foo object the notification belongs to. - The getMessage() method and the getTitle() return the message and the title of the user notification respectively. By checking the value of count($this->getAuthors()) , we check if the notification is stacked, thus if the event has been triggered for multiple users so that different languages items are used. If your notification event does not support stacking, this distinction is not necessary. - The prepare() method is called for each user notification before all user notifications are rendered. This allows to tell runtime caches to prepare to load objects later on (see Runtime Caches ). Firing Events # When the action related to a user notification is executed, you can use UserNotificationHandler::fireEvent() to create the notifications: 1 2 3 4 5 6 7 $recipientIDs = []; // fill with user ids of the recipients of the notification UserNotificationHandler :: getInstance () -> fireEvent ( 'bar' , // event name 'com.woltlab.example.foo' , // event object type name new FooUserNotificationObject ( new Foo ( $fooID )), // object related to the event $recipientIDs ); Marking Notifications as Confirmed # In some instances, you might want to manually mark user notifications as confirmed without the user manually confirming them, for example when they visit the page that is related to the user notification. In this case, you can use UserNotificationHandler::markAsConfirmed() : 1 2 3 4 5 6 7 8 $recipientIDs = []; // fill with user ids of the recipients of the notification $fooIDs = []; // fill with ids of related foo objects UserNotificationHandler :: getInstance () -> markAsConfirmed ( 'bar' , // event name 'com.woltlab.example.foo' , // event object type name $recipientIDs , $fooIDs );","title":"User Notifications"},{"location":"php/api/user_notifications/#user-notifications","text":"WoltLab Suite includes a powerful user notification system that supports notifications directly shown on the website and emails sent immediately or on a daily basis.","title":"User Notifications"},{"location":"php/api/user_notifications/#objecttypexml","text":"For any type of object related to events, you have to define an object type for the object type definition com.woltlab.wcf.notification.objectType : objectType.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/objectType.xsd\" > <import> <type> <name> com.woltlab.example.foo </name> <definitionname> com.woltlab.wcf.notification.objectType </definitionname> <classname> example\\system\\user\\notification\\object\\type\\FooUserNotificationObjectType </classname> <category> com.woltlab.example </category> </type> </import> </data> The referenced class FooUserNotificationObjectType has to implement the IUserNotificationObjectType interface, which should be done by extending AbstractUserNotificationObjectType . files/lib/system/user/notification/object/type/FooUserNotificationObjectType.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <? php namespace example\\system\\user\\notification\\object\\type ; use example\\data\\foo\\Foo ; use example\\data\\foo\\FooList ; use example\\system\\user\\notification\\object\\FooUserNotificationObject ; use wcf\\system\\user\\notification\\object\\type\\AbstractUserNotificationObjectType ; /** * Represents a foo as a notification object type. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Object\\Type */ class FooUserNotificationObjectType extends AbstractUserNotificationObjectType { /** * @inheritDoc */ protected static $decoratorClassName = FooUserNotificationObject :: class ; /** * @inheritDoc */ protected static $objectClassName = Foo :: class ; /** * @inheritDoc */ protected static $objectListClassName = FooList :: class ; } You have to set the class names of the database object ( $objectClassName ) and the related list ( $objectListClassName ). Additionally, you have to create a class that implements the IUserNotificationObject whose name you have to set as the value of the $decoratorClassName property. files/lib/system/user/notification/object/FooUserNotificationObject.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <? php namespace example\\system\\user\\notification\\object ; use example\\data\\foo\\Foo ; use wcf\\data\\DatabaseObjectDecorator ; use wcf\\system\\user\\notification\\object\\IUserNotificationObject ; /** * Represents a foo as a notification object. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Object * * @method Foo getDecoratedObject() * @mixin Foo */ class FooUserNotificationObject extends DatabaseObjectDecorator implements IUserNotificationObject { /** * @inheritDoc */ protected static $baseClass = Foo :: class ; /** * @inheritDoc */ public function getTitle () { return $this -> getDecoratedObject () -> getTitle (); } /** * @inheritDoc */ public function getURL () { return $this -> getDecoratedObject () -> getLink (); } /** * @inheritDoc */ public function getAuthorID () { return $this -> getDecoratedObject () -> userID ; } } The getTitle() method returns the title of the object. In this case, we assume that the Foo class has implemented the ITitledObject interface so that the decorated Foo can handle this method call itself. The getURL() method returns the link to the object. As for the getTitle() , we assume that the Foo class has implemented the ILinkableObject interface so that the decorated Foo can also handle this method call itself. The getAuthorID() method returns the id of the user who created the decorated Foo object. We assume that Foo objects have a userID property that contains this id.","title":"objectType.xml"},{"location":"php/api/user_notifications/#usernotificationeventxml","text":"Each event that you fire in your package needs to be registered using the user notification event package installation plugin . An example file might look like this: userNotificationEvent.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/2019/userNotificationEvent.xsd\" > <import> <event> <name> bar </name> <objecttype> com.woltlab.example.foo </objecttype> <classname> example\\system\\user\\notification\\event\\FooUserNotificationEvent </classname> <preset> 1 </preset> </event> </import> </data> Here, you reference the user notification object type created via objectType.xml . The referenced class in the <classname> element has to implement the IUserNotificationEvent interface by extending the AbstractUserNotificationEvent class or the AbstractSharedUserNotificationEvent class if you want to pre-load additional data before processing notifications. In AbstractSharedUserNotificationEvent::prepare() , you can, for example, tell runtime caches to prepare to load certain objects which then are loaded all at once when the objects are needed. files/lib/system/user/notification/event/FooUserNotificationEvent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 <? php namespace example\\system\\user\\notification\\event ; use example\\system\\cache\\runtime\\BazRuntimeCache ; use example\\system\\user\\notification\\object\\FooUserNotificationObject ; use wcf\\system\\email\\Email ; use wcf\\system\\request\\LinkHandler ; use wcf\\system\\user\\notification\\event\\AbstractSharedUserNotificationEvent ; /** * Notification event for foos. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Example\\System\\User\\Notification\\Event * * @method FooUserNotificationObject getUserNotificationObject() */ class FooUserNotificationEvent extends AbstractSharedUserNotificationEvent { /** * @inheritDoc */ protected $stackable = true ; /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function checkAccess () { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); if ( ! $this -> getUserNotificationObject () -> isAccessible ()) { // do some cleanup, if necessary return false ; } return true ; } /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function getEmailMessage ( $notificationType = 'instant' ) { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); $messageID = '<com.woltlab.example.baz/' . $this -> getUserNotificationObject () -> bazID . '@' . Email :: getHost () . '>' ; return [ 'application' => 'example' , 'in-reply-to' => [ $messageID ], 'message-id' => 'com.woltlab.example.foo/' . $this -> getUserNotificationObject () -> fooID , 'references' => [ $messageID ], 'template' => 'email_notification_foo' ]; } /** * @inheritDoc * @since 5.0 */ public function getEmailTitle () { $this -> getUserNotificationObject () -> setBaz ( BazRuntimeCache :: getInstance () -> getObject ( $this -> getUserNotificationObject () -> bazID )); return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.mail.title' , [ 'userNotificationObject' => $this -> getUserNotificationObject () ]); } /** @noinspection PhpMissingParentCallCommonInspection */ /** * @inheritDoc */ public function getEventHash () { return sha1 ( $this -> eventID . '-' . $this -> getUserNotificationObject () -> bazID ); } /** * @inheritDoc */ public function getLink () { return LinkHandler :: getInstance () -> getLink ( 'Foo' , [ 'application' => 'example' , 'object' => $this -> getUserNotificationObject () -> getDecoratedObject () ]); } /** * @inheritDoc */ public function getMessage () { $authors = $this -> getAuthors (); $count = count ( $authors ); if ( $count > 1 ) { if ( isset ( $authors [ 0 ])) { unset ( $authors [ 0 ]); } $count = count ( $authors ); return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.message.stacked' , [ 'author' => $this -> author , 'authors' => array_values ( $authors ), 'count' => $count , 'guestTimesTriggered' => $this -> notification -> guestTimesTriggered , 'message' => $this -> getUserNotificationObject (), 'others' => $count - 1 ]); } return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.message' , [ 'author' => $this -> author , 'userNotificationObject' => $this -> getUserNotificationObject () ]); } /** * @inheritDoc */ public function getTitle () { $count = count ( $this -> getAuthors ()); if ( $count > 1 ) { return $this -> getLanguage () -> getDynamicVariable ( 'example.foo.notification.title.stacked' , [ 'count' => $count , 'timesTriggered' => $this -> notification -> timesTriggered ]); } return $this -> getLanguage () -> get ( 'example.foo.notification.title' ); } /** * @inheritDoc */ protected function prepare () { BazRuntimeCache :: getInstance () -> cacheObjectID ( $this -> getUserNotificationObject () -> bazID ); } } The $stackable property is false by default and has to be explicitly set to true if stacking of notifications should be enabled. Stacking of notification does not create new notifications for the same event for a certain object if the related action as been triggered by different users. For example, if something is liked by one user and then liked again by another user before the recipient of the notification has confirmed it, the existing notification will be amended to include both users who liked the content. Stacking can thus be used to avoid cluttering the notification list of users. The checkAccess() method makes sure that the active user still has access to the object related to the notification. If that is not the case, the user notification system will automatically deleted the user notification based on the return value of the method. If you have any cached values related to notifications, you should also reset these values here. The getEmailMessage() method return data to create the instant email or the daily summary email. For instant emails ( $notificationType = 'instant' ), you have to return an array like the one shown in the code above with the following components: application : abbreviation of application in-reply-to (optional): message id of the notification for the parent item and used to improve the ordering in threaded email clients message-id (optional): message id of the notification mail and has to be used in in-reply-to and references for follow up mails references (optional): all of the message ids of parent items (i.e. recursive in-reply-to) template : name of the template used to render the email body, should start with email_ variables (optional): template variables passed to the email template where they can be accessed via $notificationContent[variables] For daily emails ( $notificationType = 'daily' ), only application , template , and variables are supported. - The getEmailTitle() returns the title of the instant email sent to the user. By default, getEmailTitle() simply calls getTitle() . - The getEventHash() method returns a hash by which user notifications are grouped. Here, we want to group them not by the actual Foo object but by its parent Baz object and thus overwrite the default implementation provided by AbstractUserNotificationEvent . - The getLink() returns the link to the Foo object the notification belongs to. - The getMessage() method and the getTitle() return the message and the title of the user notification respectively. By checking the value of count($this->getAuthors()) , we check if the notification is stacked, thus if the event has been triggered for multiple users so that different languages items are used. If your notification event does not support stacking, this distinction is not necessary. - The prepare() method is called for each user notification before all user notifications are rendered. This allows to tell runtime caches to prepare to load objects later on (see Runtime Caches ).","title":"userNotificationEvent.xml"},{"location":"php/api/user_notifications/#firing-events","text":"When the action related to a user notification is executed, you can use UserNotificationHandler::fireEvent() to create the notifications: 1 2 3 4 5 6 7 $recipientIDs = []; // fill with user ids of the recipients of the notification UserNotificationHandler :: getInstance () -> fireEvent ( 'bar' , // event name 'com.woltlab.example.foo' , // event object type name new FooUserNotificationObject ( new Foo ( $fooID )), // object related to the event $recipientIDs );","title":"Firing Events"},{"location":"php/api/user_notifications/#marking-notifications-as-confirmed","text":"In some instances, you might want to manually mark user notifications as confirmed without the user manually confirming them, for example when they visit the page that is related to the user notification. In this case, you can use UserNotificationHandler::markAsConfirmed() : 1 2 3 4 5 6 7 8 $recipientIDs = []; // fill with user ids of the recipients of the notification $fooIDs = []; // fill with ids of related foo objects UserNotificationHandler :: getInstance () -> markAsConfirmed ( 'bar' , // event name 'com.woltlab.example.foo' , // event object type name $recipientIDs , $fooIDs );","title":"Marking Notifications as Confirmed"},{"location":"php/api/form_builder/dependencies/","text":"Form Node Dependencies # Form node dependencies allow to make parts of a form dynamically available or unavailable depending on the values of form fields. Dependencies are always added to the object whose visibility is determined by certain form fields. They are not added to the form field\u2019s whose values determine the visibility! An example is a text form field that should only be available if a certain option from a single selection form field is selected. Form builder\u2019s dependency system supports such scenarios and also automatically making form containers unavailable once all of its children are unavailable. If a form node has multiple dependencies and one of them is not met, the form node is unavailable. A form node not being available due to dependencies has to the following consequences: The form field value is not validated. It is, however, read from the request data as all request data needs to be read first so that the dependencies can determine whether they are met or not. No data is collected for the form field and returned by IFormDocument::getData() . In the actual form, the form field will be hidden via JavaScript. IFormFieldDependency # The basis of the dependencies is the IFormFieldDependency interface that has to be implemented by every dependency class. The interface requires the following methods: checkDependency() checks if the dependency is met, thus if the dependant form field should be considered available. dependentNode(IFormNode $node) and getDependentNode() can be used to set and get the node whose availability depends on the referenced form field. TFormNode::addDependency() automatically calls dependentNode(IFormNode $node) with itself as the dependent node, thus the dependent node is automatically set by the API. field(IFormField $field) and getField() can be used to set and get the form field that influences the availability of the dependent node. fieldId($fieldId) and getFieldId() can be used to set and get the id of the form field that influences the availability of the dependent node. getHtml() returns JavaScript code required to ensure the dependency in the form output. getId() returns the id of the dependency used to identify multiple dependencies of the same form node. static create($id) is the factory method that has to be used to create new dependencies with the given id. AbstractFormFieldDependency provides default implementations for all methods except for checkDependency() . Using fieldId($fieldId) instead of field(IFormField $field) makes sense when adding the dependency directly when setting up the form: 1 2 3 4 5 6 7 8 9 $container -> appendChildren ([ FooField :: create ( 'a' ), BarField :: create ( 'b' ) -> addDependency ( BazDependency :: create ( 'a' ) -> fieldId ( 'a' ) ) ]); Here, without an additional assignment, the first field with id a cannot be accessed thus fieldId($fieldId) should be used as the id of the relevant field is known. When the form is built, all dependencies that only know the id of the relevant field and do not have a reference for the actual object are populated with the actual form field objects. Default Dependencies # WoltLab Suite Core delivers the following default dependency classes by default: NonEmptyFormFieldDependency # NonEmptyFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is not empty (being empty is determined using PHP\u2019s empty() language construct). EmptyFormFieldDependency # This is the inverse of NonEmptyFormFieldDependency , checking for !empty() . ValueFormFieldDependency # ValueFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is from a specified list of of values (see methods values($values) and getValues() ). Additionally, via negate($negate = true) and isNegated() , the logic can also be inverted by requiring the value of the referenced form field not to be from a specified list of values. ValueIntervalFormFieldDependency # Only available since version 5.5. ValueIntervalFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is in a specific interval whose boundaries are set via minimum(?float $minimum = null) and maximum(?float $maximum = null) . IsNotClickedFormFieldDependency # IsNotClickedFormFieldDependency is a special dependency for ButtonFormField s . Refer to the documentation of ButtomFormField for details. JavaScript Implementation # To ensure that dependent node are correctly shown and hidden when changing the value of referenced form fields, every PHP dependency class has a corresponding JavaScript module that checks the dependency in the browser. Every JavaScript dependency has to extend WoltLabSuite/Core/Form/Builder/Field/Dependency/Abstract and implement the checkDependency() function, the JavaScript version of IFormFieldDependency::checkDependency() . All of the JavaScript dependency objects automatically register themselves during initialization with the WoltLabSuite/Core/Form/Builder/Field/Dependency/Manager which takes care of checking the dependencies at the correct points in time. Additionally, the dependency manager also ensures that form containers in which all children are hidden due to dependencies are also hidden and, once any child becomes available again, makes the container also available again. Every form container has to create a matching form container dependency object from a module based on WoltLabSuite/Core/Form/Builder/Field/Dependency/Abstract . Examples # If $booleanFormField is an instance of BooleanFormField and the text form field $textFormField should only be available if \u201cYes\u201d has been selected, the following condition has to be set up: 1 2 3 4 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'booleanFormField' ) -> field ( $booleanFormField ) ); If $singleSelectionFormField is an instance of SingleSelectionFormField that offers the options 1 , 2 , and 3 and $textFormField should only be available if 1 or 3 is selected, the following condition has to be set up: 1 2 3 4 5 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'singleSelectionFormField' ) -> field ( $singleSelectionFormField ) -> values ([ 1 , 3 ]) ); If, in contrast, $singleSelectionFormField has many available options and 7 is the only option for which $textFormField should not be available, negate() should be used: 1 2 3 4 5 6 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'singleSelectionFormField' ) -> field ( $singleSelectionFormField ) -> values ([ 7 ]) -> negate () );","title":"Dependencies"},{"location":"php/api/form_builder/dependencies/#form-node-dependencies","text":"Form node dependencies allow to make parts of a form dynamically available or unavailable depending on the values of form fields. Dependencies are always added to the object whose visibility is determined by certain form fields. They are not added to the form field\u2019s whose values determine the visibility! An example is a text form field that should only be available if a certain option from a single selection form field is selected. Form builder\u2019s dependency system supports such scenarios and also automatically making form containers unavailable once all of its children are unavailable. If a form node has multiple dependencies and one of them is not met, the form node is unavailable. A form node not being available due to dependencies has to the following consequences: The form field value is not validated. It is, however, read from the request data as all request data needs to be read first so that the dependencies can determine whether they are met or not. No data is collected for the form field and returned by IFormDocument::getData() . In the actual form, the form field will be hidden via JavaScript.","title":"Form Node Dependencies"},{"location":"php/api/form_builder/dependencies/#iformfielddependency","text":"The basis of the dependencies is the IFormFieldDependency interface that has to be implemented by every dependency class. The interface requires the following methods: checkDependency() checks if the dependency is met, thus if the dependant form field should be considered available. dependentNode(IFormNode $node) and getDependentNode() can be used to set and get the node whose availability depends on the referenced form field. TFormNode::addDependency() automatically calls dependentNode(IFormNode $node) with itself as the dependent node, thus the dependent node is automatically set by the API. field(IFormField $field) and getField() can be used to set and get the form field that influences the availability of the dependent node. fieldId($fieldId) and getFieldId() can be used to set and get the id of the form field that influences the availability of the dependent node. getHtml() returns JavaScript code required to ensure the dependency in the form output. getId() returns the id of the dependency used to identify multiple dependencies of the same form node. static create($id) is the factory method that has to be used to create new dependencies with the given id. AbstractFormFieldDependency provides default implementations for all methods except for checkDependency() . Using fieldId($fieldId) instead of field(IFormField $field) makes sense when adding the dependency directly when setting up the form: 1 2 3 4 5 6 7 8 9 $container -> appendChildren ([ FooField :: create ( 'a' ), BarField :: create ( 'b' ) -> addDependency ( BazDependency :: create ( 'a' ) -> fieldId ( 'a' ) ) ]); Here, without an additional assignment, the first field with id a cannot be accessed thus fieldId($fieldId) should be used as the id of the relevant field is known. When the form is built, all dependencies that only know the id of the relevant field and do not have a reference for the actual object are populated with the actual form field objects.","title":"IFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#default-dependencies","text":"WoltLab Suite Core delivers the following default dependency classes by default:","title":"Default Dependencies"},{"location":"php/api/form_builder/dependencies/#nonemptyformfielddependency","text":"NonEmptyFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is not empty (being empty is determined using PHP\u2019s empty() language construct).","title":"NonEmptyFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#emptyformfielddependency","text":"This is the inverse of NonEmptyFormFieldDependency , checking for !empty() .","title":"EmptyFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#valueformfielddependency","text":"ValueFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is from a specified list of of values (see methods values($values) and getValues() ). Additionally, via negate($negate = true) and isNegated() , the logic can also be inverted by requiring the value of the referenced form field not to be from a specified list of values.","title":"ValueFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#valueintervalformfielddependency","text":"Only available since version 5.5. ValueIntervalFormFieldDependency can be used to ensure that a node is only shown if the value of the referenced form field is in a specific interval whose boundaries are set via minimum(?float $minimum = null) and maximum(?float $maximum = null) .","title":"ValueIntervalFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#isnotclickedformfielddependency","text":"IsNotClickedFormFieldDependency is a special dependency for ButtonFormField s . Refer to the documentation of ButtomFormField for details.","title":"IsNotClickedFormFieldDependency"},{"location":"php/api/form_builder/dependencies/#javascript-implementation","text":"To ensure that dependent node are correctly shown and hidden when changing the value of referenced form fields, every PHP dependency class has a corresponding JavaScript module that checks the dependency in the browser. Every JavaScript dependency has to extend WoltLabSuite/Core/Form/Builder/Field/Dependency/Abstract and implement the checkDependency() function, the JavaScript version of IFormFieldDependency::checkDependency() . All of the JavaScript dependency objects automatically register themselves during initialization with the WoltLabSuite/Core/Form/Builder/Field/Dependency/Manager which takes care of checking the dependencies at the correct points in time. Additionally, the dependency manager also ensures that form containers in which all children are hidden due to dependencies are also hidden and, once any child becomes available again, makes the container also available again. Every form container has to create a matching form container dependency object from a module based on WoltLabSuite/Core/Form/Builder/Field/Dependency/Abstract .","title":"JavaScript Implementation"},{"location":"php/api/form_builder/dependencies/#examples","text":"If $booleanFormField is an instance of BooleanFormField and the text form field $textFormField should only be available if \u201cYes\u201d has been selected, the following condition has to be set up: 1 2 3 4 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'booleanFormField' ) -> field ( $booleanFormField ) ); If $singleSelectionFormField is an instance of SingleSelectionFormField that offers the options 1 , 2 , and 3 and $textFormField should only be available if 1 or 3 is selected, the following condition has to be set up: 1 2 3 4 5 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'singleSelectionFormField' ) -> field ( $singleSelectionFormField ) -> values ([ 1 , 3 ]) ); If, in contrast, $singleSelectionFormField has many available options and 7 is the only option for which $textFormField should not be available, negate() should be used: 1 2 3 4 5 6 $textFormField -> addDependency ( NonEmptyFormFieldDependency :: create ( 'singleSelectionFormField' ) -> field ( $singleSelectionFormField ) -> values ([ 7 ]) -> negate () );","title":"Examples"},{"location":"php/api/form_builder/form_fields/","text":"Form Builder Fields # Abstract Form Fields # The following form field classes cannot be instantiated directly because they are abstract, but they can/must be used when creating own form field classes. AbstractFormField # AbstractFormField is the abstract default implementation of the IFormField interface and it is expected that every implementation of IFormField implements the interface by extending this class. AbstractNumericFormField # AbstractNumericFormField is the abstract implementation of a form field handling a single numeric value. The class implements IAttributeFormField , IAutoCompleteFormField , ICssClassFormField , IImmutableFormField , IInputModeFormField , IMaximumFormField , IMinimumFormField , INullableFormField , IPlaceholderFormField and ISuffixedFormField . If the property $integerValues is true , the form field works with integer values, otherwise it works with floating point numbers. The methods step($step = null) and getStep() can be used to set and get the step attribute of the input element. The default step for form fields with integer values is 1 . Otherwise, the default step is any . AbstractFormFieldDecorator # Only available since version 5.4.5. AbstractFormFieldDecorator is a default implementation of a decorator for form fields that forwards calls to all methods defined in IFormField to the respective method of the decorated object. The class implements IFormfield . If the implementation of a more specific interface is required then the remaining methods must be implemented in the concrete decorator derived from AbstractFormFieldDecorator and the type of the $field property must be narrowed appropriately. General Form Fields # The following form fields are general reusable fields without any underlying context. BooleanFormField # BooleanFormField is used for boolean ( 0 or 1 , yes or no ) values. Objects of this class require a label. The return value of getSaveValue() is the integer representation of the boolean value, i.e. 0 or 1 . The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , and IImmutableFormField . CheckboxFormField # Only available since version 5.3.2. CheckboxFormField extends BooleanFormField and offers a simple HTML checkbox. ClassNameFormField # ClassNameFormField is a text form field that supports additional settings, specific to entering a PHP class name: classExists($classExists = true) and getClassExists() can be used to ensure that the entered class currently exists in the installation. By default, the existance of the entered class is required. implementedInterface($interface) and getImplementedInterface() can be used to ensure that the entered class implements the specified interface. By default, no interface is required. parentClass($parentClass) and getParentClass() can be used to ensure that the entered class extends the specified class. By default, no parent class is required. instantiable($instantiable = true) and isInstantiable() can be used to ensure that the entered class is instantiable. By default, entered classes have to instantiable. Additionally, the default id of a ClassNameFormField object is className , the default label is wcf.form.field.className , and if either an interface or a parent class is required, a default description is set if no description has already been set ( wcf.form.field.className.description.interface and wcf.form.field.className.description.parentClass , respectively). DateFormField # DateFormField is a form field to enter a date (and optionally a time). The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , IImmutableFormField , and INullableFormField . The following methods are specific to this form field class: earliestDate($earliestDate) and getEarliestDate() can be used to get and set the earliest selectable/valid date and latestDate($latestDate) and getLatestDate() can be used to get and set the latest selectable/valid date. The date passed to the setters must have the same format as set via saveValueFormat() . If a custom format is used, that format has to be set via saveValueFormat() before calling any of the setters. saveValueFormat($saveValueFormat) and getSaveValueFormat() can be used to specify the date format of the value returned by getSaveValue() . By default, U is used as format. The PHP manual provides an overview of supported formats. supportTime($supportsTime = true) and supportsTime() can be used to toggle whether, in addition to a date, a time can also be specified. By default, specifying a time is disabled. DescriptionFormField # DescriptionFormField is a multi-line text form field with description as the default id and wcf.global.description as the default label. EmailFormField # EmailFormField is a form field to enter an email address which is internally validated using UserUtil::isValidEmail() . The class implements IAttributeFormField , IAutoCompleteFormField , IAutoFocusFormField , ICssClassFormField , II18nFormField , IImmutableFormField , IInputModeFormField , IPatternFormField , and IPlaceholderFormField . FloatFormField # FloatFormField is an implementation of AbstractNumericFormField for floating point numbers. IconFormField # IconFormField is a form field to select a FontAwesome icon. IntegerFormField # IntegerFormField is an implementation of AbstractNumericFormField for integers. IsDisabledFormField # IsDisabledFormField is a boolean form field with isDisabled as the default id. ItemListFormField # ItemListFormField is a form field in which multiple values can be entered and returned in different formats as save value. The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , IImmutableFormField , and IMultipleFormField . The saveValueType($saveValueType) and getSaveValueType() methods are specific to this form field class and determine the format of the save value. The following save value types are supported: ItemListFormField::SAVE_VALUE_TYPE_ARRAY adds a custom data processor that writes the form field data directly in the parameters array and not in the data sub-array of the parameters array. ItemListFormField::SAVE_VALUE_TYPE_CSV lets the value be returned as a string in which the values are concatenated by commas. ItemListFormField::SAVE_VALUE_TYPE_NSV lets the value be returned as a string in which the values are concatenated by \\n . ItemListFormField::SAVE_VALUE_TYPE_SSV lets the value be returned as a string in which the values are concatenated by spaces. By default, ItemListFormField::SAVE_VALUE_TYPE_CSV is used. If ItemListFormField::SAVE_VALUE_TYPE_ARRAY is used as save value type, ItemListFormField objects register a custom form field data processor to add the relevant array into the $parameters array directly using the object property as the array key. MultilineTextFormField # MultilineTextFormField is a text form field that supports multiple rows of text. The methods rows($rows) and getRows() can be used to set and get the number of rows of the textarea elements. The default number of rows is 10 . These methods do not , however, restrict the number of text rows that can be entered. MultipleSelectionFormField # MultipleSelectionFormField is a form fields that allows the selection of multiple options out of a predefined list of available options. The class implements IAttributeFormField , ICssClassFormField , IFilterableSelectionFormField , IImmutableFormField , and INullableFormField . If the field is nullable and no option is selected, null is returned as the save value. RadioButtonFormField # RadioButtonFormField is a form fields that allows the selection of a single option out of a predefined list of available options using radiobuttons. The class implements IAttributeFormField , ICssClassFormField , IImmutableFormField , and ISelectionFormField . RatingFormField # RatingFormField is a form field to set a rating for an object. The class implements IImmutableFormField , IMaximumFormField , IMinimumFormField , and INullableFormField . Form fields of this class have rating as their default id, wcf.form.field.rating as their default label, 1 as their default minimum, and 5 as their default maximum. For this field, the minimum and maximum refer to the minimum and maximum rating an object can get. When the field is shown, there will be maximum() - minimum() + 1 icons be shown with additional CSS classes that can be set and gotten via defaultCssClasses(array $cssClasses) and getDefaultCssClasses() . If a rating values is set, the first getValue() icons will instead use the classes that can be set and gotten via activeCssClasses(array $cssClasses) and getActiveCssClasses() . By default, the only default class is fa-star-o and the active classes are fa-star and orange . ShowOrderFormField # ShowOrderFormField is a single selection form field for which the selected value determines the position at which an object is shown. The show order field provides a list of all siblings and the object will be positioned after the selected sibling. To insert objects at the very beginning, the options() automatically method prepends an additional option for that case so that only the existing siblings need to be passed. The default id of instances of this class is showOrder and their default label is wcf.form.field.showOrder . It is important that the relevant object property is always kept updated. Whenever a new object is added or an existing object is edited or delete, the values of the other objects have to be adjusted to ensure consecutive numbering. SingleSelectionFormField # SingleSelectionFormField is a form fields that allows the selection of a single option out of a predefined list of available options. The class implements ICssClassFormField , IFilterableSelectionFormField , IImmutableFormField , and INullableFormField . If the field is nullable and the current form field value is considered empty by PHP, null is returned as the save value. SortOrderFormField # SingleSelectionFormField is a single selection form field with default id sortOrder , default label wcf.global.showOrder and default options ASC: wcf.global.sortOrder.ascending and DESC: wcf.global.sortOrder.descending . TextFormField # TextFormField is a form field that allows entering a single line of text. The class implements IAttributeFormField , IAutoCompleteFormField , ICssClassFormField , IImmutableFormField , II18nFormField , IInputModeFormField , IMaximumLengthFormField , IMinimumLengthFormField , IPatternFormField , and IPlaceholderFormField . TitleFormField # TitleFormField is a text form field with title as the default id and wcf.global.title as the default label. UrlFormField # UrlFormField is a text form field whose values are checked via Url::is() . Specific Fields # The following form fields are reusable fields that generally are bound to a certain API or DatabaseObject implementation. AclFormField # AclFormField is used for setting up acl values for specific objects. The class implements IObjectTypeFormField and requires an object type of the object type definition com.woltlab.wcf.acl . Additionally, the class provides the methods categoryName($categoryName) and getCategoryName() that allow setting a specific name or filter for the acl option categories whose acl options are shown. A category name of null signals that no category filter is used. Since version 5.5, the category name also supports filtering using a wildcard like user.* , see WoltLab/WCF#4355 . AclFormField objects register a custom form field data processor to add the relevant ACL object type id into the $parameters array directly using {$objectProperty}_aclObjectTypeID as the array key. The relevant database object action method is expected, based on the given ACL object type id, to save the ACL option values appropriately. ButtonFormField # Only available since version 5.4. ButtonFormField shows a submit button as part of the form. The class implements IAttributeFormField and ICssClassFormField . Specifically for this form field, there is the IsNotClickedFormFieldDependency dependency with which certain parts of the form will only be processed if the relevent button has not clicked. CaptchaFormField # CaptchaFormField is used to add captcha protection to the form. You must specify a captcha object type ( com.woltlab.wcf.captcha ) using the objectType() method. ColorFormField # Only available since version 5.5. ColorFormField is used to specify RGBA colors using the rgba(r, g, b, a) format. The class implements IImmutableFormField . ContentLanguageFormField # ContentLanguageFormField is used to select the content language of an object. Fields of this class are only available if multilingualism is enabled and if there are content languages. The class implements IImmutableFormField . LabelFormField # LabelFormField is used to select a label from a specific label group. The class implements IObjectTypeFormNode . The labelGroup(ViewableLabelGroup $labelGroup) and getLabelGroup() methods are specific to this form field class and can be used to set and get the label group whose labels can be selected. Additionally, there is the static method createFields($objectType, array $labelGroups, $objectProperty = 'labelIDs) that can be used to create all relevant label form fields for a given list of label groups. In most cases, LabelFormField::createFields() should be used. OptionFormField # OptionFormField is an item list form field to set a list of options. The class implements IPackagesFormField and only options of the set packages are considered available. The default label of instances of this class is wcf.form.field.option and their default id is options . SimpleAclFormField # SimpleAclFormField is used for setting up simple acl values (one yes / no option per user and user group) for specific objects. SimpleAclFormField objects register a custom form field data processor to add the relevant simple ACL data array into the $parameters array directly using the object property as the array key. Since version 5.5, the field also supports inverted permissions, see WoltLab/WCF#4570 . The SimpleAclFormField supports inverted permissions, allowing the administrator to grant access to all non-selected users and groups. If this behavior is desired, it needs to be enabled by calling supportInvertedPermissions . An invertPermissions key containing a boolean value with the users selection will be provided together with the ACL values when saving the field. SingleMediaSelectionFormField # SingleMediaSelectionFormField is used to select a specific media file. The class implements IImmutableFormField . The following methods are specific to this form field class: imageOnly($imageOnly = true) and isImageOnly() can be used to set and check if only images may be selected. getMedia() returns the media file based on the current field value if a field is set. TagFormField # TagFormField is a form field to enter tags. The class implements IAttributeFormField and IObjectTypeFormNode . Arrays passed to TagFormField::values() can contain tag names as strings and Tag objects. The default label of instances of this class is wcf.tagging.tags and their default description is wcf.tagging.tags.description . TagFormField objects register a custom form field data processor to add the array with entered tag names into the $parameters array directly using the object property as the array key. UploadFormField # UploadFormField is a form field that allows uploading files by the user. UploadFormField objects register a custom form field data processor to add the array of wcf\\system\\file\\upload\\UploadFile\\UploadFile into the $parameters array directly using the object property as the array key. Also it registers the removed files as an array of wcf\\system\\file\\upload\\UploadFile\\UploadFile into the $parameters array directly using the object property with the suffix _removedFiles as the array key. The field supports additional settings: - imageOnly($imageOnly = true) and isImageOnly() can be used to ensure that the uploaded files are only images. - allowSvgImage($allowSvgImages = true) and svgImageAllowed() can be used to allow SVG images, if the image only mode is enabled (otherwise, the method will throw an exception). By default, SVG images are not allowed. Provide value from database object # To provide values from a database object, you should implement the method get{$objectProperty}UploadFileLocations() to your database object class. This method must return an array of strings with the locations of the files. Process files # To process files in the database object action class, you must rename the file to the final destination. You get the temporary location, by calling the method getLocation() on the given UploadFile objects. After that, you call setProcessed($location) with $location contains the new file location. This method sets the isProcessed flag to true and saves the new location. For updating files, it is relevant, whether a given file is already processed or not. For this case, the UploadFile object has an method isProcessed() which indicates, whether a file is already processed or new uploaded. UserFormField # UserFormField is a form field to enter existing users. The class implements IAutoCompleteFormField , IAutoFocusFormField , IImmutableFormField , IMultipleFormField , and INullableFormField . While the user is presented the names of the specified users in the user interface, the field returns the ids of the users as data. The relevant UserProfile objects can be accessed via the getUsers() method. UserPasswordField # Only available since version 5.4. UserPasswordField is a form field for users' to enter their current password. The class implements IAttributeFormField , IAttributeFormField , IAutoCompleteFormField , IAutoFocusFormField , and IPlaceholderFormField UserGroupOptionFormField # UserGroupOptionFormField is an item list form field to set a list of user group options/permissions. The class implements IPackagesFormField and only user group options of the set packages are considered available. The default label of instances of this class is wcf.form.field.userGroupOption and their default id is permissions . UsernameFormField # UsernameFormField is used for entering one non-existing username. The class implements IAttributeFormField , IImmutableFormField , IMaximumLengthFormField , IMinimumLengthFormField , INullableFormField , and IPlaceholderFormField . As usernames have a system-wide restriction of a minimum length of 3 and a maximum length of 100 characters, these values are also used as the default value for the field\u2019s minimum and maximum length. Wysiwyg form container # To integrate a wysiwyg editor into a form, you have to create a WysiwygFormContainer object. This container takes care of creating all necessary form nodes listed below for a wysiwyg editor. When creating the container object, its id has to be the id of the form field that will manage the actual text. The following methods are specific to this form container class: addSettingsNode(IFormChildNode $settingsNode) and addSettingsNodes(array $settingsNodes) can be used to add nodes to the settings tab container. attachmentData($objectType, $parentObjectID) can be used to set the data relevant for attachment support. By default, not attachment data is set, thus attachments are not supported. getAttachmentField() , getPollContainer() , getSettingsContainer() , getSmiliesContainer() , and getWysiwygField() can be used to get the different components of the wysiwyg form container once the form has been built. enablePreviewButton($enablePreviewButton) can be used to set whether the preview button for the message is shown or not. By default, the preview button is shown. This method is only relevant before the form is built. Afterwards, the preview button availability can not be changed. Only available since WoltLab Suite Core 5.3. getObjectId() returns the id of the edited object or 0 if no object is edited. getPreselect() , preselect($preselect) can be used to set the value of the wysiwyg tab menu's data-preselect attribute used to determine which tab is preselected. By default, the preselect is 'true' which is used to pre-select the first tab. messageObjectType($messageObjectType) can be used to set the message object type. pollObjectType($pollObjectType) can be used to set the poll object type. By default, no poll object type is set, thus the poll form field container is not available. supportMentions($supportMentions) can be used to set if mentions are supported. By default, mentions are not supported. This method is only relevant before the form is built. Afterwards, mention support can only be changed via the wysiwyg form field. supportSmilies($supportSmilies) can be used to set if smilies are supported. By default, smilies are supported. This method is only relevant before the form is built. Afterwards, smiley availability can only be changed via changing the availability of the smilies form container. WysiwygAttachmentFormField # WysiwygAttachmentFormField provides attachment support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . The methods attachmentHandler(AttachmentHandler $attachmentHandler) and getAttachmentHandler() can be used to set and get the AttachmentHandler object that is used for uploaded attachments. WysiwygPollFormContainer # WysiwygPollFormContainer provides poll support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . WysiwygPollFormContainer contains all form fields that are required to create polls and requires edited objects to implement IPollContainer . The following methods are specific to this form container class: getEndTimeField() returns the form field to set the end time of the poll once the form has been built. getIsChangeableField() returns the form field to set if poll votes can be changed once the form has been built. getIsPublicField() returns the form field to set if poll results are public once the form has been built. getMaxVotesField() returns the form field to set the maximum number of votes once the form has been built. getOptionsField() returns the form field to set the poll options once the form has been built. getQuestionField() returns the form field to set the poll question once the form has been built. getResultsRequireVoteField() returns the form field to set if viewing the poll results requires voting once the form has been built. getSortByVotesField() returns the form field to set if the results are sorted by votes once the form has been built. WysiwygSmileyFormContainer # WysiwygSmileyFormContainer provides smiley support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . WysiwygSmileyFormContainer creates a sub-tab for each smiley category. WysiwygSmileyFormNode # WysiwygSmileyFormNode is contains the smilies of a specific category. This class should not be used directly but only via WysiwygSmileyFormContainer . Example # The following code creates a WYSIWYG editor component for a message object property. As smilies are supported by default and an attachment object type is given, the tab menu below the editor has two tabs: \u201cSmilies\u201d and \u201cAttachments\u201d. Additionally, mentions and quotes are supported. 1 2 3 4 5 6 WysiwygFormContainer :: create ( 'message' ) -> label ( 'foo.bar.message' ) -> messageObjectType ( 'com.example.foo.bar' ) -> attachmentData ( 'com.example.foo.bar' ) -> supportMentions () -> supportQuotes () WysiwygFormField # WysiwygFormField is used for wysiwyg editor form fields. This class should, in general, not be used directly but only via WysiwygFormContainer . The class implements IAttributeFormField , IMaximumLengthFormField , IMinimumLengthFormField , and IObjectTypeFormNode and requires an object type of the object type definition com.woltlab.wcf.message . The following methods are specific to this form field class: autosaveId($autosaveId) and getAutosaveId() can be used enable automatically saving the current editor contents in the browser using the given id. An empty string signals that autosaving is disabled. lastEditTime($lastEditTime) and getLastEditTime() can be used to set the last time the contents have been edited and saved so that the JavaScript can determine if the contents stored in the browser are older or newer. 0 signals that no last edit time has been set. supportAttachments($supportAttachments) and supportsAttachments() can be used to set and check if the form field supports attachments. It is not sufficient to simply signal attachment support via these methods for attachments to work. These methods are relevant internally to signal the Javascript code that the editor supports attachments. Actual attachment support is provided by WysiwygAttachmentFormField . supportMentions($supportMentions) and supportsMentions() can be used to set and check if the form field supports mentions of other users. WysiwygFormField objects register a custom form field data processor to add the relevant simple ACL data array into the $parameters array directly using the object property as the array key. TWysiwygFormNode # All form nodes that need to know the id of the WysiwygFormField field should use TWysiwygFormNode . This trait provides getWysiwygId() and wysiwygId($wysiwygId) to get and set the relevant wysiwyg editor id. Application-Specific Form Fields # WoltLab Suite Forum # MultipleBoardSelectionFormField # Only available since version 5.5. MultipleBoardSelectionFormField is used to select multiple forums. The class implements IAttributeFormField , ICssClassFormField , and IImmutableFormField . The field supports additional settings: boardNodeList(BoardNodeList $boardNodeList): self and getBoardNodeList(): BoardNodeList are used to set and get the list of board nodes used to render the board selection. boardNodeList(BoardNodeList $boardNodeList): self will automatically call readNodeTree() on the given board node list. categoriesSelectable(bool $categoriesSelectable = true): self and areCategoriesSelectable(): bool are used to set and check if the categories in the board node list are selectable. By default, categories are selectable. This option is useful if only actual boards, in which threads can be posted, should be selectable but the categories must still be shown so that the overall forum structure is still properly shown. supportExternalLinks(bool $supportExternalLinks): self and supportsExternalLinks(): bool are used to set and check if external links will be shown in the selection list. By default, external links are shown. Like in the example given before, in cases where only actual boards, in which threads can be posted, are relevant, this option allows to exclude external links. Single-Use Form Fields # The following form fields are specific for certain forms and hardly reusable in other contexts. BBCodeAttributesFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the attributes of a BBCode. DevtoolsProjectExcludedPackagesFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the excluded packages of a devtools project. DevtoolsProjectInstructionsFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the installation and update instructions of a devtools project. DevtoolsProjectOptionalPackagesFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the optional packages of a devtools project. DevtoolsProjectRequiredPackagesFormField # DevtoolsProjectExcludedPackagesFormField is a form field for setting the required packages of a devtools project.","title":"Fields"},{"location":"php/api/form_builder/form_fields/#form-builder-fields","text":"","title":"Form Builder Fields"},{"location":"php/api/form_builder/form_fields/#abstract-form-fields","text":"The following form field classes cannot be instantiated directly because they are abstract, but they can/must be used when creating own form field classes.","title":"Abstract Form Fields"},{"location":"php/api/form_builder/form_fields/#abstractformfield","text":"AbstractFormField is the abstract default implementation of the IFormField interface and it is expected that every implementation of IFormField implements the interface by extending this class.","title":"AbstractFormField"},{"location":"php/api/form_builder/form_fields/#abstractnumericformfield","text":"AbstractNumericFormField is the abstract implementation of a form field handling a single numeric value. The class implements IAttributeFormField , IAutoCompleteFormField , ICssClassFormField , IImmutableFormField , IInputModeFormField , IMaximumFormField , IMinimumFormField , INullableFormField , IPlaceholderFormField and ISuffixedFormField . If the property $integerValues is true , the form field works with integer values, otherwise it works with floating point numbers. The methods step($step = null) and getStep() can be used to set and get the step attribute of the input element. The default step for form fields with integer values is 1 . Otherwise, the default step is any .","title":"AbstractNumericFormField"},{"location":"php/api/form_builder/form_fields/#abstractformfielddecorator","text":"Only available since version 5.4.5. AbstractFormFieldDecorator is a default implementation of a decorator for form fields that forwards calls to all methods defined in IFormField to the respective method of the decorated object. The class implements IFormfield . If the implementation of a more specific interface is required then the remaining methods must be implemented in the concrete decorator derived from AbstractFormFieldDecorator and the type of the $field property must be narrowed appropriately.","title":"AbstractFormFieldDecorator"},{"location":"php/api/form_builder/form_fields/#general-form-fields","text":"The following form fields are general reusable fields without any underlying context.","title":"General Form Fields"},{"location":"php/api/form_builder/form_fields/#booleanformfield","text":"BooleanFormField is used for boolean ( 0 or 1 , yes or no ) values. Objects of this class require a label. The return value of getSaveValue() is the integer representation of the boolean value, i.e. 0 or 1 . The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , and IImmutableFormField .","title":"BooleanFormField"},{"location":"php/api/form_builder/form_fields/#checkboxformfield","text":"Only available since version 5.3.2. CheckboxFormField extends BooleanFormField and offers a simple HTML checkbox.","title":"CheckboxFormField"},{"location":"php/api/form_builder/form_fields/#classnameformfield","text":"ClassNameFormField is a text form field that supports additional settings, specific to entering a PHP class name: classExists($classExists = true) and getClassExists() can be used to ensure that the entered class currently exists in the installation. By default, the existance of the entered class is required. implementedInterface($interface) and getImplementedInterface() can be used to ensure that the entered class implements the specified interface. By default, no interface is required. parentClass($parentClass) and getParentClass() can be used to ensure that the entered class extends the specified class. By default, no parent class is required. instantiable($instantiable = true) and isInstantiable() can be used to ensure that the entered class is instantiable. By default, entered classes have to instantiable. Additionally, the default id of a ClassNameFormField object is className , the default label is wcf.form.field.className , and if either an interface or a parent class is required, a default description is set if no description has already been set ( wcf.form.field.className.description.interface and wcf.form.field.className.description.parentClass , respectively).","title":"ClassNameFormField"},{"location":"php/api/form_builder/form_fields/#dateformfield","text":"DateFormField is a form field to enter a date (and optionally a time). The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , IImmutableFormField , and INullableFormField . The following methods are specific to this form field class: earliestDate($earliestDate) and getEarliestDate() can be used to get and set the earliest selectable/valid date and latestDate($latestDate) and getLatestDate() can be used to get and set the latest selectable/valid date. The date passed to the setters must have the same format as set via saveValueFormat() . If a custom format is used, that format has to be set via saveValueFormat() before calling any of the setters. saveValueFormat($saveValueFormat) and getSaveValueFormat() can be used to specify the date format of the value returned by getSaveValue() . By default, U is used as format. The PHP manual provides an overview of supported formats. supportTime($supportsTime = true) and supportsTime() can be used to toggle whether, in addition to a date, a time can also be specified. By default, specifying a time is disabled.","title":"DateFormField"},{"location":"php/api/form_builder/form_fields/#descriptionformfield","text":"DescriptionFormField is a multi-line text form field with description as the default id and wcf.global.description as the default label.","title":"DescriptionFormField"},{"location":"php/api/form_builder/form_fields/#emailformfield","text":"EmailFormField is a form field to enter an email address which is internally validated using UserUtil::isValidEmail() . The class implements IAttributeFormField , IAutoCompleteFormField , IAutoFocusFormField , ICssClassFormField , II18nFormField , IImmutableFormField , IInputModeFormField , IPatternFormField , and IPlaceholderFormField .","title":"EmailFormField"},{"location":"php/api/form_builder/form_fields/#floatformfield","text":"FloatFormField is an implementation of AbstractNumericFormField for floating point numbers.","title":"FloatFormField"},{"location":"php/api/form_builder/form_fields/#iconformfield","text":"IconFormField is a form field to select a FontAwesome icon.","title":"IconFormField"},{"location":"php/api/form_builder/form_fields/#integerformfield","text":"IntegerFormField is an implementation of AbstractNumericFormField for integers.","title":"IntegerFormField"},{"location":"php/api/form_builder/form_fields/#isdisabledformfield","text":"IsDisabledFormField is a boolean form field with isDisabled as the default id.","title":"IsDisabledFormField"},{"location":"php/api/form_builder/form_fields/#itemlistformfield","text":"ItemListFormField is a form field in which multiple values can be entered and returned in different formats as save value. The class implements IAttributeFormField , IAutoFocusFormField , ICssClassFormField , IImmutableFormField , and IMultipleFormField . The saveValueType($saveValueType) and getSaveValueType() methods are specific to this form field class and determine the format of the save value. The following save value types are supported: ItemListFormField::SAVE_VALUE_TYPE_ARRAY adds a custom data processor that writes the form field data directly in the parameters array and not in the data sub-array of the parameters array. ItemListFormField::SAVE_VALUE_TYPE_CSV lets the value be returned as a string in which the values are concatenated by commas. ItemListFormField::SAVE_VALUE_TYPE_NSV lets the value be returned as a string in which the values are concatenated by \\n . ItemListFormField::SAVE_VALUE_TYPE_SSV lets the value be returned as a string in which the values are concatenated by spaces. By default, ItemListFormField::SAVE_VALUE_TYPE_CSV is used. If ItemListFormField::SAVE_VALUE_TYPE_ARRAY is used as save value type, ItemListFormField objects register a custom form field data processor to add the relevant array into the $parameters array directly using the object property as the array key.","title":"ItemListFormField"},{"location":"php/api/form_builder/form_fields/#multilinetextformfield","text":"MultilineTextFormField is a text form field that supports multiple rows of text. The methods rows($rows) and getRows() can be used to set and get the number of rows of the textarea elements. The default number of rows is 10 . These methods do not , however, restrict the number of text rows that can be entered.","title":"MultilineTextFormField"},{"location":"php/api/form_builder/form_fields/#multipleselectionformfield","text":"MultipleSelectionFormField is a form fields that allows the selection of multiple options out of a predefined list of available options. The class implements IAttributeFormField , ICssClassFormField , IFilterableSelectionFormField , IImmutableFormField , and INullableFormField . If the field is nullable and no option is selected, null is returned as the save value.","title":"MultipleSelectionFormField"},{"location":"php/api/form_builder/form_fields/#radiobuttonformfield","text":"RadioButtonFormField is a form fields that allows the selection of a single option out of a predefined list of available options using radiobuttons. The class implements IAttributeFormField , ICssClassFormField , IImmutableFormField , and ISelectionFormField .","title":"RadioButtonFormField"},{"location":"php/api/form_builder/form_fields/#ratingformfield","text":"RatingFormField is a form field to set a rating for an object. The class implements IImmutableFormField , IMaximumFormField , IMinimumFormField , and INullableFormField . Form fields of this class have rating as their default id, wcf.form.field.rating as their default label, 1 as their default minimum, and 5 as their default maximum. For this field, the minimum and maximum refer to the minimum and maximum rating an object can get. When the field is shown, there will be maximum() - minimum() + 1 icons be shown with additional CSS classes that can be set and gotten via defaultCssClasses(array $cssClasses) and getDefaultCssClasses() . If a rating values is set, the first getValue() icons will instead use the classes that can be set and gotten via activeCssClasses(array $cssClasses) and getActiveCssClasses() . By default, the only default class is fa-star-o and the active classes are fa-star and orange .","title":"RatingFormField"},{"location":"php/api/form_builder/form_fields/#showorderformfield","text":"ShowOrderFormField is a single selection form field for which the selected value determines the position at which an object is shown. The show order field provides a list of all siblings and the object will be positioned after the selected sibling. To insert objects at the very beginning, the options() automatically method prepends an additional option for that case so that only the existing siblings need to be passed. The default id of instances of this class is showOrder and their default label is wcf.form.field.showOrder . It is important that the relevant object property is always kept updated. Whenever a new object is added or an existing object is edited or delete, the values of the other objects have to be adjusted to ensure consecutive numbering.","title":"ShowOrderFormField"},{"location":"php/api/form_builder/form_fields/#singleselectionformfield","text":"SingleSelectionFormField is a form fields that allows the selection of a single option out of a predefined list of available options. The class implements ICssClassFormField , IFilterableSelectionFormField , IImmutableFormField , and INullableFormField . If the field is nullable and the current form field value is considered empty by PHP, null is returned as the save value.","title":"SingleSelectionFormField"},{"location":"php/api/form_builder/form_fields/#sortorderformfield","text":"SingleSelectionFormField is a single selection form field with default id sortOrder , default label wcf.global.showOrder and default options ASC: wcf.global.sortOrder.ascending and DESC: wcf.global.sortOrder.descending .","title":"SortOrderFormField"},{"location":"php/api/form_builder/form_fields/#textformfield","text":"TextFormField is a form field that allows entering a single line of text. The class implements IAttributeFormField , IAutoCompleteFormField , ICssClassFormField , IImmutableFormField , II18nFormField , IInputModeFormField , IMaximumLengthFormField , IMinimumLengthFormField , IPatternFormField , and IPlaceholderFormField .","title":"TextFormField"},{"location":"php/api/form_builder/form_fields/#titleformfield","text":"TitleFormField is a text form field with title as the default id and wcf.global.title as the default label.","title":"TitleFormField"},{"location":"php/api/form_builder/form_fields/#urlformfield","text":"UrlFormField is a text form field whose values are checked via Url::is() .","title":"UrlFormField"},{"location":"php/api/form_builder/form_fields/#specific-fields","text":"The following form fields are reusable fields that generally are bound to a certain API or DatabaseObject implementation.","title":"Specific Fields"},{"location":"php/api/form_builder/form_fields/#aclformfield","text":"AclFormField is used for setting up acl values for specific objects. The class implements IObjectTypeFormField and requires an object type of the object type definition com.woltlab.wcf.acl . Additionally, the class provides the methods categoryName($categoryName) and getCategoryName() that allow setting a specific name or filter for the acl option categories whose acl options are shown. A category name of null signals that no category filter is used. Since version 5.5, the category name also supports filtering using a wildcard like user.* , see WoltLab/WCF#4355 . AclFormField objects register a custom form field data processor to add the relevant ACL object type id into the $parameters array directly using {$objectProperty}_aclObjectTypeID as the array key. The relevant database object action method is expected, based on the given ACL object type id, to save the ACL option values appropriately.","title":"AclFormField"},{"location":"php/api/form_builder/form_fields/#buttonformfield","text":"Only available since version 5.4. ButtonFormField shows a submit button as part of the form. The class implements IAttributeFormField and ICssClassFormField . Specifically for this form field, there is the IsNotClickedFormFieldDependency dependency with which certain parts of the form will only be processed if the relevent button has not clicked.","title":"ButtonFormField"},{"location":"php/api/form_builder/form_fields/#captchaformfield","text":"CaptchaFormField is used to add captcha protection to the form. You must specify a captcha object type ( com.woltlab.wcf.captcha ) using the objectType() method.","title":"CaptchaFormField"},{"location":"php/api/form_builder/form_fields/#colorformfield","text":"Only available since version 5.5. ColorFormField is used to specify RGBA colors using the rgba(r, g, b, a) format. The class implements IImmutableFormField .","title":"ColorFormField"},{"location":"php/api/form_builder/form_fields/#contentlanguageformfield","text":"ContentLanguageFormField is used to select the content language of an object. Fields of this class are only available if multilingualism is enabled and if there are content languages. The class implements IImmutableFormField .","title":"ContentLanguageFormField"},{"location":"php/api/form_builder/form_fields/#labelformfield","text":"LabelFormField is used to select a label from a specific label group. The class implements IObjectTypeFormNode . The labelGroup(ViewableLabelGroup $labelGroup) and getLabelGroup() methods are specific to this form field class and can be used to set and get the label group whose labels can be selected. Additionally, there is the static method createFields($objectType, array $labelGroups, $objectProperty = 'labelIDs) that can be used to create all relevant label form fields for a given list of label groups. In most cases, LabelFormField::createFields() should be used.","title":"LabelFormField"},{"location":"php/api/form_builder/form_fields/#optionformfield","text":"OptionFormField is an item list form field to set a list of options. The class implements IPackagesFormField and only options of the set packages are considered available. The default label of instances of this class is wcf.form.field.option and their default id is options .","title":"OptionFormField"},{"location":"php/api/form_builder/form_fields/#simpleaclformfield","text":"SimpleAclFormField is used for setting up simple acl values (one yes / no option per user and user group) for specific objects. SimpleAclFormField objects register a custom form field data processor to add the relevant simple ACL data array into the $parameters array directly using the object property as the array key. Since version 5.5, the field also supports inverted permissions, see WoltLab/WCF#4570 . The SimpleAclFormField supports inverted permissions, allowing the administrator to grant access to all non-selected users and groups. If this behavior is desired, it needs to be enabled by calling supportInvertedPermissions . An invertPermissions key containing a boolean value with the users selection will be provided together with the ACL values when saving the field.","title":"SimpleAclFormField"},{"location":"php/api/form_builder/form_fields/#singlemediaselectionformfield","text":"SingleMediaSelectionFormField is used to select a specific media file. The class implements IImmutableFormField . The following methods are specific to this form field class: imageOnly($imageOnly = true) and isImageOnly() can be used to set and check if only images may be selected. getMedia() returns the media file based on the current field value if a field is set.","title":"SingleMediaSelectionFormField"},{"location":"php/api/form_builder/form_fields/#tagformfield","text":"TagFormField is a form field to enter tags. The class implements IAttributeFormField and IObjectTypeFormNode . Arrays passed to TagFormField::values() can contain tag names as strings and Tag objects. The default label of instances of this class is wcf.tagging.tags and their default description is wcf.tagging.tags.description . TagFormField objects register a custom form field data processor to add the array with entered tag names into the $parameters array directly using the object property as the array key.","title":"TagFormField"},{"location":"php/api/form_builder/form_fields/#uploadformfield","text":"UploadFormField is a form field that allows uploading files by the user. UploadFormField objects register a custom form field data processor to add the array of wcf\\system\\file\\upload\\UploadFile\\UploadFile into the $parameters array directly using the object property as the array key. Also it registers the removed files as an array of wcf\\system\\file\\upload\\UploadFile\\UploadFile into the $parameters array directly using the object property with the suffix _removedFiles as the array key. The field supports additional settings: - imageOnly($imageOnly = true) and isImageOnly() can be used to ensure that the uploaded files are only images. - allowSvgImage($allowSvgImages = true) and svgImageAllowed() can be used to allow SVG images, if the image only mode is enabled (otherwise, the method will throw an exception). By default, SVG images are not allowed.","title":"UploadFormField"},{"location":"php/api/form_builder/form_fields/#provide-value-from-database-object","text":"To provide values from a database object, you should implement the method get{$objectProperty}UploadFileLocations() to your database object class. This method must return an array of strings with the locations of the files.","title":"Provide value from database object"},{"location":"php/api/form_builder/form_fields/#process-files","text":"To process files in the database object action class, you must rename the file to the final destination. You get the temporary location, by calling the method getLocation() on the given UploadFile objects. After that, you call setProcessed($location) with $location contains the new file location. This method sets the isProcessed flag to true and saves the new location. For updating files, it is relevant, whether a given file is already processed or not. For this case, the UploadFile object has an method isProcessed() which indicates, whether a file is already processed or new uploaded.","title":"Process files"},{"location":"php/api/form_builder/form_fields/#userformfield","text":"UserFormField is a form field to enter existing users. The class implements IAutoCompleteFormField , IAutoFocusFormField , IImmutableFormField , IMultipleFormField , and INullableFormField . While the user is presented the names of the specified users in the user interface, the field returns the ids of the users as data. The relevant UserProfile objects can be accessed via the getUsers() method.","title":"UserFormField"},{"location":"php/api/form_builder/form_fields/#userpasswordfield","text":"Only available since version 5.4. UserPasswordField is a form field for users' to enter their current password. The class implements IAttributeFormField , IAttributeFormField , IAutoCompleteFormField , IAutoFocusFormField , and IPlaceholderFormField","title":"UserPasswordField"},{"location":"php/api/form_builder/form_fields/#usergroupoptionformfield","text":"UserGroupOptionFormField is an item list form field to set a list of user group options/permissions. The class implements IPackagesFormField and only user group options of the set packages are considered available. The default label of instances of this class is wcf.form.field.userGroupOption and their default id is permissions .","title":"UserGroupOptionFormField"},{"location":"php/api/form_builder/form_fields/#usernameformfield","text":"UsernameFormField is used for entering one non-existing username. The class implements IAttributeFormField , IImmutableFormField , IMaximumLengthFormField , IMinimumLengthFormField , INullableFormField , and IPlaceholderFormField . As usernames have a system-wide restriction of a minimum length of 3 and a maximum length of 100 characters, these values are also used as the default value for the field\u2019s minimum and maximum length.","title":"UsernameFormField"},{"location":"php/api/form_builder/form_fields/#wysiwyg-form-container","text":"To integrate a wysiwyg editor into a form, you have to create a WysiwygFormContainer object. This container takes care of creating all necessary form nodes listed below for a wysiwyg editor. When creating the container object, its id has to be the id of the form field that will manage the actual text. The following methods are specific to this form container class: addSettingsNode(IFormChildNode $settingsNode) and addSettingsNodes(array $settingsNodes) can be used to add nodes to the settings tab container. attachmentData($objectType, $parentObjectID) can be used to set the data relevant for attachment support. By default, not attachment data is set, thus attachments are not supported. getAttachmentField() , getPollContainer() , getSettingsContainer() , getSmiliesContainer() , and getWysiwygField() can be used to get the different components of the wysiwyg form container once the form has been built. enablePreviewButton($enablePreviewButton) can be used to set whether the preview button for the message is shown or not. By default, the preview button is shown. This method is only relevant before the form is built. Afterwards, the preview button availability can not be changed. Only available since WoltLab Suite Core 5.3. getObjectId() returns the id of the edited object or 0 if no object is edited. getPreselect() , preselect($preselect) can be used to set the value of the wysiwyg tab menu's data-preselect attribute used to determine which tab is preselected. By default, the preselect is 'true' which is used to pre-select the first tab. messageObjectType($messageObjectType) can be used to set the message object type. pollObjectType($pollObjectType) can be used to set the poll object type. By default, no poll object type is set, thus the poll form field container is not available. supportMentions($supportMentions) can be used to set if mentions are supported. By default, mentions are not supported. This method is only relevant before the form is built. Afterwards, mention support can only be changed via the wysiwyg form field. supportSmilies($supportSmilies) can be used to set if smilies are supported. By default, smilies are supported. This method is only relevant before the form is built. Afterwards, smiley availability can only be changed via changing the availability of the smilies form container.","title":"Wysiwyg form container"},{"location":"php/api/form_builder/form_fields/#wysiwygattachmentformfield","text":"WysiwygAttachmentFormField provides attachment support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . The methods attachmentHandler(AttachmentHandler $attachmentHandler) and getAttachmentHandler() can be used to set and get the AttachmentHandler object that is used for uploaded attachments.","title":"WysiwygAttachmentFormField"},{"location":"php/api/form_builder/form_fields/#wysiwygpollformcontainer","text":"WysiwygPollFormContainer provides poll support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . WysiwygPollFormContainer contains all form fields that are required to create polls and requires edited objects to implement IPollContainer . The following methods are specific to this form container class: getEndTimeField() returns the form field to set the end time of the poll once the form has been built. getIsChangeableField() returns the form field to set if poll votes can be changed once the form has been built. getIsPublicField() returns the form field to set if poll results are public once the form has been built. getMaxVotesField() returns the form field to set the maximum number of votes once the form has been built. getOptionsField() returns the form field to set the poll options once the form has been built. getQuestionField() returns the form field to set the poll question once the form has been built. getResultsRequireVoteField() returns the form field to set if viewing the poll results requires voting once the form has been built. getSortByVotesField() returns the form field to set if the results are sorted by votes once the form has been built.","title":"WysiwygPollFormContainer"},{"location":"php/api/form_builder/form_fields/#wysiwygsmileyformcontainer","text":"WysiwygSmileyFormContainer provides smiley support for a wysiwyg editor via a tab in the menu below the editor. This class should not be used directly but only via WysiwygFormContainer . WysiwygSmileyFormContainer creates a sub-tab for each smiley category.","title":"WysiwygSmileyFormContainer"},{"location":"php/api/form_builder/form_fields/#wysiwygsmileyformnode","text":"WysiwygSmileyFormNode is contains the smilies of a specific category. This class should not be used directly but only via WysiwygSmileyFormContainer .","title":"WysiwygSmileyFormNode"},{"location":"php/api/form_builder/form_fields/#example","text":"The following code creates a WYSIWYG editor component for a message object property. As smilies are supported by default and an attachment object type is given, the tab menu below the editor has two tabs: \u201cSmilies\u201d and \u201cAttachments\u201d. Additionally, mentions and quotes are supported. 1 2 3 4 5 6 WysiwygFormContainer :: create ( 'message' ) -> label ( 'foo.bar.message' ) -> messageObjectType ( 'com.example.foo.bar' ) -> attachmentData ( 'com.example.foo.bar' ) -> supportMentions () -> supportQuotes ()","title":"Example"},{"location":"php/api/form_builder/form_fields/#wysiwygformfield","text":"WysiwygFormField is used for wysiwyg editor form fields. This class should, in general, not be used directly but only via WysiwygFormContainer . The class implements IAttributeFormField , IMaximumLengthFormField , IMinimumLengthFormField , and IObjectTypeFormNode and requires an object type of the object type definition com.woltlab.wcf.message . The following methods are specific to this form field class: autosaveId($autosaveId) and getAutosaveId() can be used enable automatically saving the current editor contents in the browser using the given id. An empty string signals that autosaving is disabled. lastEditTime($lastEditTime) and getLastEditTime() can be used to set the last time the contents have been edited and saved so that the JavaScript can determine if the contents stored in the browser are older or newer. 0 signals that no last edit time has been set. supportAttachments($supportAttachments) and supportsAttachments() can be used to set and check if the form field supports attachments. It is not sufficient to simply signal attachment support via these methods for attachments to work. These methods are relevant internally to signal the Javascript code that the editor supports attachments. Actual attachment support is provided by WysiwygAttachmentFormField . supportMentions($supportMentions) and supportsMentions() can be used to set and check if the form field supports mentions of other users. WysiwygFormField objects register a custom form field data processor to add the relevant simple ACL data array into the $parameters array directly using the object property as the array key.","title":"WysiwygFormField"},{"location":"php/api/form_builder/form_fields/#twysiwygformnode","text":"All form nodes that need to know the id of the WysiwygFormField field should use TWysiwygFormNode . This trait provides getWysiwygId() and wysiwygId($wysiwygId) to get and set the relevant wysiwyg editor id.","title":"TWysiwygFormNode"},{"location":"php/api/form_builder/form_fields/#application-specific-form-fields","text":"","title":"Application-Specific Form Fields"},{"location":"php/api/form_builder/form_fields/#woltlab-suite-forum","text":"","title":"WoltLab Suite Forum"},{"location":"php/api/form_builder/form_fields/#multipleboardselectionformfield","text":"Only available since version 5.5. MultipleBoardSelectionFormField is used to select multiple forums. The class implements IAttributeFormField , ICssClassFormField , and IImmutableFormField . The field supports additional settings: boardNodeList(BoardNodeList $boardNodeList): self and getBoardNodeList(): BoardNodeList are used to set and get the list of board nodes used to render the board selection. boardNodeList(BoardNodeList $boardNodeList): self will automatically call readNodeTree() on the given board node list. categoriesSelectable(bool $categoriesSelectable = true): self and areCategoriesSelectable(): bool are used to set and check if the categories in the board node list are selectable. By default, categories are selectable. This option is useful if only actual boards, in which threads can be posted, should be selectable but the categories must still be shown so that the overall forum structure is still properly shown. supportExternalLinks(bool $supportExternalLinks): self and supportsExternalLinks(): bool are used to set and check if external links will be shown in the selection list. By default, external links are shown. Like in the example given before, in cases where only actual boards, in which threads can be posted, are relevant, this option allows to exclude external links.","title":"MultipleBoardSelectionFormField"},{"location":"php/api/form_builder/form_fields/#single-use-form-fields","text":"The following form fields are specific for certain forms and hardly reusable in other contexts.","title":"Single-Use Form Fields"},{"location":"php/api/form_builder/form_fields/#bbcodeattributesformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the attributes of a BBCode.","title":"BBCodeAttributesFormField"},{"location":"php/api/form_builder/form_fields/#devtoolsprojectexcludedpackagesformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the excluded packages of a devtools project.","title":"DevtoolsProjectExcludedPackagesFormField"},{"location":"php/api/form_builder/form_fields/#devtoolsprojectinstructionsformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the installation and update instructions of a devtools project.","title":"DevtoolsProjectInstructionsFormField"},{"location":"php/api/form_builder/form_fields/#devtoolsprojectoptionalpackagesformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the optional packages of a devtools project.","title":"DevtoolsProjectOptionalPackagesFormField"},{"location":"php/api/form_builder/form_fields/#devtoolsprojectrequiredpackagesformfield","text":"DevtoolsProjectExcludedPackagesFormField is a form field for setting the required packages of a devtools project.","title":"DevtoolsProjectRequiredPackagesFormField"},{"location":"php/api/form_builder/overview/","text":"Form Builder # WoltLab Suite includes a powerful way of creating forms: Form Builder. Form builder allows you to easily define all the fields and their constraints and interdependencies within PHP with full IDE support. It will then automatically generate the necessary HTML with full interactivity to render all the fields and also validate the fields\u2019 contents upon submission. The migration guide for WoltLab Suite Core 5.2 provides some examples of how to migrate existing forms to form builder that can also help in understanding form builder if the old way of creating forms is familiar. Form Builder Components # Form builder consists of several components that are presented on the following pages: Structure of form builder Form validation and form data Form node dependencies In general, form builder provides default implementation of interfaces by providing either abstract classes or traits. It is expected that the interfaces are always implemented using these abstract classes and traits! This way, if new methods are added to the interfaces, default implementations can be provided by the abstract classes and traits without causing backwards compatibility problems. AbstractFormBuilderForm # To make using form builder easier, AbstractFormBuilderForm extends AbstractForm and provides most of the code needed to set up a form (of course without specific fields, those have to be added by the concrete form class), like reading and validating form values and using a database object action to use the form data to create or update a database object. In addition to the existing methods inherited by AbstractForm , AbstractFormBuilderForm provides the following methods: buildForm() builds the form in the following steps: Call AbtractFormBuilderForm::createForm() to create the IFormDocument object and add the form fields. Call IFormDocument::build() to build the form. Call AbtractFormBuilderForm::finalizeForm() to finalize the form like adding dependencies. Additionally, between steps 1 and 2 and after step 3, the method provides two events, createForm and buildForm to allow plugins to register event listeners to execute additional code at the right point in time. - createForm() creates the FormDocument object and sets the form mode. Classes extending AbstractFormBuilderForm have to override this method (and call parent::createForm() as the first line in the overridden method) to add concrete form containers and form fields to the bare form document. - finalizeForm() is called after the form has been built and the complete form hierarchy has been established. This method should be overridden to add dependencies, for example. - setFormAction() is called at the end of readData() and sets the form document\u2019s action based on the controller class name and whether an object is currently edited. - If an object is edited, at the beginning of readData() , setFormObjectData() is called which calls IFormDocument::loadValuesFromObject() . If values need to be loaded from additional sources, this method should be used for that. AbstractFormBuilderForm also provides the following (public) properties: $form contains the IFormDocument object created in createForm() . $formAction is either create (default) or edit and handles which method of the database object is called by default ( create is called for $formAction = 'create' and update is called for $formAction = 'edit' ) and is used to set the value of the action template variable. $formObject contains the IStorableObject if the form is used to edit an existing object. For forms used to create objects, $formObject is always null . Edit forms have to manually identify the edited object based on the request data and set the value of $formObject . $objectActionName can be used to set an alternative action to be executed by the database object action that deviates from the default action determined by the value of $formAction . $objectActionClass is the name of the database object action class that is used to create or update the database object. DialogFormDocument # Form builder forms can also be used in dialogs. For such forms, DialogFormDocument should be used which provides the additional methods cancelable($cancelable = true) and isCancelable() to set and check if the dialog can be canceled. If a dialog form can be canceled, a cancel button is added. If the dialog form is fetched via an AJAX request, IFormDocument::ajax() has to be called. AJAX forms are registered with WoltLabSuite/Core/Form/Builder/Manager which also supports getting all of the data of a form via the getData(formId) function. The getData() function relies on all form fields creating and registering a WoltLabSuite/Core/Form/Builder/Field/Field object that provides the data of a specific field. To make it as easy as possible to work with AJAX forms in dialogs, WoltLabSuite/Core/Form/Builder/Dialog (abbreviated as FormBuilderDialog from now on) should generally be used instead of WoltLabSuite/Core/Form/Builder/Manager directly. The constructor of FormBuilderDialog expects the following parameters: dialogId : id of the dialog element className : PHP class used to get the form dialog (and save the data if options.submitActionName is set) actionName : name of the action/method of className that returns the dialog; the method is expected to return an array with formId containg the id of the returned form and dialog containing the rendered form dialog options : additional options: actionParameters (default: empty): additional parameters sent during AJAX requests destroyOnClose (default: false ): if true , whenever the dialog is closed, the form is destroyed so that a new form is fetched if the dialog is opened again dialog : additional dialog options used as options during dialog setup onSubmit : callback when the form is submitted (takes precedence over submitActionName ) submitActionName (default: not set): name of the action/method of className called when the form is submitted The three public functions of FormBuilderDialog are: destroy() destroys the dialog, the form, and all of the form fields. getData() returns a Promise that returns the form data. open() opens the dialog. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 require ([ 'WoltLabSuite/Core/Form/Builder/Dialog' ], function ( FormBuilderDialog ) { var dialog = new FormBuilderDialog ( 'testDialog' , 'wcf\\\\data\\\\test\\\\TestAction' , 'getDialog' , { destroyOnClose : true , dialog : { title : 'Test Dialog' }, submitActionName : 'saveDialog' } ); elById ( 'testDialogButton' ). addEventListener ( 'click' , function () { dialog . open (); }); });","title":"Overview"},{"location":"php/api/form_builder/overview/#form-builder","text":"WoltLab Suite includes a powerful way of creating forms: Form Builder. Form builder allows you to easily define all the fields and their constraints and interdependencies within PHP with full IDE support. It will then automatically generate the necessary HTML with full interactivity to render all the fields and also validate the fields\u2019 contents upon submission. The migration guide for WoltLab Suite Core 5.2 provides some examples of how to migrate existing forms to form builder that can also help in understanding form builder if the old way of creating forms is familiar.","title":"Form Builder"},{"location":"php/api/form_builder/overview/#form-builder-components","text":"Form builder consists of several components that are presented on the following pages: Structure of form builder Form validation and form data Form node dependencies In general, form builder provides default implementation of interfaces by providing either abstract classes or traits. It is expected that the interfaces are always implemented using these abstract classes and traits! This way, if new methods are added to the interfaces, default implementations can be provided by the abstract classes and traits without causing backwards compatibility problems.","title":"Form Builder Components"},{"location":"php/api/form_builder/overview/#abstractformbuilderform","text":"To make using form builder easier, AbstractFormBuilderForm extends AbstractForm and provides most of the code needed to set up a form (of course without specific fields, those have to be added by the concrete form class), like reading and validating form values and using a database object action to use the form data to create or update a database object. In addition to the existing methods inherited by AbstractForm , AbstractFormBuilderForm provides the following methods: buildForm() builds the form in the following steps: Call AbtractFormBuilderForm::createForm() to create the IFormDocument object and add the form fields. Call IFormDocument::build() to build the form. Call AbtractFormBuilderForm::finalizeForm() to finalize the form like adding dependencies. Additionally, between steps 1 and 2 and after step 3, the method provides two events, createForm and buildForm to allow plugins to register event listeners to execute additional code at the right point in time. - createForm() creates the FormDocument object and sets the form mode. Classes extending AbstractFormBuilderForm have to override this method (and call parent::createForm() as the first line in the overridden method) to add concrete form containers and form fields to the bare form document. - finalizeForm() is called after the form has been built and the complete form hierarchy has been established. This method should be overridden to add dependencies, for example. - setFormAction() is called at the end of readData() and sets the form document\u2019s action based on the controller class name and whether an object is currently edited. - If an object is edited, at the beginning of readData() , setFormObjectData() is called which calls IFormDocument::loadValuesFromObject() . If values need to be loaded from additional sources, this method should be used for that. AbstractFormBuilderForm also provides the following (public) properties: $form contains the IFormDocument object created in createForm() . $formAction is either create (default) or edit and handles which method of the database object is called by default ( create is called for $formAction = 'create' and update is called for $formAction = 'edit' ) and is used to set the value of the action template variable. $formObject contains the IStorableObject if the form is used to edit an existing object. For forms used to create objects, $formObject is always null . Edit forms have to manually identify the edited object based on the request data and set the value of $formObject . $objectActionName can be used to set an alternative action to be executed by the database object action that deviates from the default action determined by the value of $formAction . $objectActionClass is the name of the database object action class that is used to create or update the database object.","title":"AbstractFormBuilderForm"},{"location":"php/api/form_builder/overview/#dialogformdocument","text":"Form builder forms can also be used in dialogs. For such forms, DialogFormDocument should be used which provides the additional methods cancelable($cancelable = true) and isCancelable() to set and check if the dialog can be canceled. If a dialog form can be canceled, a cancel button is added. If the dialog form is fetched via an AJAX request, IFormDocument::ajax() has to be called. AJAX forms are registered with WoltLabSuite/Core/Form/Builder/Manager which also supports getting all of the data of a form via the getData(formId) function. The getData() function relies on all form fields creating and registering a WoltLabSuite/Core/Form/Builder/Field/Field object that provides the data of a specific field. To make it as easy as possible to work with AJAX forms in dialogs, WoltLabSuite/Core/Form/Builder/Dialog (abbreviated as FormBuilderDialog from now on) should generally be used instead of WoltLabSuite/Core/Form/Builder/Manager directly. The constructor of FormBuilderDialog expects the following parameters: dialogId : id of the dialog element className : PHP class used to get the form dialog (and save the data if options.submitActionName is set) actionName : name of the action/method of className that returns the dialog; the method is expected to return an array with formId containg the id of the returned form and dialog containing the rendered form dialog options : additional options: actionParameters (default: empty): additional parameters sent during AJAX requests destroyOnClose (default: false ): if true , whenever the dialog is closed, the form is destroyed so that a new form is fetched if the dialog is opened again dialog : additional dialog options used as options during dialog setup onSubmit : callback when the form is submitted (takes precedence over submitActionName ) submitActionName (default: not set): name of the action/method of className called when the form is submitted The three public functions of FormBuilderDialog are: destroy() destroys the dialog, the form, and all of the form fields. getData() returns a Promise that returns the form data. open() opens the dialog. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 require ([ 'WoltLabSuite/Core/Form/Builder/Dialog' ], function ( FormBuilderDialog ) { var dialog = new FormBuilderDialog ( 'testDialog' , 'wcf\\\\data\\\\test\\\\TestAction' , 'getDialog' , { destroyOnClose : true , dialog : { title : 'Test Dialog' }, submitActionName : 'saveDialog' } ); elById ( 'testDialogButton' ). addEventListener ( 'click' , function () { dialog . open (); }); });","title":"DialogFormDocument"},{"location":"php/api/form_builder/structure/","text":"Structure of Form Builder # Forms built with form builder consist of three major structural elements listed from top to bottom: form document, form container, form field. The basis for all three elements are form nodes. The form builder API uses fluent interfaces heavily, meaning that unless a method is a getter, it generally returns the objects itself to support method chaining. Form Nodes # IFormNode is the base interface that any node of a form has to implement. IFormChildNode extends IFormNode for such elements of a form that can be a child node to a parent node. IFormParentNode extends IFormNode for such elements of a form that can be a parent to child nodes. IFormElement extends IFormNode for such elements of a form that can have a description and a label. IFormNode # IFormNode is the base interface that any node of a form has to implement and it requires the following methods: addClass($class) , addClasses(array $classes) , removeClass($class) , getClasses() , and hasClass($class) add, remove, get, and check for CSS classes of the HTML element representing the form node. If the form node consists of multiple (nested) HTML elements, the classes are generally added to the top element. static validateClass($class) is used to check if a given CSS class is valid. By default, a form node has no CSS classes. addDependency(IFormFieldDependency $dependency) , removeDependency($dependencyId) , getDependencies() , and hasDependency($dependencyId) add, remove, get, and check for dependencies of this form node on other form fields. checkDependencies() checks if all of the node\u2019s dependencies are met and returns a boolean value reflecting the check\u2019s result. The form builder dependency documentation provides more detailed information about dependencies and how they work. By default, a form node has no dependencies. attribute($name, $value = null) , removeAttribute($name) , getAttribute($name) , getAttributes() , hasAttribute($name) add, remove, get, and check for attributes of the HTML element represting the form node. The attributes are added to the same element that the CSS classes are added to. static validateAttribute($name) is used to check if a given attribute is valid. By default, a form node has no attributes. available($available = true) and isAvailable() can be used to set and check if the node is available. The availability functionality can be used to easily toggle form nodes based, for example, on options without having to create a condition to append the relevant. This way of checking availability makes it easier to set up forms. By default, every form node is available. The following aspects are important when working with availability: Unavailable fields produce no output, their value is not read, they are not validated and they are not checked for save values. Form fields are also able to mark themselves as unavailable, for example, a selection field without any options. Form containers are automatically unavailable if they contain no available children. Availability sets the static availability for form nodes that does not change during the lifetime of a form. In contrast, dependencies represent a dynamic availability for form nodes that depends on the current value of certain form fields. - cleanup() is called after the whole form is not used anymore to reset other APIs if the form fields depends on them and they expect such a reset. This method is not intended to clean up the form field\u2019s value as a new form document object is created to show a clean form. - getDocument() returns the IFormDocument object the node belongs to. (As IFormDocument extends IFormNode , form document objects simply return themselves.) - getHtml() returns the HTML representation of the node. getHtmlVariables() return template variables (in addition to the form node itself) to render the node\u2019s HTML representation. - id($id) and getId() set and get the id of the form node. Every id has to be unique within a form. getPrefixedId() returns the prefixed version of the node\u2019s id (see IFormDocument::getPrefix() and IFormDocument::prefix() ). static validateId($id) is used to check if a given id is valid. - populate() is called by IFormDocument::build() after all form nodes have been added. This method should finilize the initialization of the form node after all parent-child relations of the form document have been established. This method is needed because during the construction of a form node, it neither knows the form document it will belong to nor does it know its parent. - validate() checks, after the form is submitted, if the form node is valid. A form node with children is valid if all of its child nodes are valid. A form field is valid if its value is valid. - static create($id) is the factory method that has to be used to create new form nodes with the given id. TFormNode provides a default implementation of most of these methods. IFormChildNode # IFormChildNode extends IFormNode for such elements of a form that can be a child node to a parent node and it requires the parent(IFormParentNode $parentNode) and getParent() methods used to set and get the node\u2019s parent node. TFormChildNode provides a default implementation of these two methods and also of IFormNode::getDocument() . IFormParentNode # IFormParentNode extends IFormNode for such elements of a form that can be a parent to child nodes. Additionally, the interface also extends \\Countable and \\RecursiveIterator . The interface requires the following methods: appendChild(IFormChildNode $child) , appendChildren(array $children) , insertAfter(IFormChildNode $child, $referenceNodeId) , and insertBefore(IFormChildNode $child, $referenceNodeId) are used to insert new children either at the end or at specific positions. validateChild(IFormChildNode $child) is used to check if a given child node can be added. A child node cannot be added if it would cause an id to be used twice. children() returns the direct children of a form node. getIterator() return a recursive iterator for a form node. getNodeById($nodeId) returns the node with the given id by searching for it in the node\u2019s children and recursively in all of their children. contains($nodeId) can be used to simply check if a node with the given id exists. hasValidationErrors() checks if a form node or any of its children has a validation error (see IFormField::getValidationErrors() ). readValues() recursively calls IFormParentNode::readValues() and IFormField::readValue() on its children. IFormElement # IFormElement extends IFormNode for such elements of a form that can have a description and a label and it requires the following methods: label($languageItem = null, array $variables = []) and getLabel() can be used to set and get the label of the form element. requiresLabel() can be checked if the form element requires a label. A label-less form element that requires a label will prevent the form from being rendered by throwing an exception. description($languageItem = null, array $variables = []) and getDescription() can be used to set and get the description of the form element. IObjectTypeFormNode # IObjectTypeFormField has to be implemented by form nodes that rely on a object type of a specific object type definition in order to function. The implementing class has to implement the methods objectType($objectType) , getObjectType() , and getObjectTypeDefinition() . TObjectTypeFormNode provides a default implementation of these three methods. CustomFormNode # CustomFormNode is a form node whose contents can be set directly via content($content) . This class should generally not be relied on. Instead, TemplateFormNode should be used. TemplateFormNode # TemplateFormNode is a form node whose contents are read from a template. TemplateFormNode has the following additional methods: application($application) and getApplicaton() can be used to set and get the abbreviation of the application the shown template belongs to. If no template has been set explicitly, getApplicaton() returns wcf . templateName($templateName) and getTemplateName() can be used to set and get the name of the template containing the node contents. If no template has been set and the node is rendered, an exception will be thrown. variables(array $variables) and getVariables() can be used to set and get additional variables passed to the template. Form Document # A form document object represents the form as a whole and has to implement the IFormDocument interface. WoltLab Suite provides a default implementation with the FormDocument class. IFormDocument should not be implemented directly but instead FormDocument should be extended to avoid issues if the IFormDocument interface changes in the future. IFormDocument extends IFormParentNode and requires the following additional methods: action($action) and getAction() can be used set and get the action attribute of the <form> HTML element. addButton(IFormButton $button) and getButtons() can be used add and get form buttons that are shown at the bottom of the form. addDefaultButton($addDefaultButton) and hasDefaultButton() can be used to set and check if the form has the default button which is added by default unless specified otherwise. Each implementing class may define its own default button. FormDocument has a button with id submitButton , label wcf.global.button.submit , access key s , and CSS class buttonPrimary as its default button. ajax($ajax) and isAjax() can be used to set and check if the form document is requested via an AJAX request or processes data via an AJAX request. These methods are helpful for form fields that behave differently when providing data via AJAX. build() has to be called once after all nodes have been added to this document to trigger IFormNode::populate() . formMode($formMode) and getFormMode() sets the form mode. Possible form modes are: IFormDocument::FORM_MODE_CREATE has to be used when the form is used to create a new object. IFormDocument::FORM_MODE_UPDATE has to be used when the form is used to edit an existing object. getData() returns the array containing the form data and which is passed as the $parameters argument of the constructor of a database object action object. getDataHandler() returns the data handler for this document that is used to process the field data into a parameters array for the constructor of a database object action object. getEnctype() returns the encoding type of the form. If the form contains a IFileFormField , multipart/form-data is returned, otherwise null is returned. loadValues(array $data, IStorableObject $object) is used when editing an existing object to set the form field values by calling IFormField::loadValue() for all form fields. Additionally, the form mode is set to IFormDocument::FORM_MODE_UPDATE . 5.4+ markRequiredFields(bool $markRequiredFields = true): self and marksRequiredFields(): bool can be used to set and check whether fields that are required are marked (with an asterisk in the label) in the output. method($method) and getMethod() can be used to set and get the method attribute of the <form> HTML element. By default, the method is post . prefix($prefix) and getPrefix() can be used to set and get a global form prefix that is prepended to form elements\u2019 names and ids to avoid conflicts with other forms. By default, the prefix is an empty string. If a prefix of foo is set, getPrefix() returns foo_ (additional trailing underscore). requestData(array $requestData) , getRequestData($index = null) , and hasRequestData($index = null) can be used to set, get and check for specific request data. In most cases, the relevant request data is the $_POST array. In default AJAX requests handled by database object actions, however, the request data generally is in AbstractDatabaseObjectAction::$parameters . By default, $_POST is the request data. The last aspect is relevant for DialogFormDocument objects. DialogFormDocument is a specialized class for forms in dialogs that, in contrast to FormDocument do not require an action to be set. Additionally, DialogFormDocument provides the cancelable($cancelable = true) and isCancelable() methods used to determine if the dialog from can be canceled. By default, dialog forms are cancelable. Form Button # A form button object represents a button shown at the end of the form that, for example, submits the form. Every form button has to implement the IFormButton interface that extends IFormChildNode and IFormElement . IFormButton requires four methods to be implemented: accessKey($accessKey) and getAccessKey() can be used to set and get the access key with which the form button can be activated. By default, form buttons have no access key set. submit($submitButton) and isSubmit() can be used to set and check if the form button is a submit button. A submit button is an input[type=submit] element. Otherwise, the button is a button element. Form Container # A form container object represents a container for other form containers or form field directly. Every form container has to implement the IFormContainer interface which requires the following method: loadValues(array $data, IStorableObject $object) is called by IFormDocument::loadValuesFromObject() to inform the container that object data is loaded. This method is not intended to generally call IFormField::loadValues() on its form field children as these methods are already called by IFormDocument::loadValuesFromObject() . This method is intended for specialized form containers with more complex logic. There are multiple default container implementations: FormContainer is the default implementation of IFormContainer . TabMenuFormContainer represents the container of tab menu, while TabFormContainer represents a tab of a tab menu and TabTabMenuFormContainer represents a tab of a tab menu that itself contains a tab menu. The children of RowFormContainer are shown in a row and should use col-* classes. The children of RowFormFieldContainer are also shown in a row but does not show the labels and descriptions of the individual form fields. Instead of the individual labels and descriptions, the container's label and description is shown and both span all of fields. SuffixFormFieldContainer can be used for one form field with a second selection form field used as a suffix. The methods of the interfaces that FormContainer is implementing are well documented, but here is a short overview of the most important methods when setting up a form or extending a form with an event listener: appendChild(IFormChildNode $child) , appendChildren(array $children) , and insertBefore(IFormChildNode $child, $referenceNodeId) are used to insert new children into the form container. description($languageItem = null, array $variables = []) and label($languageItem = null, array $variables = []) are used to set the description and the label or title of the form container. Form Field # A form field object represents a concrete form field that allows entering data. Every form field has to implement the IFormField interface which extends IFormChildNode and IFormElement . IFormField requires the following additional methods: addValidationError(IFormFieldValidationError $error) and getValidationErrors() can be used to get and set validation errors of the form field (see form validation ). addValidator(IFormFieldValidator $validator) , getValidators() , removeValidator($validatorId) , and hasValidator($validatorId) can be used to get, set, remove, and check for validators for the form field (see form validation ). getFieldHtml() returns the field's HTML output without the surrounding dl structure. objectProperty($objectProperty) and getObjectProperty() can be used to get and set the object property that the field represents. When setting the object property is set to an empty string, the previously set object property is unset. If no object property has been set, the field\u2019s (non-prefixed) id is returned. The object property allows having different fields (requiring different ids) that represent the same object property which is handy when available options of the field\u2019s value depend on another field. Having object property allows to define different fields for each value of the other field and to use form field dependencies to only show the appropriate field. - readValue() reads the form field value from the request data after the form is submitted. - required($required = true) and isRequired() can be used to determine if the form field has to be filled out. By default, form fields do not have to be filled out. - value($value) and getSaveValue() can be used to get and set the value of the form field to be used outside of the context of forms. getValue() , in contrast, returns the internal representation of the form field\u2019s value. In general, the internal representation is only relevant when validating the value in additional validators. loadValue(array $data, IStorableObject $object) extracts the form field value from the given data array (and additional, non-editable data from the object if the field needs them). AbstractFormField provides default implementations of many of the listed methods above and should be extended instead of implementing IFormField directly. An overview of the form fields provided by default can be found here . Form Field Interfaces and Traits # WoltLab Suite Core provides a variety of interfaces and matching traits with default implementations for several common features of form fields: IAttributeFormField # Only available since version 5.4. IAttributeFormField has to be implemented by form fields for which attributes can be added to the actual form element (in addition to adding attributes to the surrounding element via the attribute-related methods of IFormNode ). The implementing class has to implement the methods fieldAttribute(string $name, string $value = null): self and getFieldAttribute(string $name): self / getFieldAttributes(): array , which are used to add and get the attributes, respectively. Additionally, hasFieldAttribute(string $name): bool has to implemented to check if a certain attribute is present, removeFieldAttribute(string $name): self to remove an attribute, and static validateFieldAttribute(string $name) to check if the attribute is valid for this specific class. TAttributeFormField provides a default implementation of these methods and TInputAttributeFormField specializes the trait for input -based form fields. These two traits also ensure that if a specific interface that handles a specific attribute is implemented, like IAutoCompleteFormField handling autocomplete , this attribute cannot be set with this API. Instead, the dedicated API provided by the relevant interface has to be used. IAutoCompleteFormField # Only available since version 5.4. IAutoCompleteFormField has to be implemented by form fields that support the autocomplete attribute . The implementing class has to implement the methods autoComplete(?string $autoComplete): self and getAutoComplete(): ?string , which are used to set and get the autocomplete value, respectively. TAutoCompleteFormField provides a default implementation of these two methods and TTextAutoCompleteFormField specializes the trait for text form fields. When using TAutoCompleteFormField , you have to implement the getValidAutoCompleteTokens(): array method which returns all valid autocomplete tokens. IAutoFocusFormField # IAutoFocusFormField has to be implemented by form fields that can be auto-focused. The implementing class has to implement the methods autoFocus($autoFocus = true) and isAutoFocused() . By default, form fields are not auto-focused. TAutoFocusFormField provides a default implementation of these two methods. ICssClassFormField # Only available since version 5.4. ICssClassFormField has to be implemented by form fields for which CSS classes can be added to the actual form element (in addition to adding CSS classes to the surrounding element via the class-related methods of IFormNode ). The implementing class has to implement the methods addFieldClass(string $class): self / addFieldClasses(array $classes): self and getFieldClasses(): array , which are used to add and get the CSS classes, respectively. Additionally, hasFieldClass(string $class): bool has to implemented to check if a certain CSS class is present and removeFieldClass(string $class): self to remove a CSS class. TCssClassFormField provides a default implementation of these methods. IFileFormField # IFileFormField has to be implemented by every form field that uploads files so that the enctype attribute of the form document is multipart/form-data (see IFormDocument::getEnctype() ). IFilterableSelectionFormField # IFilterableSelectionFormField extends ISelectionFormField by the possibilty for users when selecting the value(s) to filter the list of available options. The implementing class has to implement the methods filterable($filterable = true) and isFilterable() . TFilterableSelectionFormField provides a default implementation of these two methods. II18nFormField # II18nFormField has to be implemented by form fields if the form field value can be entered separately for all available languages. The implementing class has to implement the following methods: i18n($i18n = true) and isI18n() can be used to set whether a specific instance of the class actually supports multilingual input. i18nRequired($i18nRequired = true) and isI18nRequired() can be used to set whether a specific instance of the class requires separate values for all languages. languageItemPattern($pattern) and getLanguageItemPattern() can be used to set the pattern/regular expression for the language item used to save the multilingual values. hasI18nValues() and hasPlainValue() check if the current value is a multilingual or monolingual value. TI18nFormField provides a default implementation of these eight methods and additional default implementations of some of the IFormField methods. If multilingual input is enabled for a specific form field, classes using TI18nFormField register a custom form field data processor to add the array with multilingual input into the $parameters array directly using {$objectProperty}_i18n as the array key. If multilingual input is enabled but only a monolingual value is entered, the custom form field data processor does nothing and the form field\u2019s value is added by the DefaultFormDataProcessor into the data sub-array of the $parameters array. TI18nFormField already provides a default implementation of IFormField::validate() . IImmutableFormField # IImmutableFormField has to be implemented by form fields that support being displayed but whose value cannot be changed. The implementing class has to implement the methods immutable($immutable = true) and isImmutable() that can be used to determine if the value of the form field is mutable or immutable. By default, form field are mutable. IInputModeFormField # Only available since version 5.4. IInputModeFormField has to be implemented by form fields that support the inputmode attribute . The implementing class has to implement the methods inputMode(?string $inputMode): self and getInputMode(): ?string , which are used to set and get the input mode, respectively. TInputModeFormField provides a default implementation of these two methods. IMaximumFormField # IMaximumFormField has to be implemented by form fields if the entered value must have a maximum value. The implementing class has to implement the methods maximum($maximum = null) and getMaximum() . A maximum of null signals that no maximum value has been set. TMaximumFormField provides a default implementation of these two methods. The implementing class has to validate the entered value against the maximum value manually. IMaximumLengthFormField # IMaximumLengthFormField has to be implemented by form fields if the entered value must have a maximum length. The implementing class has to implement the methods maximumLength($maximumLength = null) , getMaximumLength() , and validateMaximumLength($text, Language $language = null) . A maximum length of null signals that no maximum length has been set. TMaximumLengthFormField provides a default implementation of these two methods. The implementing class has to validate the entered value against the maximum value manually by calling validateMaximumLength() . IMinimumFormField # IMinimumFormField has to be implemented by form fields if the entered value must have a minimum value. The implementing class has to implement the methods minimum($minimum = null) and getMinimum() . A minimum of null signals that no minimum value has been set. TMinimumFormField provides a default implementation of these three methods. The implementing class has to validate the entered value against the minimum value manually. IMinimumLengthFormField # IMinimumLengthFormField has to be implemented by form fields if the entered value must have a minimum length. The implementing class has to implement the methods minimumLength($minimumLength = null) , getMinimumLength() , and validateMinimumLength($text, Language $language = null) . A minimum length of null signals that no minimum length has been set. TMinimumLengthFormField provides a default implementation of these three methods. The implementing class has to validate the entered value against the minimum value manually by calling validateMinimumLength() . IMultipleFormField # IMinimumLengthFormField has to be implemented by form fields that support selecting or setting multiple values. The implementing class has to implement the following methods: multiple($multiple = true) and allowsMultiple() can be used to set whether a specific instance of the class actually should support multiple values. By default, multiple values are not supported. minimumMultiples($minimum) and getMinimumMultiples() can be used to set the minimum number of values that have to be selected/entered. By default, there is no required minimum number of values. maximumMultiples($minimum) and getMaximumMultiples() can be used to set the maximum number of values that have to be selected/entered. By default, there is no maximum number of values. IMultipleFormField::NO_MAXIMUM_MULTIPLES is returned if no maximum number of values has been set and it can also be used to unset a previously set maximum number of values. TMultipleFormField provides a default implementation of these six methods and classes using TMultipleFormField register a custom form field data processor to add the HtmlInputProcessor object with the text into the $parameters array directly using {$objectProperty}_htmlInputProcessor as the array key. The implementing class has to validate the values against the minimum and maximum number of values manually. INullableFormField # INullableFormField has to be implemented by form fields that support null as their (empty) value. The implementing class has to implement the methods nullable($nullable = true) and isNullable() . TNullableFormField provides a default implementation of these two methods. null should be returned by IFormField::getSaveValue() is the field is considered empty and the form field has been set as nullable. IPackagesFormField # IPackagesFormField has to be implemented by form fields that, in some way, considers packages whose ids may be passed to the field object. The implementing class has to implement the methods packageIDs(array $packageIDs) and getPackageIDs() . TPackagesFormField provides a default implementation of these two methods. IPatternFormField # Only available since version 5.4. IPatternFormField has to be implemented by form fields that support the pattern attribute . The implementing class has to implement the methods pattern(?string $pattern): self and getPattern(): ?string , which are used to set and get the pattern, respectively. TPatternFormField provides a default implementation of these two methods. IPlaceholderFormField # IPlaceholderFormField has to be implemented by form fields that support a placeholder value for empty fields. The implementing class has to implement the methods placeholder($languageItem = null, array $variables = []) and getPlaceholder() . TPlaceholderFormField provides a default implementation of these two methods. ISelectionFormField # ISelectionFormField has to be implemented by form fields with a predefined set of possible values. The implementing class has to implement the getter and setter methods options($options, $nestedOptions = false, $labelLanguageItems = true) and getOptions() and additionally two methods related to nesting, i.e. whether the selectable options have a hierarchy: supportsNestedOptions() and getNestedOptions() . TSelectionFormField provides a default implementation of these four methods. ISuffixedFormField # ISuffixedFormField has to be implemented by form fields that support supports displaying a suffix behind the actual input field. The implementing class has to implement the methods suffix($languageItem = null, array $variables = []) and getSuffix() . TSuffixedFormField provides a default implementation of these two methods. TDefaultIdFormField # Form fields that have a default id have to use TDefaultIdFormField and have to implement the method getDefaultId() . Displaying Forms # The only thing to do in a template to display the whole form including all of the necessary JavaScript is to put 1 { @ $form -> getHtml () } into the template file at the relevant position.","title":"Structure"},{"location":"php/api/form_builder/structure/#structure-of-form-builder","text":"Forms built with form builder consist of three major structural elements listed from top to bottom: form document, form container, form field. The basis for all three elements are form nodes. The form builder API uses fluent interfaces heavily, meaning that unless a method is a getter, it generally returns the objects itself to support method chaining.","title":"Structure of Form Builder"},{"location":"php/api/form_builder/structure/#form-nodes","text":"IFormNode is the base interface that any node of a form has to implement. IFormChildNode extends IFormNode for such elements of a form that can be a child node to a parent node. IFormParentNode extends IFormNode for such elements of a form that can be a parent to child nodes. IFormElement extends IFormNode for such elements of a form that can have a description and a label.","title":"Form Nodes"},{"location":"php/api/form_builder/structure/#iformnode","text":"IFormNode is the base interface that any node of a form has to implement and it requires the following methods: addClass($class) , addClasses(array $classes) , removeClass($class) , getClasses() , and hasClass($class) add, remove, get, and check for CSS classes of the HTML element representing the form node. If the form node consists of multiple (nested) HTML elements, the classes are generally added to the top element. static validateClass($class) is used to check if a given CSS class is valid. By default, a form node has no CSS classes. addDependency(IFormFieldDependency $dependency) , removeDependency($dependencyId) , getDependencies() , and hasDependency($dependencyId) add, remove, get, and check for dependencies of this form node on other form fields. checkDependencies() checks if all of the node\u2019s dependencies are met and returns a boolean value reflecting the check\u2019s result. The form builder dependency documentation provides more detailed information about dependencies and how they work. By default, a form node has no dependencies. attribute($name, $value = null) , removeAttribute($name) , getAttribute($name) , getAttributes() , hasAttribute($name) add, remove, get, and check for attributes of the HTML element represting the form node. The attributes are added to the same element that the CSS classes are added to. static validateAttribute($name) is used to check if a given attribute is valid. By default, a form node has no attributes. available($available = true) and isAvailable() can be used to set and check if the node is available. The availability functionality can be used to easily toggle form nodes based, for example, on options without having to create a condition to append the relevant. This way of checking availability makes it easier to set up forms. By default, every form node is available. The following aspects are important when working with availability: Unavailable fields produce no output, their value is not read, they are not validated and they are not checked for save values. Form fields are also able to mark themselves as unavailable, for example, a selection field without any options. Form containers are automatically unavailable if they contain no available children. Availability sets the static availability for form nodes that does not change during the lifetime of a form. In contrast, dependencies represent a dynamic availability for form nodes that depends on the current value of certain form fields. - cleanup() is called after the whole form is not used anymore to reset other APIs if the form fields depends on them and they expect such a reset. This method is not intended to clean up the form field\u2019s value as a new form document object is created to show a clean form. - getDocument() returns the IFormDocument object the node belongs to. (As IFormDocument extends IFormNode , form document objects simply return themselves.) - getHtml() returns the HTML representation of the node. getHtmlVariables() return template variables (in addition to the form node itself) to render the node\u2019s HTML representation. - id($id) and getId() set and get the id of the form node. Every id has to be unique within a form. getPrefixedId() returns the prefixed version of the node\u2019s id (see IFormDocument::getPrefix() and IFormDocument::prefix() ). static validateId($id) is used to check if a given id is valid. - populate() is called by IFormDocument::build() after all form nodes have been added. This method should finilize the initialization of the form node after all parent-child relations of the form document have been established. This method is needed because during the construction of a form node, it neither knows the form document it will belong to nor does it know its parent. - validate() checks, after the form is submitted, if the form node is valid. A form node with children is valid if all of its child nodes are valid. A form field is valid if its value is valid. - static create($id) is the factory method that has to be used to create new form nodes with the given id. TFormNode provides a default implementation of most of these methods.","title":"IFormNode"},{"location":"php/api/form_builder/structure/#iformchildnode","text":"IFormChildNode extends IFormNode for such elements of a form that can be a child node to a parent node and it requires the parent(IFormParentNode $parentNode) and getParent() methods used to set and get the node\u2019s parent node. TFormChildNode provides a default implementation of these two methods and also of IFormNode::getDocument() .","title":"IFormChildNode"},{"location":"php/api/form_builder/structure/#iformparentnode","text":"IFormParentNode extends IFormNode for such elements of a form that can be a parent to child nodes. Additionally, the interface also extends \\Countable and \\RecursiveIterator . The interface requires the following methods: appendChild(IFormChildNode $child) , appendChildren(array $children) , insertAfter(IFormChildNode $child, $referenceNodeId) , and insertBefore(IFormChildNode $child, $referenceNodeId) are used to insert new children either at the end or at specific positions. validateChild(IFormChildNode $child) is used to check if a given child node can be added. A child node cannot be added if it would cause an id to be used twice. children() returns the direct children of a form node. getIterator() return a recursive iterator for a form node. getNodeById($nodeId) returns the node with the given id by searching for it in the node\u2019s children and recursively in all of their children. contains($nodeId) can be used to simply check if a node with the given id exists. hasValidationErrors() checks if a form node or any of its children has a validation error (see IFormField::getValidationErrors() ). readValues() recursively calls IFormParentNode::readValues() and IFormField::readValue() on its children.","title":"IFormParentNode"},{"location":"php/api/form_builder/structure/#iformelement","text":"IFormElement extends IFormNode for such elements of a form that can have a description and a label and it requires the following methods: label($languageItem = null, array $variables = []) and getLabel() can be used to set and get the label of the form element. requiresLabel() can be checked if the form element requires a label. A label-less form element that requires a label will prevent the form from being rendered by throwing an exception. description($languageItem = null, array $variables = []) and getDescription() can be used to set and get the description of the form element.","title":"IFormElement"},{"location":"php/api/form_builder/structure/#iobjecttypeformnode","text":"IObjectTypeFormField has to be implemented by form nodes that rely on a object type of a specific object type definition in order to function. The implementing class has to implement the methods objectType($objectType) , getObjectType() , and getObjectTypeDefinition() . TObjectTypeFormNode provides a default implementation of these three methods.","title":"IObjectTypeFormNode"},{"location":"php/api/form_builder/structure/#customformnode","text":"CustomFormNode is a form node whose contents can be set directly via content($content) . This class should generally not be relied on. Instead, TemplateFormNode should be used.","title":"CustomFormNode"},{"location":"php/api/form_builder/structure/#templateformnode","text":"TemplateFormNode is a form node whose contents are read from a template. TemplateFormNode has the following additional methods: application($application) and getApplicaton() can be used to set and get the abbreviation of the application the shown template belongs to. If no template has been set explicitly, getApplicaton() returns wcf . templateName($templateName) and getTemplateName() can be used to set and get the name of the template containing the node contents. If no template has been set and the node is rendered, an exception will be thrown. variables(array $variables) and getVariables() can be used to set and get additional variables passed to the template.","title":"TemplateFormNode"},{"location":"php/api/form_builder/structure/#form-document","text":"A form document object represents the form as a whole and has to implement the IFormDocument interface. WoltLab Suite provides a default implementation with the FormDocument class. IFormDocument should not be implemented directly but instead FormDocument should be extended to avoid issues if the IFormDocument interface changes in the future. IFormDocument extends IFormParentNode and requires the following additional methods: action($action) and getAction() can be used set and get the action attribute of the <form> HTML element. addButton(IFormButton $button) and getButtons() can be used add and get form buttons that are shown at the bottom of the form. addDefaultButton($addDefaultButton) and hasDefaultButton() can be used to set and check if the form has the default button which is added by default unless specified otherwise. Each implementing class may define its own default button. FormDocument has a button with id submitButton , label wcf.global.button.submit , access key s , and CSS class buttonPrimary as its default button. ajax($ajax) and isAjax() can be used to set and check if the form document is requested via an AJAX request or processes data via an AJAX request. These methods are helpful for form fields that behave differently when providing data via AJAX. build() has to be called once after all nodes have been added to this document to trigger IFormNode::populate() . formMode($formMode) and getFormMode() sets the form mode. Possible form modes are: IFormDocument::FORM_MODE_CREATE has to be used when the form is used to create a new object. IFormDocument::FORM_MODE_UPDATE has to be used when the form is used to edit an existing object. getData() returns the array containing the form data and which is passed as the $parameters argument of the constructor of a database object action object. getDataHandler() returns the data handler for this document that is used to process the field data into a parameters array for the constructor of a database object action object. getEnctype() returns the encoding type of the form. If the form contains a IFileFormField , multipart/form-data is returned, otherwise null is returned. loadValues(array $data, IStorableObject $object) is used when editing an existing object to set the form field values by calling IFormField::loadValue() for all form fields. Additionally, the form mode is set to IFormDocument::FORM_MODE_UPDATE . 5.4+ markRequiredFields(bool $markRequiredFields = true): self and marksRequiredFields(): bool can be used to set and check whether fields that are required are marked (with an asterisk in the label) in the output. method($method) and getMethod() can be used to set and get the method attribute of the <form> HTML element. By default, the method is post . prefix($prefix) and getPrefix() can be used to set and get a global form prefix that is prepended to form elements\u2019 names and ids to avoid conflicts with other forms. By default, the prefix is an empty string. If a prefix of foo is set, getPrefix() returns foo_ (additional trailing underscore). requestData(array $requestData) , getRequestData($index = null) , and hasRequestData($index = null) can be used to set, get and check for specific request data. In most cases, the relevant request data is the $_POST array. In default AJAX requests handled by database object actions, however, the request data generally is in AbstractDatabaseObjectAction::$parameters . By default, $_POST is the request data. The last aspect is relevant for DialogFormDocument objects. DialogFormDocument is a specialized class for forms in dialogs that, in contrast to FormDocument do not require an action to be set. Additionally, DialogFormDocument provides the cancelable($cancelable = true) and isCancelable() methods used to determine if the dialog from can be canceled. By default, dialog forms are cancelable.","title":"Form Document"},{"location":"php/api/form_builder/structure/#form-button","text":"A form button object represents a button shown at the end of the form that, for example, submits the form. Every form button has to implement the IFormButton interface that extends IFormChildNode and IFormElement . IFormButton requires four methods to be implemented: accessKey($accessKey) and getAccessKey() can be used to set and get the access key with which the form button can be activated. By default, form buttons have no access key set. submit($submitButton) and isSubmit() can be used to set and check if the form button is a submit button. A submit button is an input[type=submit] element. Otherwise, the button is a button element.","title":"Form Button"},{"location":"php/api/form_builder/structure/#form-container","text":"A form container object represents a container for other form containers or form field directly. Every form container has to implement the IFormContainer interface which requires the following method: loadValues(array $data, IStorableObject $object) is called by IFormDocument::loadValuesFromObject() to inform the container that object data is loaded. This method is not intended to generally call IFormField::loadValues() on its form field children as these methods are already called by IFormDocument::loadValuesFromObject() . This method is intended for specialized form containers with more complex logic. There are multiple default container implementations: FormContainer is the default implementation of IFormContainer . TabMenuFormContainer represents the container of tab menu, while TabFormContainer represents a tab of a tab menu and TabTabMenuFormContainer represents a tab of a tab menu that itself contains a tab menu. The children of RowFormContainer are shown in a row and should use col-* classes. The children of RowFormFieldContainer are also shown in a row but does not show the labels and descriptions of the individual form fields. Instead of the individual labels and descriptions, the container's label and description is shown and both span all of fields. SuffixFormFieldContainer can be used for one form field with a second selection form field used as a suffix. The methods of the interfaces that FormContainer is implementing are well documented, but here is a short overview of the most important methods when setting up a form or extending a form with an event listener: appendChild(IFormChildNode $child) , appendChildren(array $children) , and insertBefore(IFormChildNode $child, $referenceNodeId) are used to insert new children into the form container. description($languageItem = null, array $variables = []) and label($languageItem = null, array $variables = []) are used to set the description and the label or title of the form container.","title":"Form Container"},{"location":"php/api/form_builder/structure/#form-field","text":"A form field object represents a concrete form field that allows entering data. Every form field has to implement the IFormField interface which extends IFormChildNode and IFormElement . IFormField requires the following additional methods: addValidationError(IFormFieldValidationError $error) and getValidationErrors() can be used to get and set validation errors of the form field (see form validation ). addValidator(IFormFieldValidator $validator) , getValidators() , removeValidator($validatorId) , and hasValidator($validatorId) can be used to get, set, remove, and check for validators for the form field (see form validation ). getFieldHtml() returns the field's HTML output without the surrounding dl structure. objectProperty($objectProperty) and getObjectProperty() can be used to get and set the object property that the field represents. When setting the object property is set to an empty string, the previously set object property is unset. If no object property has been set, the field\u2019s (non-prefixed) id is returned. The object property allows having different fields (requiring different ids) that represent the same object property which is handy when available options of the field\u2019s value depend on another field. Having object property allows to define different fields for each value of the other field and to use form field dependencies to only show the appropriate field. - readValue() reads the form field value from the request data after the form is submitted. - required($required = true) and isRequired() can be used to determine if the form field has to be filled out. By default, form fields do not have to be filled out. - value($value) and getSaveValue() can be used to get and set the value of the form field to be used outside of the context of forms. getValue() , in contrast, returns the internal representation of the form field\u2019s value. In general, the internal representation is only relevant when validating the value in additional validators. loadValue(array $data, IStorableObject $object) extracts the form field value from the given data array (and additional, non-editable data from the object if the field needs them). AbstractFormField provides default implementations of many of the listed methods above and should be extended instead of implementing IFormField directly. An overview of the form fields provided by default can be found here .","title":"Form Field"},{"location":"php/api/form_builder/structure/#form-field-interfaces-and-traits","text":"WoltLab Suite Core provides a variety of interfaces and matching traits with default implementations for several common features of form fields:","title":"Form Field Interfaces and Traits"},{"location":"php/api/form_builder/structure/#iattributeformfield","text":"Only available since version 5.4. IAttributeFormField has to be implemented by form fields for which attributes can be added to the actual form element (in addition to adding attributes to the surrounding element via the attribute-related methods of IFormNode ). The implementing class has to implement the methods fieldAttribute(string $name, string $value = null): self and getFieldAttribute(string $name): self / getFieldAttributes(): array , which are used to add and get the attributes, respectively. Additionally, hasFieldAttribute(string $name): bool has to implemented to check if a certain attribute is present, removeFieldAttribute(string $name): self to remove an attribute, and static validateFieldAttribute(string $name) to check if the attribute is valid for this specific class. TAttributeFormField provides a default implementation of these methods and TInputAttributeFormField specializes the trait for input -based form fields. These two traits also ensure that if a specific interface that handles a specific attribute is implemented, like IAutoCompleteFormField handling autocomplete , this attribute cannot be set with this API. Instead, the dedicated API provided by the relevant interface has to be used.","title":"IAttributeFormField"},{"location":"php/api/form_builder/structure/#iautocompleteformfield","text":"Only available since version 5.4. IAutoCompleteFormField has to be implemented by form fields that support the autocomplete attribute . The implementing class has to implement the methods autoComplete(?string $autoComplete): self and getAutoComplete(): ?string , which are used to set and get the autocomplete value, respectively. TAutoCompleteFormField provides a default implementation of these two methods and TTextAutoCompleteFormField specializes the trait for text form fields. When using TAutoCompleteFormField , you have to implement the getValidAutoCompleteTokens(): array method which returns all valid autocomplete tokens.","title":"IAutoCompleteFormField"},{"location":"php/api/form_builder/structure/#iautofocusformfield","text":"IAutoFocusFormField has to be implemented by form fields that can be auto-focused. The implementing class has to implement the methods autoFocus($autoFocus = true) and isAutoFocused() . By default, form fields are not auto-focused. TAutoFocusFormField provides a default implementation of these two methods.","title":"IAutoFocusFormField"},{"location":"php/api/form_builder/structure/#icssclassformfield","text":"Only available since version 5.4. ICssClassFormField has to be implemented by form fields for which CSS classes can be added to the actual form element (in addition to adding CSS classes to the surrounding element via the class-related methods of IFormNode ). The implementing class has to implement the methods addFieldClass(string $class): self / addFieldClasses(array $classes): self and getFieldClasses(): array , which are used to add and get the CSS classes, respectively. Additionally, hasFieldClass(string $class): bool has to implemented to check if a certain CSS class is present and removeFieldClass(string $class): self to remove a CSS class. TCssClassFormField provides a default implementation of these methods.","title":"ICssClassFormField"},{"location":"php/api/form_builder/structure/#ifileformfield","text":"IFileFormField has to be implemented by every form field that uploads files so that the enctype attribute of the form document is multipart/form-data (see IFormDocument::getEnctype() ).","title":"IFileFormField"},{"location":"php/api/form_builder/structure/#ifilterableselectionformfield","text":"IFilterableSelectionFormField extends ISelectionFormField by the possibilty for users when selecting the value(s) to filter the list of available options. The implementing class has to implement the methods filterable($filterable = true) and isFilterable() . TFilterableSelectionFormField provides a default implementation of these two methods.","title":"IFilterableSelectionFormField"},{"location":"php/api/form_builder/structure/#ii18nformfield","text":"II18nFormField has to be implemented by form fields if the form field value can be entered separately for all available languages. The implementing class has to implement the following methods: i18n($i18n = true) and isI18n() can be used to set whether a specific instance of the class actually supports multilingual input. i18nRequired($i18nRequired = true) and isI18nRequired() can be used to set whether a specific instance of the class requires separate values for all languages. languageItemPattern($pattern) and getLanguageItemPattern() can be used to set the pattern/regular expression for the language item used to save the multilingual values. hasI18nValues() and hasPlainValue() check if the current value is a multilingual or monolingual value. TI18nFormField provides a default implementation of these eight methods and additional default implementations of some of the IFormField methods. If multilingual input is enabled for a specific form field, classes using TI18nFormField register a custom form field data processor to add the array with multilingual input into the $parameters array directly using {$objectProperty}_i18n as the array key. If multilingual input is enabled but only a monolingual value is entered, the custom form field data processor does nothing and the form field\u2019s value is added by the DefaultFormDataProcessor into the data sub-array of the $parameters array. TI18nFormField already provides a default implementation of IFormField::validate() .","title":"II18nFormField"},{"location":"php/api/form_builder/structure/#iimmutableformfield","text":"IImmutableFormField has to be implemented by form fields that support being displayed but whose value cannot be changed. The implementing class has to implement the methods immutable($immutable = true) and isImmutable() that can be used to determine if the value of the form field is mutable or immutable. By default, form field are mutable.","title":"IImmutableFormField"},{"location":"php/api/form_builder/structure/#iinputmodeformfield","text":"Only available since version 5.4. IInputModeFormField has to be implemented by form fields that support the inputmode attribute . The implementing class has to implement the methods inputMode(?string $inputMode): self and getInputMode(): ?string , which are used to set and get the input mode, respectively. TInputModeFormField provides a default implementation of these two methods.","title":"IInputModeFormField"},{"location":"php/api/form_builder/structure/#imaximumformfield","text":"IMaximumFormField has to be implemented by form fields if the entered value must have a maximum value. The implementing class has to implement the methods maximum($maximum = null) and getMaximum() . A maximum of null signals that no maximum value has been set. TMaximumFormField provides a default implementation of these two methods. The implementing class has to validate the entered value against the maximum value manually.","title":"IMaximumFormField"},{"location":"php/api/form_builder/structure/#imaximumlengthformfield","text":"IMaximumLengthFormField has to be implemented by form fields if the entered value must have a maximum length. The implementing class has to implement the methods maximumLength($maximumLength = null) , getMaximumLength() , and validateMaximumLength($text, Language $language = null) . A maximum length of null signals that no maximum length has been set. TMaximumLengthFormField provides a default implementation of these two methods. The implementing class has to validate the entered value against the maximum value manually by calling validateMaximumLength() .","title":"IMaximumLengthFormField"},{"location":"php/api/form_builder/structure/#iminimumformfield","text":"IMinimumFormField has to be implemented by form fields if the entered value must have a minimum value. The implementing class has to implement the methods minimum($minimum = null) and getMinimum() . A minimum of null signals that no minimum value has been set. TMinimumFormField provides a default implementation of these three methods. The implementing class has to validate the entered value against the minimum value manually.","title":"IMinimumFormField"},{"location":"php/api/form_builder/structure/#iminimumlengthformfield","text":"IMinimumLengthFormField has to be implemented by form fields if the entered value must have a minimum length. The implementing class has to implement the methods minimumLength($minimumLength = null) , getMinimumLength() , and validateMinimumLength($text, Language $language = null) . A minimum length of null signals that no minimum length has been set. TMinimumLengthFormField provides a default implementation of these three methods. The implementing class has to validate the entered value against the minimum value manually by calling validateMinimumLength() .","title":"IMinimumLengthFormField"},{"location":"php/api/form_builder/structure/#imultipleformfield","text":"IMinimumLengthFormField has to be implemented by form fields that support selecting or setting multiple values. The implementing class has to implement the following methods: multiple($multiple = true) and allowsMultiple() can be used to set whether a specific instance of the class actually should support multiple values. By default, multiple values are not supported. minimumMultiples($minimum) and getMinimumMultiples() can be used to set the minimum number of values that have to be selected/entered. By default, there is no required minimum number of values. maximumMultiples($minimum) and getMaximumMultiples() can be used to set the maximum number of values that have to be selected/entered. By default, there is no maximum number of values. IMultipleFormField::NO_MAXIMUM_MULTIPLES is returned if no maximum number of values has been set and it can also be used to unset a previously set maximum number of values. TMultipleFormField provides a default implementation of these six methods and classes using TMultipleFormField register a custom form field data processor to add the HtmlInputProcessor object with the text into the $parameters array directly using {$objectProperty}_htmlInputProcessor as the array key. The implementing class has to validate the values against the minimum and maximum number of values manually.","title":"IMultipleFormField"},{"location":"php/api/form_builder/structure/#inullableformfield","text":"INullableFormField has to be implemented by form fields that support null as their (empty) value. The implementing class has to implement the methods nullable($nullable = true) and isNullable() . TNullableFormField provides a default implementation of these two methods. null should be returned by IFormField::getSaveValue() is the field is considered empty and the form field has been set as nullable.","title":"INullableFormField"},{"location":"php/api/form_builder/structure/#ipackagesformfield","text":"IPackagesFormField has to be implemented by form fields that, in some way, considers packages whose ids may be passed to the field object. The implementing class has to implement the methods packageIDs(array $packageIDs) and getPackageIDs() . TPackagesFormField provides a default implementation of these two methods.","title":"IPackagesFormField"},{"location":"php/api/form_builder/structure/#ipatternformfield","text":"Only available since version 5.4. IPatternFormField has to be implemented by form fields that support the pattern attribute . The implementing class has to implement the methods pattern(?string $pattern): self and getPattern(): ?string , which are used to set and get the pattern, respectively. TPatternFormField provides a default implementation of these two methods.","title":"IPatternFormField"},{"location":"php/api/form_builder/structure/#iplaceholderformfield","text":"IPlaceholderFormField has to be implemented by form fields that support a placeholder value for empty fields. The implementing class has to implement the methods placeholder($languageItem = null, array $variables = []) and getPlaceholder() . TPlaceholderFormField provides a default implementation of these two methods.","title":"IPlaceholderFormField"},{"location":"php/api/form_builder/structure/#iselectionformfield","text":"ISelectionFormField has to be implemented by form fields with a predefined set of possible values. The implementing class has to implement the getter and setter methods options($options, $nestedOptions = false, $labelLanguageItems = true) and getOptions() and additionally two methods related to nesting, i.e. whether the selectable options have a hierarchy: supportsNestedOptions() and getNestedOptions() . TSelectionFormField provides a default implementation of these four methods.","title":"ISelectionFormField"},{"location":"php/api/form_builder/structure/#isuffixedformfield","text":"ISuffixedFormField has to be implemented by form fields that support supports displaying a suffix behind the actual input field. The implementing class has to implement the methods suffix($languageItem = null, array $variables = []) and getSuffix() . TSuffixedFormField provides a default implementation of these two methods.","title":"ISuffixedFormField"},{"location":"php/api/form_builder/structure/#tdefaultidformfield","text":"Form fields that have a default id have to use TDefaultIdFormField and have to implement the method getDefaultId() .","title":"TDefaultIdFormField"},{"location":"php/api/form_builder/structure/#displaying-forms","text":"The only thing to do in a template to display the whole form including all of the necessary JavaScript is to put 1 { @ $form -> getHtml () } into the template file at the relevant position.","title":"Displaying Forms"},{"location":"php/api/form_builder/validation_data/","text":"Form Validation and Form Data # Form Validation # Every form field class has to implement IFormField::validate() according to their internal logic of what constitutes a valid value. If a certain constraint for the value is not met, a form field validation error object is added to the form field. Form field validation error classes have to implement the interface IFormFieldValidationError . In addition to intrinsic validations like checking the length of the value of a text form field, in many cases, there are additional constraints specific to the form like ensuring that the text is not already used by a different object of the same database object class. Such additional validations can be added to (and removed from) the form field via implementations of the IFormFieldValidator interface. IFormFieldValidationError / FormFieldValidationError # IFormFieldValidationError requires the following methods: __construct($type, $languageItem = null, array $information = []) creates a new validation error object for an error with the given type and message stored in the given language items. The information array is used when generating the error message. getHtml() returns the HTML element representing the error that is shown to the user. getMessage() returns the error message based on the language item and information array given in the constructor. getInformation() and getType() are getters for the first and third parameter of the constructor. FormFieldValidationError is a default implementation of the interface that shows the error in an small.innerError HTML element below the form field. Form field validation errors are added to form fields via the IFormField::addValidationError(IFormFieldValidationError $error) method. IFormFieldValidator / FormFieldValidator # IFormFieldValidator requires the following methods: __construct($id, callable $validator) creates a new validator with the given id that passes the validated form field to the given callable that does the actual validation. static validateId($id) is used to check if the given id is valid. __invoke(IFormField $field) is used when the form field is validated to execute the validator. getId() returns the id of the validator. FormFieldValidator is a default implementation of the interface. Form field validators are added to form fields via the addValidator(IFormFieldValidator $validator) method. Form Data # After a form is successfully validated, the data of the form fields (returned by IFormDocument::getData() ) have to be extracted which is the job of the IFormDataHandler object returned by IFormDocument::getDataHandler() . Form data handlers themselves, however, are only iterating through all IFormDataProcessor instances that have been registered with the data handler. IFormDataHandler / FormDataHandler # IFormDataHandler requires the following methods: addProcessor(IFormDataProcessor $processor) adds a new data processor to the data handler. getFormData(IFormDocument $document) returns the data of the given form by applying all registered data handlers on the form. getObjectData(IFormDocument $document, IStorableObject $object) returns the data of the given object which will be used to populate the form field values of the given form. FormDataHandler is the default implementation of this interface and should also be extended instead of implementing the interface directly. IFormDataProcessor / DefaultFormDataProcessor # IFormDataProcessor requires the following methods: processFormData(IFormDocument $document, array $parameters) is called by IFormDataHandler::getFormData() . The method processes the given parameters array and returns the processed version. processObjectData(IFormDocument $document, array $data, IStorableObject $object) is called by IFormDataHandler::getObjectData() . The method processes the given object data array and returns the processed version. When FormDocument creates its FormDataHandler instance, it automatically registers an DefaultFormDataProcessor object as the first data processor. DefaultFormDataProcessor puts the save value of all form fields that are available and have a save value into $parameters['data'] using the form field\u2019s object property as the array key. IFormDataProcessor should not be implemented directly. Instead, AbstractFormDataProcessor should be extended. All form data is put into the data sub-array so that the whole $parameters array can be passed to a database object action object that requires the actual database object data to be in the data sub-array. When adding a data processor to a form, make sure to add the data processor after the form has been built. Additional Data Processors # CustomFormDataProcessor # As mentioned above, the data in the data sub-array is intended to directly create or update the database object with. As these values are used in the database query directly, these values cannot contain arrays. Several form fields, however, store and return their data in form of arrays. Thus, this data cannot be returned by IFormField::getSaveValue() so that IFormField::hasSaveValue() returns false and the form field\u2019s data is not collected by the standard DefaultFormDataProcessor object. Instead, such form fields register a CustomFormDataProcessor in their IFormField::populate() method that inserts the form field value into the $parameters array directly. This way, the relevant database object action method has access to the data to save it appropriately. The constructor of CustomFormDataProcessor requires an id (that is primarily used in error messages during the validation of the second parameter) and callables for IFormDataProcessor::processFormData() and IFormDataProcessor::processObjectData() which are passed the same parameters as the IFormDataProcessor methods. Only one of the callables has to be given, the other one then defaults to simply returning the relevant array unchanged. VoidFormDataProcessor # Some form fields might only exist to toggle the visibility of other form fields (via dependencies) but the data of form field itself is irrelevant. As DefaultFormDataProcessor collects the data of all form fields, an additional data processor in the form of a VoidFormDataProcessor can be added whose constructor __construct($property, $isDataProperty = true) requires the name of the relevant object property/form id and whether the form field value is stored in the data sub-array or directory in the $parameters array. When the data processor is invoked, it checks whether the relevant entry in the $parameters array exists and voids it by removing it from the array.","title":"Validation and Data"},{"location":"php/api/form_builder/validation_data/#form-validation-and-form-data","text":"","title":"Form Validation and Form Data"},{"location":"php/api/form_builder/validation_data/#form-validation","text":"Every form field class has to implement IFormField::validate() according to their internal logic of what constitutes a valid value. If a certain constraint for the value is not met, a form field validation error object is added to the form field. Form field validation error classes have to implement the interface IFormFieldValidationError . In addition to intrinsic validations like checking the length of the value of a text form field, in many cases, there are additional constraints specific to the form like ensuring that the text is not already used by a different object of the same database object class. Such additional validations can be added to (and removed from) the form field via implementations of the IFormFieldValidator interface.","title":"Form Validation"},{"location":"php/api/form_builder/validation_data/#iformfieldvalidationerror-formfieldvalidationerror","text":"IFormFieldValidationError requires the following methods: __construct($type, $languageItem = null, array $information = []) creates a new validation error object for an error with the given type and message stored in the given language items. The information array is used when generating the error message. getHtml() returns the HTML element representing the error that is shown to the user. getMessage() returns the error message based on the language item and information array given in the constructor. getInformation() and getType() are getters for the first and third parameter of the constructor. FormFieldValidationError is a default implementation of the interface that shows the error in an small.innerError HTML element below the form field. Form field validation errors are added to form fields via the IFormField::addValidationError(IFormFieldValidationError $error) method.","title":"IFormFieldValidationError / FormFieldValidationError"},{"location":"php/api/form_builder/validation_data/#iformfieldvalidator-formfieldvalidator","text":"IFormFieldValidator requires the following methods: __construct($id, callable $validator) creates a new validator with the given id that passes the validated form field to the given callable that does the actual validation. static validateId($id) is used to check if the given id is valid. __invoke(IFormField $field) is used when the form field is validated to execute the validator. getId() returns the id of the validator. FormFieldValidator is a default implementation of the interface. Form field validators are added to form fields via the addValidator(IFormFieldValidator $validator) method.","title":"IFormFieldValidator / FormFieldValidator"},{"location":"php/api/form_builder/validation_data/#form-data","text":"After a form is successfully validated, the data of the form fields (returned by IFormDocument::getData() ) have to be extracted which is the job of the IFormDataHandler object returned by IFormDocument::getDataHandler() . Form data handlers themselves, however, are only iterating through all IFormDataProcessor instances that have been registered with the data handler.","title":"Form Data"},{"location":"php/api/form_builder/validation_data/#iformdatahandler-formdatahandler","text":"IFormDataHandler requires the following methods: addProcessor(IFormDataProcessor $processor) adds a new data processor to the data handler. getFormData(IFormDocument $document) returns the data of the given form by applying all registered data handlers on the form. getObjectData(IFormDocument $document, IStorableObject $object) returns the data of the given object which will be used to populate the form field values of the given form. FormDataHandler is the default implementation of this interface and should also be extended instead of implementing the interface directly.","title":"IFormDataHandler / FormDataHandler"},{"location":"php/api/form_builder/validation_data/#iformdataprocessor-defaultformdataprocessor","text":"IFormDataProcessor requires the following methods: processFormData(IFormDocument $document, array $parameters) is called by IFormDataHandler::getFormData() . The method processes the given parameters array and returns the processed version. processObjectData(IFormDocument $document, array $data, IStorableObject $object) is called by IFormDataHandler::getObjectData() . The method processes the given object data array and returns the processed version. When FormDocument creates its FormDataHandler instance, it automatically registers an DefaultFormDataProcessor object as the first data processor. DefaultFormDataProcessor puts the save value of all form fields that are available and have a save value into $parameters['data'] using the form field\u2019s object property as the array key. IFormDataProcessor should not be implemented directly. Instead, AbstractFormDataProcessor should be extended. All form data is put into the data sub-array so that the whole $parameters array can be passed to a database object action object that requires the actual database object data to be in the data sub-array. When adding a data processor to a form, make sure to add the data processor after the form has been built.","title":"IFormDataProcessor / DefaultFormDataProcessor"},{"location":"php/api/form_builder/validation_data/#additional-data-processors","text":"","title":"Additional Data Processors"},{"location":"php/api/form_builder/validation_data/#customformdataprocessor","text":"As mentioned above, the data in the data sub-array is intended to directly create or update the database object with. As these values are used in the database query directly, these values cannot contain arrays. Several form fields, however, store and return their data in form of arrays. Thus, this data cannot be returned by IFormField::getSaveValue() so that IFormField::hasSaveValue() returns false and the form field\u2019s data is not collected by the standard DefaultFormDataProcessor object. Instead, such form fields register a CustomFormDataProcessor in their IFormField::populate() method that inserts the form field value into the $parameters array directly. This way, the relevant database object action method has access to the data to save it appropriately. The constructor of CustomFormDataProcessor requires an id (that is primarily used in error messages during the validation of the second parameter) and callables for IFormDataProcessor::processFormData() and IFormDataProcessor::processObjectData() which are passed the same parameters as the IFormDataProcessor methods. Only one of the callables has to be given, the other one then defaults to simply returning the relevant array unchanged.","title":"CustomFormDataProcessor"},{"location":"php/api/form_builder/validation_data/#voidformdataprocessor","text":"Some form fields might only exist to toggle the visibility of other form fields (via dependencies) but the data of form field itself is irrelevant. As DefaultFormDataProcessor collects the data of all form fields, an additional data processor in the form of a VoidFormDataProcessor can be added whose constructor __construct($property, $isDataProperty = true) requires the name of the relevant object property/form id and whether the form field value is stored in the data sub-array or directory in the $parameters array. When the data processor is invoked, it checks whether the relevant entry in the $parameters array exists and voids it by removing it from the array.","title":"VoidFormDataProcessor"},{"location":"tutorial/series/overview/","text":"Tutorial Series # In this tutorial series, we will code a package that allows administrators to create a registry of people. In this context, \"people\" does not refer to users registered on the website but anybody living, dead or fictional. We will start this tutorial series by creating a base structure for the package and then continue by adding further features step by step using different APIs. Note that in the context of this example, not every added feature might make perfect sense but the goal of this tutorial is not to create a useful package but to introduce you to WoltLab Suite. Part 1: Base Structure Part 2: Event and Template Listeners Part 3: Person Page and Comments Part 4: Box and Box Conditions Part 5: Person Information Part 6: Activity Points and Activity Events","title":"Overview"},{"location":"tutorial/series/overview/#tutorial-series","text":"In this tutorial series, we will code a package that allows administrators to create a registry of people. In this context, \"people\" does not refer to users registered on the website but anybody living, dead or fictional. We will start this tutorial series by creating a base structure for the package and then continue by adding further features step by step using different APIs. Note that in the context of this example, not every added feature might make perfect sense but the goal of this tutorial is not to create a useful package but to introduce you to WoltLab Suite. Part 1: Base Structure Part 2: Event and Template Listeners Part 3: Person Page and Comments Part 4: Box and Box Conditions Part 5: Person Information Part 6: Activity Points and Activity Events","title":"Tutorial Series"},{"location":"tutorial/series/part_1/","text":"Tutorial Series Part 1: Base Structure # In the first part of this tutorial series, we will lay out what the basic version of package should be able to do and how to implement these functions. Package Functionality # The package should provide the following possibilities/functions: Sortable list of all people in the ACP Ability to add, edit and delete people in the ACP Restrict the ability to add, edit and delete people (in short: manage people) in the ACP Sortable list of all people in the front end Used Components # We will use the following package installation plugins: acpTemplate package installation plugin , acpMenu package installation plugin , database package installation plugin , file package installation plugin , language package installation plugin , menuItem package installation plugin , page package installation plugin , template package installation plugin , userGroupOption package installation plugin , use database objects , create pages and use templates . Package Structure # The package will have the following file structure: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 \u251c\u2500\u2500 acpMenu.xml \u251c\u2500\u2500 acptemplates \u2502 \u251c\u2500\u2500 personAdd.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u251c\u2500\u2500 form \u2502 \u2502 \u2502 \u251c\u2500\u2500 PersonAddForm.class.php \u2502 \u2502 \u2502 \u2514\u2500\u2500 PersonEditForm.class.php \u2502 \u2502 \u2514\u2500\u2500 page \u2502 \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonList.class.php \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 menuItem.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u251c\u2500\u2500 templates \u2502 \u2514\u2500\u2500 personList.tpl \u2514\u2500\u2500 userGroupOption.xml Person Modeling # Database Table # As the first step, we have to model the people we want to manage with this package. As this is only an introductory tutorial, we will keep things simple and only consider the first and last name of a person. Thus, the database table we will store the people in only contains three columns: personID is the unique numeric identifier of each person created, firstName contains the first name of the person, lastName contains the last name of the person. The first file for our package is the install_com.woltlab.wcf.people.php file used to create such a database table during package installation: files/acp/database/install_com.woltlab.wcf.people.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php use wcf\\system\\database\\table\\column\\NotNullVarchar255DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\ObjectIdDatabaseTableColumn ; use wcf\\system\\database\\table\\DatabaseTable ; use wcf\\system\\database\\table\\index\\DatabaseTablePrimaryIndex ; return [ DatabaseTable :: create ( 'wcf1_person' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'personID' ), NotNullVarchar255DatabaseTableColumn :: create ( 'firstName' ), NotNullVarchar255DatabaseTableColumn :: create ( 'lastName' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'personID' ]), ]), ]; Database Object # Person # In our PHP code, each person will be represented by an object of the following class: files/lib/data/person/Person.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObject ; use wcf\\system\\request\\IRouteController ; /** * Represents a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @property-read int $personID unique id of the person * @property-read string $firstName first name of the person * @property-read string $lastName last name of the person */ class Person extends DatabaseObject implements IRouteController { /** * Returns the first and last name of the person if a person object is treated as a string. * * @return string */ public function __toString () { return $this -> getTitle (); } /** * @inheritDoc */ public function getTitle () { return $this -> firstName . ' ' . $this -> lastName ; } } The important thing here is that Person extends DatabaseObject . Additionally, we implement the IRouteController interface, which allows us to use Person objects to create links, and we implement PHP's magic __toString() method for convenience. For every database object, you need to implement three additional classes: an action class, an editor class and a list class. PersonAction # files/lib/data/person/PersonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <? php namespace wcf\\data\\person ; use wcf\\data\\AbstractDatabaseObjectAction ; /** * Executes person-related actions. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method Person create() * @method PersonEditor[] getObjects() * @method PersonEditor getSingleObject() */ class PersonAction extends AbstractDatabaseObjectAction { /** * @inheritDoc */ protected $permissionsDelete = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ protected $requireACP = [ 'delete' ]; } This implementation of AbstractDatabaseObjectAction is very basic and only sets the $permissionsDelete and $requireACP properties. This is done so that later on, when implementing the people list for the ACP, we can delete people simply via AJAX. $permissionsDelete has to be set to the permission needed in order to delete a person. We will later use the userGroupOption package installation plugin to create the admin.content.canManagePeople permission. $requireACP restricts deletion of people to the ACP. PersonEditor # files/lib/data/person/PersonEditor.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObjectEditor ; /** * Provides functions to edit people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method static Person create(array $parameters = []) * @method Person getDecoratedObject() * @mixin Person */ class PersonEditor extends DatabaseObjectEditor { /** * @inheritDoc */ protected static $baseClass = Person :: class ; } This implementation of DatabaseObjectEditor fulfills the minimum requirement for a database object editor: setting the static $baseClass property to the database object class name. PersonList # files/lib/data/person/PersonList.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObjectList ; /** * Represents a list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method Person current() * @method Person[] getObjects() * @method Person|null search($objectID) * @property Person[] $objects */ class PersonList extends DatabaseObjectList { } Due to the default implementation of DatabaseObjectList , our PersonList class just needs to extend it and everything else is either automatically set by the code of DatabaseObjectList or, in the case of properties and methods, provided by that class. ACP # Next, we will take care of the controllers and views for the ACP. In total, we need three each: page to list people, form to add people, and form to edit people. Before we create the controllers and views, let us first create the menu items for the pages in the ACP menu. ACP Menu # We need to create three menu items: a \u201cparent\u201d menu item on the second level of the ACP menu item tree, a third level menu item for the people list page, and a fourth level menu item for the form to add new people. acpMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/acpMenu.xsd\" > <import> <acpmenuitem name= \"wcf.acp.menu.link.person\" > <parent> wcf.acp.menu.link.content </parent> </acpmenuitem> <acpmenuitem name= \"wcf.acp.menu.link.person.list\" > <controller> wcf\\acp\\page\\PersonListPage </controller> <parent> wcf.acp.menu.link.person </parent> <permissions> admin.content.canManagePeople </permissions> </acpmenuitem> <acpmenuitem name= \"wcf.acp.menu.link.person.add\" > <controller> wcf\\acp\\form\\PersonAddForm </controller> <parent> wcf.acp.menu.link.person.list </parent> <permissions> admin.content.canManagePeople </permissions> <icon> fa-plus </icon> </acpmenuitem> </import> </data> We choose wcf.acp.menu.link.content as the parent menu item for the first menu item wcf.acp.menu.link.person because the people we are managing is just one form of content. The fourth level menu item wcf.acp.menu.link.person.add will only be shown as an icon and thus needs an additional element icon which takes a FontAwesome icon class as value. People List # To list the people in the ACP, we need a PersonListPage class and a personList template. PersonListPage # files/lib/acp/page/PersonListPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\acp\\page ; use wcf\\data\\person\\PersonList ; use wcf\\page\\SortablePage ; /** * Shows the list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Page */ class PersonListPage extends SortablePage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.list' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectListClassName = PersonList :: class ; /** * @inheritDoc */ public $validSortFields = [ 'personID' , 'firstName' , 'lastName' ]; } As WoltLab Suite Core already provides a powerful default implementation of a sortable page, our work here is minimal: We need to set the active ACP menu item via the $activeMenuItem . $neededPermissions contains a list of permissions of which the user needs to have at least one in order to see the person list. We use the same permission for both the menu item and the page. The database object list class whose name is provided via $objectListClassName and that handles fetching the people from database is the PersonList class, which we have already created. To validate the sort field passed with the request, we set $validSortFields to the available database table columns. personList.tpl # acptemplates/personList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 { include file = 'header' pageTitle = 'wcf.acp.person.list' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person.list { /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonAdd' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.acp.menu.link.person.add { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { hascontent } <div class=\"paginationTop\"> { content }{ pages print = true assign = pagesLinks controller = \"PersonList\" link = \"pageNo=%d&sortField=$sortField&sortOrder=$sortOrder\" }{ /content } </div> { /hascontent } { if $objects | count } <div class=\"section tabularBox\"> <table class=\"table jsObjectActionContainer\" data-object-action-class-name=\"wcf\\data\\person\\PersonAction\"> <thead> <tr> <th class=\"columnID columnPersonID { if $sortField == 'personID' } active { @ $sortOrder }{ /if } \" colspan=\"2\"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=personID&sortOrder= { if $sortField == 'personID' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.global.objectID { /lang } </a></th> <th class=\"columnTitle columnFirstName { if $sortField == 'firstName' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=firstName&sortOrder= { if $sortField == 'firstName' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.firstName { /lang } </a></th> <th class=\"columnTitle columnLastName { if $sortField == 'lastName' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=lastName&sortOrder= { if $sortField == 'lastName' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.lastName { /lang } </a></th> { event name = 'columnHeads' } </tr> </thead> <tbody class=\"jsReloadPageWhenEmpty\"> { foreach from = $objects item = person } <tr class=\"jsObjectActionObject\" data-object-id=\" { @ $person -> getObjectID () } \"> <td class=\"columnIcon\"> <a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \" title=\" { lang } wcf.global.button.edit { /lang } \" class=\"jsTooltip\"><span class=\"icon icon16 fa-pencil\"></span></a> { objectAction action = \"delete\" objectTitle = $person -> getTitle () } { event name = 'rowButtons' } </td> <td class=\"columnID\"> { # $person -> personID } </td> <td class=\"columnTitle columnFirstName\"><a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \"> { $person -> firstName } </a></td> <td class=\"columnTitle columnLastName\"><a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \"> { $person -> lastName } </a></td> { event name = 'columns' } </tr> { /foreach } </tbody> </table> </div> <footer class=\"contentFooter\"> { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } <nav class=\"contentFooterNavigation\"> <ul> <li><a href=\" { link controller = 'PersonAdd' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.acp.menu.link.person.add { /lang } </span></a></li> { event name = 'contentFooterNavigation' } </ul> </nav> </footer> { else } <p class=\"info\"> { lang } wcf.global.noItems { /lang } </p> { /if } { include file = 'footer' } We will go piece by piece through the template code: We include the header template and set the page title wcf.acp.person.list . You have to include this template for every page! We set the content header and additional provide a button to create a new person in the content header navigation. As not all people are listed on the same page if many people have been created, we need a pagination for which we use the pages template plugin. The {hascontent}{content}{/content}{/hascontent} construct ensures the .paginationTop element is only shown if the pages template plugin has a return value, thus if a pagination is necessary. Now comes the main part of the page, the list of the people, which will only be displayed if any people exist. Otherwise, an info box is displayed using the generic wcf.global.noItems language item. The $objects template variable is automatically assigned by wcf\\page\\MultipleLinkPage and contains the PersonList object used to read the people from database. The table itself consists of a thead and a tbody element and is extendable with more columns using the template events columnHeads and columns . In general, every table should provide these events. The default structure of a table is used here so that the first column of the content rows contains icons to edit and to delete the row (and provides another standard event rowButtons ) and that the second column contains the ID of the person. The table can be sorted by clicking on the head of each column. The used variables $sortField and $sortOrder are automatically assigned to the template by SortablePage . The .contentFooter element is only shown if people exist as it basically repeats the .contentHeaderNavigation and .paginationTop element. The delete button for each person shown in the .columnIcon element relies on the global WoltLabSuite/Core/Ui/Object/Action module which only requires the jsObjectActionContainer CSS class in combination with the data-object-action-class-name attribute for the table element, the jsObjectActionObject CSS class for each person's tr element in combination with the data-object-id attribute, and lastly the delete button itself, which is created with the objectAction template plugin . The .jsReloadPageWhenEmpty CSS class on the tbody element ensures that once all persons on the page have been deleted, the page is reloaded. Lastly, the footer template is included that terminates the page. You also have to include this template for every page! Now, we have finished the page to manage the people so that we can move on to the forms with which we actually create and edit the people. Person Add Form # Like the person list, the form to add new people requires a controller class and a template. PersonAddForm # files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\TextFormField ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractFormBuilderForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * @inheritDoc */ public $formAction = 'create' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectActionClass = PersonAction :: class ; /** * @inheritDoc */ public $objectEditLinkController = PersonEditForm :: class ; /** * @inheritDoc */ protected function createForm () { parent :: createForm (); $this -> form -> appendChild ( FormContainer :: create ( 'data' ) -> label ( 'wcf.global.form.data' ) -> appendChildren ([ TextFormField :: create ( 'firstName' ) -> label ( 'wcf.person.firstName' ) -> required () -> autoFocus () -> maximumLength ( 255 ), TextFormField :: create ( 'lastName' ) -> label ( 'wcf.person.lastName' ) -> required () -> maximumLength ( 255 ), ]) ); } } The properties here consist of three types: the \u201chousekeeping\u201d properties $activeMenuItem and $neededPermissions , which fulfill the same roles as for PersonListPage , and the $objectEditLinkController property , which is used to generate a link to edit the newly created person after submitting the form, and finally $formAction and $objectActionClass required by the PHP form builder API used to generate the form. Because of using form builder, we only have to set up the two form fields for entering the first and last name, respectively: Each field is a simple single-line text field, thus we use TextFormField . The parameter of the create() method expects the id of the field/name of the database object property, which is firstName and lastName , respectively, here. The language item of the label shown in the ouput above the input field is set via the label() method. As both fields have to be filled out, required() is called, and the maximum length is set via maximumLength() . Lastly, to make it easier to fill out the form more quickly, the first field is auto-focused by calling autoFocus() . personAdd.tpl # acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { @ $form -> getHtml () } { include file = 'footer' } We will now only concentrate on the new parts compared to personList.tpl : We use the $action variable to distinguish between the languages items used for adding a person and for creating a person. Because of form builder, we only have to call {@$form->getHtml()} to generate all relevant output for the form. Person Edit Form # As mentioned before, for the form to edit existing people, we only need a new controller as the template has already been implemented in a way that it handles both, adding and editing. PersonEditForm # files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\system\\exception\\IllegalLinkException ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * @inheritDoc */ public $formAction = 'update' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> formObject = new Person ( $_REQUEST [ 'id' ]); if ( ! $this -> formObject -> getObjectID ()) { throw new IllegalLinkException (); } } } } In general, edit forms extend the associated add form so that the code to read and to validate the input data is simply inherited. After setting a different active menu item, we have to change the value of $formAction because this form, in contrast to PersonAddForm , does not create but update existing persons. As we rely on form builder, the only thing necessary in this controller is to read and validate the edit object, i.e. the edited person, which is done in readParameters() . Frontend # For the front end, that means the part with which the visitors of a website interact, we want to implement a simple sortable page that lists the people. This page should also be directly linked in the main menu. page.xml # First, let us register the page with the system because every front end page or form needs to be explicitly registered using the page package installation plugin : page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.people.PersonList\" > <pageType> system </pageType> <controller> wcf\\page\\PersonListPage </controller> <name language= \"de\" > Personen-Liste </name> <name language= \"en\" > Person List </name> <content language= \"de\" > <title> Personen </title> </content> <content language= \"en\" > <title> People </title> </content> </page> </import> </data> For more information about what each of the elements means, please refer to the page package installation plugin page . menuItem.xml # Next, we register the menu item using the menuItem package installation plugin : menuItem.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/menuItem.xsd\" > <import> <item identifier= \"com.woltlab.wcf.people.PersonList\" > <menu> com.woltlab.wcf.MainMenu </menu> <title language= \"de\" > Personen </title> <title language= \"en\" > People </title> <page> com.woltlab.wcf.people.PersonList </page> </item> </import> </data> Here, the import parts are that we register the menu item for the main menu com.woltlab.wcf.MainMenu and link the menu item with the page com.woltlab.wcf.people.PersonList , which we just registered. People List # As in the ACP, we need a controller and a template. You might notice that both the controller\u2019s (unqualified) class name and the template name are the same for the ACP and the front end. This is no problem because the qualified names of the classes differ and the files are stored in different directories and because the templates are installed by different package installation plugins and are also stored in different directories. PersonListPage # files/lib/page/PersonListPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <? php namespace wcf\\page ; use wcf\\data\\person\\PersonList ; /** * Shows the list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Page */ class PersonListPage extends SortablePage { /** * @inheritDoc */ public $defaultSortField = 'lastName' ; /** * @inheritDoc */ public $objectListClassName = PersonList :: class ; /** * @inheritDoc */ public $validSortFields = [ 'personID' , 'firstName' , 'lastName' ]; } This class is almost identical to the ACP version. In the front end, we do not need to set the active menu item manually because the system determines the active menu item automatically based on the requested page. Furthermore, $neededPermissions has not been set because in the front end, users do not need any special permission to access the page. In the front end, we explicitly set the $defaultSortField so that the people listed on the page are sorted by their last name (in ascending order) by default. personList.tpl # templates/personList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 { capture assign = 'contentTitle' }{ lang } wcf.person.list { /lang } <span class=\"badge\"> { # $items } </span> { /capture } { capture assign = 'headContent' } { if $pageNo < $pages } <link rel=\"next\" href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo + 1 }{ /link } \"> { /if } { if $pageNo > 1 } <link rel=\"prev\" href=\" { link controller = 'PersonList' }{ if $pageNo > 2 } pageNo= { @ $pageNo - 1 }{ /if }{ /link } \"> { /if } <link rel=\"canonical\" href=\" { link controller = 'PersonList' }{ if $pageNo > 1 } pageNo= { @ $pageNo }{ /if }{ /link } \"> { /capture } { capture assign = 'sidebarRight' } <section class=\"box\"> <form method=\"post\" action=\" { link controller = 'PersonList' }{ /link } \"> <h2 class=\"boxTitle\"> { lang } wcf.global.sorting { /lang } </h2> <div class=\"boxContent\"> <dl> <dt></dt> <dd> <select id=\"sortField\" name=\"sortField\"> <option value=\"firstName\" { if $sortField == 'firstName' } selected { /if } > { lang } wcf.person.firstName { /lang } </option> <option value=\"lastName\" { if $sortField == 'lastName' } selected { /if } > { lang } wcf.person.lastName { /lang } </option> { event name = 'sortField' } </select> <select name=\"sortOrder\"> <option value=\"ASC\" { if $sortOrder == 'ASC' } selected { /if } > { lang } wcf.global.sortOrder.ascending { /lang } </option> <option value=\"DESC\" { if $sortOrder == 'DESC' } selected { /if } > { lang } wcf.global.sortOrder.descending { /lang } </option> </select> </dd> </dl> <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> </div> </div> </form> </section> { /capture } { include file = 'header' } { hascontent } <div class=\"paginationTop\"> { content } { pages print = true assign = pagesLinks controller = 'PersonList' link = \"pageNo=%d&sortField=$sortField&sortOrder=$sortOrder\" } { /content } </div> { /hascontent } { if $items } <div class=\"section sectionContainerList\"> <ol class=\"containerList personList\"> { foreach from = $objects item = person } <li> <div class=\"box48\"> <span class=\"icon icon48 fa-user\"></span> <div class=\"details personInformation\"> <div class=\"containerHeadline\"> <h3> { $person } </h3> </div> { hascontent } <ul class=\"inlineList commaSeparated\"> { content }{ event name = 'personData' }{ /content } </ul> { /hascontent } { hascontent } <dl class=\"plain inlineDataList small\"> { content }{ event name = 'personStatistics' }{ /content } </dl> { /hascontent } </div> </div> </li> { /foreach } </ol> </div> { else } <p class=\"info\"> { lang } wcf.global.noItems { /lang } </p> { /if } <footer class=\"contentFooter\"> { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } { hascontent } <nav class=\"contentFooterNavigation\"> <ul> { content }{ event name = 'contentFooterNavigation' }{ /content } </ul> </nav> { /hascontent } </footer> { include file = 'footer' } If you compare this template to the one used in the ACP, you will recognize similar elements like the .paginationTop element, the p.info element if no people exist, and the .contentFooter element. Furthermore, we include a template called header before actually showing any of the page contents and terminate the template by including the footer template. Now, let us take a closer look at the differences: We do not explicitly create a .contentHeader element but simply assign the title to the contentTitle variable. The value of the assignment is simply the title of the page and a badge showing the number of listed people. The header template that we include later will handle correctly displaying the content header on its own based on the $contentTitle variable. Next, we create additional element for the HTML document\u2019s <head> element. In this case, we define the canonical link of the page and, because we are showing paginated content, add links to the previous and next page (if they exist). We want the page to be sortable but as we will not be using a table for listing the people like in the ACP, we are not able to place links to sort the people into the table head. Instead, usually a box is created in the sidebar on the right-hand side that contains select elements to determine sort field and sort order. The main part of the page is the listing of the people. We use a structure similar to the one used for displaying registered users. Here, for each person, we simply display a FontAwesome icon representing a person and show the person\u2019s full name relying on Person::__toString() . Additionally, like in the user list, we provide the initially empty ul.inlineList.commaSeparated and dl.plain.inlineDataList.small elements that can be filled by plugins using the templates events. userGroupOption.xml # We have already used the admin.content.canManagePeople permissions several times, now we need to install it using the userGroupOption package installation plugin : userGroupOption.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/userGroupOption.xsd\" > <import> <options> <option name= \"admin.content.canManagePeople\" > <categoryname> admin.content </categoryname> <optiontype> boolean </optiontype> <defaultvalue> 0 </defaultvalue> <admindefaultvalue> 1 </admindefaultvalue> <usersonly> 1 </usersonly> </option> </options> </import> </data> We use the existing admin.content user group option category for the permission as the people are \u201ccontent\u201d (similar the the ACP menu item). As the permission is for administrators only, we set defaultvalue to 0 and admindefaultvalue to 1 . This permission is only relevant for registered users so that it should not be visible when editing the guest user group. This is achieved by setting usersonly to 1 . package.xml # Lastly, we need to create the package.xml file. For more information about this kind of file, please refer to the package.xml page . package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.woltlab.wcf.people\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd\" > <packageinformation> <packagename> WoltLab Suite Core Tutorial: People </packagename> <packagedescription> Adds a simple management system for people as part of a tutorial to create packages. </packagedescription> <version> 5.4.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> WoltLab GmbH </author> <authorurl> http://www.woltlab.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"acpTemplate\" /> <instruction type= \"file\" /> <instruction type= \"database\" > acp/database/install_com.woltlab.wcf.people.php </instruction> <instruction type= \"template\" /> <instruction type= \"language\" /> <instruction type= \"acpMenu\" /> <instruction type= \"page\" /> <instruction type= \"menuItem\" /> <instruction type= \"userGroupOption\" /> </instructions> </package> As this is a package for WoltLab Suite Core 3, we need to require it using <requiredpackage> . We require the latest version (when writing this tutorial) 5.4.0 Alpha 1 . Additionally, we disallow installation of the package in the next major version 6.0 by excluding the 6.0.0 Alpha 1 version. The most important part are to installation instructions. First, we install the ACP templates, files and templates, create the database table and import the language item. Afterwards, the ACP menu items and the permission are added. Now comes the part of the instructions where the order of the instructions is crucial: In menuItem.xml , we refer to the com.woltlab.wcf.people.PersonList page that is delivered by page.xml . As the menu item package installation plugin validates the given page and throws an exception if the page does not exist, we need to install the page before the menu item! This concludes the first part of our tutorial series after which you now have a working simple package with which you can manage people in the ACP and show the visitors of your website a simple list of all created people in the front end. The complete source code of this part can be found on GitHub .","title":"Part 1"},{"location":"tutorial/series/part_1/#tutorial-series-part-1-base-structure","text":"In the first part of this tutorial series, we will lay out what the basic version of package should be able to do and how to implement these functions.","title":"Tutorial Series Part 1: Base Structure"},{"location":"tutorial/series/part_1/#package-functionality","text":"The package should provide the following possibilities/functions: Sortable list of all people in the ACP Ability to add, edit and delete people in the ACP Restrict the ability to add, edit and delete people (in short: manage people) in the ACP Sortable list of all people in the front end","title":"Package Functionality"},{"location":"tutorial/series/part_1/#used-components","text":"We will use the following package installation plugins: acpTemplate package installation plugin , acpMenu package installation plugin , database package installation plugin , file package installation plugin , language package installation plugin , menuItem package installation plugin , page package installation plugin , template package installation plugin , userGroupOption package installation plugin , use database objects , create pages and use templates .","title":"Used Components"},{"location":"tutorial/series/part_1/#package-structure","text":"The package will have the following file structure: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 \u251c\u2500\u2500 acpMenu.xml \u251c\u2500\u2500 acptemplates \u2502 \u251c\u2500\u2500 personAdd.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u251c\u2500\u2500 form \u2502 \u2502 \u2502 \u251c\u2500\u2500 PersonAddForm.class.php \u2502 \u2502 \u2502 \u2514\u2500\u2500 PersonEditForm.class.php \u2502 \u2502 \u2514\u2500\u2500 page \u2502 \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonList.class.php \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 menuItem.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u251c\u2500\u2500 templates \u2502 \u2514\u2500\u2500 personList.tpl \u2514\u2500\u2500 userGroupOption.xml","title":"Package Structure"},{"location":"tutorial/series/part_1/#person-modeling","text":"","title":"Person Modeling"},{"location":"tutorial/series/part_1/#database-table","text":"As the first step, we have to model the people we want to manage with this package. As this is only an introductory tutorial, we will keep things simple and only consider the first and last name of a person. Thus, the database table we will store the people in only contains three columns: personID is the unique numeric identifier of each person created, firstName contains the first name of the person, lastName contains the last name of the person. The first file for our package is the install_com.woltlab.wcf.people.php file used to create such a database table during package installation: files/acp/database/install_com.woltlab.wcf.people.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <? php use wcf\\system\\database\\table\\column\\NotNullVarchar255DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\ObjectIdDatabaseTableColumn ; use wcf\\system\\database\\table\\DatabaseTable ; use wcf\\system\\database\\table\\index\\DatabaseTablePrimaryIndex ; return [ DatabaseTable :: create ( 'wcf1_person' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'personID' ), NotNullVarchar255DatabaseTableColumn :: create ( 'firstName' ), NotNullVarchar255DatabaseTableColumn :: create ( 'lastName' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'personID' ]), ]), ];","title":"Database Table"},{"location":"tutorial/series/part_1/#database-object","text":"","title":"Database Object"},{"location":"tutorial/series/part_1/#person","text":"In our PHP code, each person will be represented by an object of the following class: files/lib/data/person/Person.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObject ; use wcf\\system\\request\\IRouteController ; /** * Represents a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @property-read int $personID unique id of the person * @property-read string $firstName first name of the person * @property-read string $lastName last name of the person */ class Person extends DatabaseObject implements IRouteController { /** * Returns the first and last name of the person if a person object is treated as a string. * * @return string */ public function __toString () { return $this -> getTitle (); } /** * @inheritDoc */ public function getTitle () { return $this -> firstName . ' ' . $this -> lastName ; } } The important thing here is that Person extends DatabaseObject . Additionally, we implement the IRouteController interface, which allows us to use Person objects to create links, and we implement PHP's magic __toString() method for convenience. For every database object, you need to implement three additional classes: an action class, an editor class and a list class.","title":"Person"},{"location":"tutorial/series/part_1/#personaction","text":"files/lib/data/person/PersonAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <? php namespace wcf\\data\\person ; use wcf\\data\\AbstractDatabaseObjectAction ; /** * Executes person-related actions. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method Person create() * @method PersonEditor[] getObjects() * @method PersonEditor getSingleObject() */ class PersonAction extends AbstractDatabaseObjectAction { /** * @inheritDoc */ protected $permissionsDelete = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ protected $requireACP = [ 'delete' ]; } This implementation of AbstractDatabaseObjectAction is very basic and only sets the $permissionsDelete and $requireACP properties. This is done so that later on, when implementing the people list for the ACP, we can delete people simply via AJAX. $permissionsDelete has to be set to the permission needed in order to delete a person. We will later use the userGroupOption package installation plugin to create the admin.content.canManagePeople permission. $requireACP restricts deletion of people to the ACP.","title":"PersonAction"},{"location":"tutorial/series/part_1/#personeditor","text":"files/lib/data/person/PersonEditor.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObjectEditor ; /** * Provides functions to edit people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method static Person create(array $parameters = []) * @method Person getDecoratedObject() * @mixin Person */ class PersonEditor extends DatabaseObjectEditor { /** * @inheritDoc */ protected static $baseClass = Person :: class ; } This implementation of DatabaseObjectEditor fulfills the minimum requirement for a database object editor: setting the static $baseClass property to the database object class name.","title":"PersonEditor"},{"location":"tutorial/series/part_1/#personlist","text":"files/lib/data/person/PersonList.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <? php namespace wcf\\data\\person ; use wcf\\data\\DatabaseObjectList ; /** * Represents a list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person * * @method Person current() * @method Person[] getObjects() * @method Person|null search($objectID) * @property Person[] $objects */ class PersonList extends DatabaseObjectList { } Due to the default implementation of DatabaseObjectList , our PersonList class just needs to extend it and everything else is either automatically set by the code of DatabaseObjectList or, in the case of properties and methods, provided by that class.","title":"PersonList"},{"location":"tutorial/series/part_1/#acp","text":"Next, we will take care of the controllers and views for the ACP. In total, we need three each: page to list people, form to add people, and form to edit people. Before we create the controllers and views, let us first create the menu items for the pages in the ACP menu.","title":"ACP"},{"location":"tutorial/series/part_1/#acp-menu","text":"We need to create three menu items: a \u201cparent\u201d menu item on the second level of the ACP menu item tree, a third level menu item for the people list page, and a fourth level menu item for the form to add new people. acpMenu.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/acpMenu.xsd\" > <import> <acpmenuitem name= \"wcf.acp.menu.link.person\" > <parent> wcf.acp.menu.link.content </parent> </acpmenuitem> <acpmenuitem name= \"wcf.acp.menu.link.person.list\" > <controller> wcf\\acp\\page\\PersonListPage </controller> <parent> wcf.acp.menu.link.person </parent> <permissions> admin.content.canManagePeople </permissions> </acpmenuitem> <acpmenuitem name= \"wcf.acp.menu.link.person.add\" > <controller> wcf\\acp\\form\\PersonAddForm </controller> <parent> wcf.acp.menu.link.person.list </parent> <permissions> admin.content.canManagePeople </permissions> <icon> fa-plus </icon> </acpmenuitem> </import> </data> We choose wcf.acp.menu.link.content as the parent menu item for the first menu item wcf.acp.menu.link.person because the people we are managing is just one form of content. The fourth level menu item wcf.acp.menu.link.person.add will only be shown as an icon and thus needs an additional element icon which takes a FontAwesome icon class as value.","title":"ACP Menu"},{"location":"tutorial/series/part_1/#people-list","text":"To list the people in the ACP, we need a PersonListPage class and a personList template.","title":"People List"},{"location":"tutorial/series/part_1/#personlistpage","text":"files/lib/acp/page/PersonListPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\acp\\page ; use wcf\\data\\person\\PersonList ; use wcf\\page\\SortablePage ; /** * Shows the list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Page */ class PersonListPage extends SortablePage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.list' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectListClassName = PersonList :: class ; /** * @inheritDoc */ public $validSortFields = [ 'personID' , 'firstName' , 'lastName' ]; } As WoltLab Suite Core already provides a powerful default implementation of a sortable page, our work here is minimal: We need to set the active ACP menu item via the $activeMenuItem . $neededPermissions contains a list of permissions of which the user needs to have at least one in order to see the person list. We use the same permission for both the menu item and the page. The database object list class whose name is provided via $objectListClassName and that handles fetching the people from database is the PersonList class, which we have already created. To validate the sort field passed with the request, we set $validSortFields to the available database table columns.","title":"PersonListPage"},{"location":"tutorial/series/part_1/#personlisttpl","text":"acptemplates/personList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 { include file = 'header' pageTitle = 'wcf.acp.person.list' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person.list { /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonAdd' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.acp.menu.link.person.add { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { hascontent } <div class=\"paginationTop\"> { content }{ pages print = true assign = pagesLinks controller = \"PersonList\" link = \"pageNo=%d&sortField=$sortField&sortOrder=$sortOrder\" }{ /content } </div> { /hascontent } { if $objects | count } <div class=\"section tabularBox\"> <table class=\"table jsObjectActionContainer\" data-object-action-class-name=\"wcf\\data\\person\\PersonAction\"> <thead> <tr> <th class=\"columnID columnPersonID { if $sortField == 'personID' } active { @ $sortOrder }{ /if } \" colspan=\"2\"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=personID&sortOrder= { if $sortField == 'personID' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.global.objectID { /lang } </a></th> <th class=\"columnTitle columnFirstName { if $sortField == 'firstName' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=firstName&sortOrder= { if $sortField == 'firstName' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.firstName { /lang } </a></th> <th class=\"columnTitle columnLastName { if $sortField == 'lastName' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=lastName&sortOrder= { if $sortField == 'lastName' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.lastName { /lang } </a></th> { event name = 'columnHeads' } </tr> </thead> <tbody class=\"jsReloadPageWhenEmpty\"> { foreach from = $objects item = person } <tr class=\"jsObjectActionObject\" data-object-id=\" { @ $person -> getObjectID () } \"> <td class=\"columnIcon\"> <a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \" title=\" { lang } wcf.global.button.edit { /lang } \" class=\"jsTooltip\"><span class=\"icon icon16 fa-pencil\"></span></a> { objectAction action = \"delete\" objectTitle = $person -> getTitle () } { event name = 'rowButtons' } </td> <td class=\"columnID\"> { # $person -> personID } </td> <td class=\"columnTitle columnFirstName\"><a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \"> { $person -> firstName } </a></td> <td class=\"columnTitle columnLastName\"><a href=\" { link controller = 'PersonEdit' object = $person }{ /link } \"> { $person -> lastName } </a></td> { event name = 'columns' } </tr> { /foreach } </tbody> </table> </div> <footer class=\"contentFooter\"> { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } <nav class=\"contentFooterNavigation\"> <ul> <li><a href=\" { link controller = 'PersonAdd' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.acp.menu.link.person.add { /lang } </span></a></li> { event name = 'contentFooterNavigation' } </ul> </nav> </footer> { else } <p class=\"info\"> { lang } wcf.global.noItems { /lang } </p> { /if } { include file = 'footer' } We will go piece by piece through the template code: We include the header template and set the page title wcf.acp.person.list . You have to include this template for every page! We set the content header and additional provide a button to create a new person in the content header navigation. As not all people are listed on the same page if many people have been created, we need a pagination for which we use the pages template plugin. The {hascontent}{content}{/content}{/hascontent} construct ensures the .paginationTop element is only shown if the pages template plugin has a return value, thus if a pagination is necessary. Now comes the main part of the page, the list of the people, which will only be displayed if any people exist. Otherwise, an info box is displayed using the generic wcf.global.noItems language item. The $objects template variable is automatically assigned by wcf\\page\\MultipleLinkPage and contains the PersonList object used to read the people from database. The table itself consists of a thead and a tbody element and is extendable with more columns using the template events columnHeads and columns . In general, every table should provide these events. The default structure of a table is used here so that the first column of the content rows contains icons to edit and to delete the row (and provides another standard event rowButtons ) and that the second column contains the ID of the person. The table can be sorted by clicking on the head of each column. The used variables $sortField and $sortOrder are automatically assigned to the template by SortablePage . The .contentFooter element is only shown if people exist as it basically repeats the .contentHeaderNavigation and .paginationTop element. The delete button for each person shown in the .columnIcon element relies on the global WoltLabSuite/Core/Ui/Object/Action module which only requires the jsObjectActionContainer CSS class in combination with the data-object-action-class-name attribute for the table element, the jsObjectActionObject CSS class for each person's tr element in combination with the data-object-id attribute, and lastly the delete button itself, which is created with the objectAction template plugin . The .jsReloadPageWhenEmpty CSS class on the tbody element ensures that once all persons on the page have been deleted, the page is reloaded. Lastly, the footer template is included that terminates the page. You also have to include this template for every page! Now, we have finished the page to manage the people so that we can move on to the forms with which we actually create and edit the people.","title":"personList.tpl"},{"location":"tutorial/series/part_1/#person-add-form","text":"Like the person list, the form to add new people requires a controller class and a template.","title":"Person Add Form"},{"location":"tutorial/series/part_1/#personaddform","text":"files/lib/acp/form/PersonAddForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\PersonAction ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\TextFormField ; /** * Shows the form to create a new person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonAddForm extends AbstractFormBuilderForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person.add' ; /** * @inheritDoc */ public $formAction = 'create' ; /** * @inheritDoc */ public $neededPermissions = [ 'admin.content.canManagePeople' ]; /** * @inheritDoc */ public $objectActionClass = PersonAction :: class ; /** * @inheritDoc */ public $objectEditLinkController = PersonEditForm :: class ; /** * @inheritDoc */ protected function createForm () { parent :: createForm (); $this -> form -> appendChild ( FormContainer :: create ( 'data' ) -> label ( 'wcf.global.form.data' ) -> appendChildren ([ TextFormField :: create ( 'firstName' ) -> label ( 'wcf.person.firstName' ) -> required () -> autoFocus () -> maximumLength ( 255 ), TextFormField :: create ( 'lastName' ) -> label ( 'wcf.person.lastName' ) -> required () -> maximumLength ( 255 ), ]) ); } } The properties here consist of three types: the \u201chousekeeping\u201d properties $activeMenuItem and $neededPermissions , which fulfill the same roles as for PersonListPage , and the $objectEditLinkController property , which is used to generate a link to edit the newly created person after submitting the form, and finally $formAction and $objectActionClass required by the PHP form builder API used to generate the form. Because of using form builder, we only have to set up the two form fields for entering the first and last name, respectively: Each field is a simple single-line text field, thus we use TextFormField . The parameter of the create() method expects the id of the field/name of the database object property, which is firstName and lastName , respectively, here. The language item of the label shown in the ouput above the input field is set via the label() method. As both fields have to be filled out, required() is called, and the maximum length is set via maximumLength() . Lastly, to make it easier to fill out the form more quickly, the first field is auto-focused by calling autoFocus() .","title":"PersonAddForm"},{"location":"tutorial/series/part_1/#personaddtpl","text":"acptemplates/personAdd.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'wcf.acp.person.' | concat : $action } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\"> { lang } wcf.acp.person. { $action }{ /lang } </h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> <li><a href=\" { link controller = 'PersonList' }{ /link } \" class=\"button\"><span class=\"icon icon16 fa-list\"></span> <span> { lang } wcf.acp.menu.link.person.list { /lang } </span></a></li> { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { @ $form -> getHtml () } { include file = 'footer' } We will now only concentrate on the new parts compared to personList.tpl : We use the $action variable to distinguish between the languages items used for adding a person and for creating a person. Because of form builder, we only have to call {@$form->getHtml()} to generate all relevant output for the form.","title":"personAdd.tpl"},{"location":"tutorial/series/part_1/#person-edit-form","text":"As mentioned before, for the form to edit existing people, we only need a new controller as the template has already been implemented in a way that it handles both, adding and editing.","title":"Person Edit Form"},{"location":"tutorial/series/part_1/#personeditform","text":"files/lib/acp/form/PersonEditForm.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <? php namespace wcf\\acp\\form ; use wcf\\data\\person\\Person ; use wcf\\system\\exception\\IllegalLinkException ; /** * Shows the form to edit an existing person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Acp\\Form */ class PersonEditForm extends PersonAddForm { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.person' ; /** * @inheritDoc */ public $formAction = 'update' ; /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> formObject = new Person ( $_REQUEST [ 'id' ]); if ( ! $this -> formObject -> getObjectID ()) { throw new IllegalLinkException (); } } } } In general, edit forms extend the associated add form so that the code to read and to validate the input data is simply inherited. After setting a different active menu item, we have to change the value of $formAction because this form, in contrast to PersonAddForm , does not create but update existing persons. As we rely on form builder, the only thing necessary in this controller is to read and validate the edit object, i.e. the edited person, which is done in readParameters() .","title":"PersonEditForm"},{"location":"tutorial/series/part_1/#frontend","text":"For the front end, that means the part with which the visitors of a website interact, we want to implement a simple sortable page that lists the people. This page should also be directly linked in the main menu.","title":"Frontend"},{"location":"tutorial/series/part_1/#pagexml","text":"First, let us register the page with the system because every front end page or form needs to be explicitly registered using the page package installation plugin : page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.people.PersonList\" > <pageType> system </pageType> <controller> wcf\\page\\PersonListPage </controller> <name language= \"de\" > Personen-Liste </name> <name language= \"en\" > Person List </name> <content language= \"de\" > <title> Personen </title> </content> <content language= \"en\" > <title> People </title> </content> </page> </import> </data> For more information about what each of the elements means, please refer to the page package installation plugin page .","title":"page.xml"},{"location":"tutorial/series/part_1/#menuitemxml","text":"Next, we register the menu item using the menuItem package installation plugin : menuItem.xml 1 2 3 4 5 6 7 8 9 10 11 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/menuItem.xsd\" > <import> <item identifier= \"com.woltlab.wcf.people.PersonList\" > <menu> com.woltlab.wcf.MainMenu </menu> <title language= \"de\" > Personen </title> <title language= \"en\" > People </title> <page> com.woltlab.wcf.people.PersonList </page> </item> </import> </data> Here, the import parts are that we register the menu item for the main menu com.woltlab.wcf.MainMenu and link the menu item with the page com.woltlab.wcf.people.PersonList , which we just registered.","title":"menuItem.xml"},{"location":"tutorial/series/part_1/#people-list_1","text":"As in the ACP, we need a controller and a template. You might notice that both the controller\u2019s (unqualified) class name and the template name are the same for the ACP and the front end. This is no problem because the qualified names of the classes differ and the files are stored in different directories and because the templates are installed by different package installation plugins and are also stored in different directories.","title":"People List"},{"location":"tutorial/series/part_1/#personlistpage_1","text":"files/lib/page/PersonListPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <? php namespace wcf\\page ; use wcf\\data\\person\\PersonList ; /** * Shows the list of people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Page */ class PersonListPage extends SortablePage { /** * @inheritDoc */ public $defaultSortField = 'lastName' ; /** * @inheritDoc */ public $objectListClassName = PersonList :: class ; /** * @inheritDoc */ public $validSortFields = [ 'personID' , 'firstName' , 'lastName' ]; } This class is almost identical to the ACP version. In the front end, we do not need to set the active menu item manually because the system determines the active menu item automatically based on the requested page. Furthermore, $neededPermissions has not been set because in the front end, users do not need any special permission to access the page. In the front end, we explicitly set the $defaultSortField so that the people listed on the page are sorted by their last name (in ascending order) by default.","title":"PersonListPage"},{"location":"tutorial/series/part_1/#personlisttpl_1","text":"templates/personList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 { capture assign = 'contentTitle' }{ lang } wcf.person.list { /lang } <span class=\"badge\"> { # $items } </span> { /capture } { capture assign = 'headContent' } { if $pageNo < $pages } <link rel=\"next\" href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo + 1 }{ /link } \"> { /if } { if $pageNo > 1 } <link rel=\"prev\" href=\" { link controller = 'PersonList' }{ if $pageNo > 2 } pageNo= { @ $pageNo - 1 }{ /if }{ /link } \"> { /if } <link rel=\"canonical\" href=\" { link controller = 'PersonList' }{ if $pageNo > 1 } pageNo= { @ $pageNo }{ /if }{ /link } \"> { /capture } { capture assign = 'sidebarRight' } <section class=\"box\"> <form method=\"post\" action=\" { link controller = 'PersonList' }{ /link } \"> <h2 class=\"boxTitle\"> { lang } wcf.global.sorting { /lang } </h2> <div class=\"boxContent\"> <dl> <dt></dt> <dd> <select id=\"sortField\" name=\"sortField\"> <option value=\"firstName\" { if $sortField == 'firstName' } selected { /if } > { lang } wcf.person.firstName { /lang } </option> <option value=\"lastName\" { if $sortField == 'lastName' } selected { /if } > { lang } wcf.person.lastName { /lang } </option> { event name = 'sortField' } </select> <select name=\"sortOrder\"> <option value=\"ASC\" { if $sortOrder == 'ASC' } selected { /if } > { lang } wcf.global.sortOrder.ascending { /lang } </option> <option value=\"DESC\" { if $sortOrder == 'DESC' } selected { /if } > { lang } wcf.global.sortOrder.descending { /lang } </option> </select> </dd> </dl> <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> </div> </div> </form> </section> { /capture } { include file = 'header' } { hascontent } <div class=\"paginationTop\"> { content } { pages print = true assign = pagesLinks controller = 'PersonList' link = \"pageNo=%d&sortField=$sortField&sortOrder=$sortOrder\" } { /content } </div> { /hascontent } { if $items } <div class=\"section sectionContainerList\"> <ol class=\"containerList personList\"> { foreach from = $objects item = person } <li> <div class=\"box48\"> <span class=\"icon icon48 fa-user\"></span> <div class=\"details personInformation\"> <div class=\"containerHeadline\"> <h3> { $person } </h3> </div> { hascontent } <ul class=\"inlineList commaSeparated\"> { content }{ event name = 'personData' }{ /content } </ul> { /hascontent } { hascontent } <dl class=\"plain inlineDataList small\"> { content }{ event name = 'personStatistics' }{ /content } </dl> { /hascontent } </div> </div> </li> { /foreach } </ol> </div> { else } <p class=\"info\"> { lang } wcf.global.noItems { /lang } </p> { /if } <footer class=\"contentFooter\"> { hascontent } <div class=\"paginationBottom\"> { content }{ @ $pagesLinks }{ /content } </div> { /hascontent } { hascontent } <nav class=\"contentFooterNavigation\"> <ul> { content }{ event name = 'contentFooterNavigation' }{ /content } </ul> </nav> { /hascontent } </footer> { include file = 'footer' } If you compare this template to the one used in the ACP, you will recognize similar elements like the .paginationTop element, the p.info element if no people exist, and the .contentFooter element. Furthermore, we include a template called header before actually showing any of the page contents and terminate the template by including the footer template. Now, let us take a closer look at the differences: We do not explicitly create a .contentHeader element but simply assign the title to the contentTitle variable. The value of the assignment is simply the title of the page and a badge showing the number of listed people. The header template that we include later will handle correctly displaying the content header on its own based on the $contentTitle variable. Next, we create additional element for the HTML document\u2019s <head> element. In this case, we define the canonical link of the page and, because we are showing paginated content, add links to the previous and next page (if they exist). We want the page to be sortable but as we will not be using a table for listing the people like in the ACP, we are not able to place links to sort the people into the table head. Instead, usually a box is created in the sidebar on the right-hand side that contains select elements to determine sort field and sort order. The main part of the page is the listing of the people. We use a structure similar to the one used for displaying registered users. Here, for each person, we simply display a FontAwesome icon representing a person and show the person\u2019s full name relying on Person::__toString() . Additionally, like in the user list, we provide the initially empty ul.inlineList.commaSeparated and dl.plain.inlineDataList.small elements that can be filled by plugins using the templates events.","title":"personList.tpl"},{"location":"tutorial/series/part_1/#usergroupoptionxml","text":"We have already used the admin.content.canManagePeople permissions several times, now we need to install it using the userGroupOption package installation plugin : userGroupOption.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/userGroupOption.xsd\" > <import> <options> <option name= \"admin.content.canManagePeople\" > <categoryname> admin.content </categoryname> <optiontype> boolean </optiontype> <defaultvalue> 0 </defaultvalue> <admindefaultvalue> 1 </admindefaultvalue> <usersonly> 1 </usersonly> </option> </options> </import> </data> We use the existing admin.content user group option category for the permission as the people are \u201ccontent\u201d (similar the the ACP menu item). As the permission is for administrators only, we set defaultvalue to 0 and admindefaultvalue to 1 . This permission is only relevant for registered users so that it should not be visible when editing the guest user group. This is achieved by setting usersonly to 1 .","title":"userGroupOption.xml"},{"location":"tutorial/series/part_1/#packagexml","text":"Lastly, we need to create the package.xml file. For more information about this kind of file, please refer to the package.xml page . package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.woltlab.wcf.people\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd\" > <packageinformation> <packagename> WoltLab Suite Core Tutorial: People </packagename> <packagedescription> Adds a simple management system for people as part of a tutorial to create packages. </packagedescription> <version> 5.4.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> WoltLab GmbH </author> <authorurl> http://www.woltlab.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"acpTemplate\" /> <instruction type= \"file\" /> <instruction type= \"database\" > acp/database/install_com.woltlab.wcf.people.php </instruction> <instruction type= \"template\" /> <instruction type= \"language\" /> <instruction type= \"acpMenu\" /> <instruction type= \"page\" /> <instruction type= \"menuItem\" /> <instruction type= \"userGroupOption\" /> </instructions> </package> As this is a package for WoltLab Suite Core 3, we need to require it using <requiredpackage> . We require the latest version (when writing this tutorial) 5.4.0 Alpha 1 . Additionally, we disallow installation of the package in the next major version 6.0 by excluding the 6.0.0 Alpha 1 version. The most important part are to installation instructions. First, we install the ACP templates, files and templates, create the database table and import the language item. Afterwards, the ACP menu items and the permission are added. Now comes the part of the instructions where the order of the instructions is crucial: In menuItem.xml , we refer to the com.woltlab.wcf.people.PersonList page that is delivered by page.xml . As the menu item package installation plugin validates the given page and throws an exception if the page does not exist, we need to install the page before the menu item! This concludes the first part of our tutorial series after which you now have a working simple package with which you can manage people in the ACP and show the visitors of your website a simple list of all created people in the front end. The complete source code of this part can be found on GitHub .","title":"package.xml"},{"location":"tutorial/series/part_2/","text":"Part 2: Event and Template Listeners # In the first part of this tutorial series, we have created the base structure of our people management package. In further parts, we will use the package of the first part as a basis to directly add new features. In order to explain how event listeners and template works, however, we will not directly adding a new feature to the package by altering it in this part, but we will assume that somebody else created the package and that we want to extend it the \u201ccorrect\u201d way by creating a plugin. The goal of the small plugin that will be created in this part is to add the birthday of the managed people. As in the first part, we will not bother with careful validation of the entered date but just make sure that it is a valid date. Package Functionality # The package should provide the following possibilities/functions: List person\u2019s birthday (if set) in people list in the ACP Sort people list by birthday in the ACP Add or remove birthday when adding or editing person List person\u2019s birthday (if set) in people list in the front end Sort people list by birthday in the front end Used Components # We will use the following package installation plugins: database package installation plugin , eventListener package installation plugin , file package installation plugin , language package installation plugin , template package installation plugin , templateListener package installation plugin . For more information about the event system, please refer to the dedicated page on events . Package Structure # The package will have the following file structure: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 \u251c\u2500\u2500 eventListener.xml \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.birthday.php \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 system \u2502 \u2514\u2500\u2500 event \u2502 \u2514\u2500\u2500 listener \u2502 \u251c\u2500\u2500 BirthdayPersonAddFormListener.class.php \u2502 \u2514\u2500\u2500 BirthdaySortFieldPersonListPageListener.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 templateListener.xml \u2514\u2500\u2500 templates \u251c\u2500\u2500 __personListBirthday.tpl \u2514\u2500\u2500 __personListBirthdaySortField.tpl Extending Person Model # The existing model of a person only contains the person\u2019s first name and their last name (in additional to the id used to identify created people). To add the birthday to the model, we need to create an additional database table column using the database package installation plugin : files/acp/database/install_com.woltlab.wcf.people.birthday.php 1 2 3 4 5 6 7 8 9 10 11 <? php use wcf \\ system \\ database \\ table \\ column \\ DateDatabaseTableColumn ; use wcf \\ system \\ database \\ table \\ PartialDatabaseTable ; return [ PartialDatabaseTable :: create ( 'wcf1_person' ) -> columns ([ DateDatabaseTableColumn :: create ( 'birthday' ), ]), ]; If we have a Person object , this new property can be accessed the same way as the personID property, the firstName property, or the lastName property from the base package: $person->birthday . Setting Birthday in ACP # To set the birthday of a person, we only have to add another form field with an event listener: files/lib/system/event/listener/BirthdayPersonAddFormListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\form\\PersonAddForm ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\DateFormField ; /** * Handles setting the birthday when adding and editing people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class BirthdayPersonAddFormListener extends AbstractEventListener { /** * @see AbstractFormBuilderForm::createForm() */ protected function onCreateForm ( PersonAddForm $form ) : void { /** @var FormContainer $dataContainer */ $dataContainer = $form -> form -> getNodeById ( 'data' ); $dataContainer -> appendChild ( DateFormField :: create ( 'birthday' ) -> label ( 'wcf.person.birthday' ) -> saveValueFormat ( 'Y-m-d' ) -> nullable () ); } } registered via 1 2 3 4 5 6 7 <eventlistener name= \"createForm@wcf\\acp\\form\\PersonAddForm\" > <environment> admin </environment> <eventclassname> wcf\\acp\\form\\PersonAddForm </eventclassname> <eventname> createForm </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdayPersonAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> in eventListener.xml , see below . As BirthdayPersonAddFormListener extends AbstractEventListener and as the name of relevant event is createForm , AbstractEventListener internally automatically calls onCreateForm() with the event object as the parameter. It is important to set <inherit>1</inherit> so that the event listener is also executed for PersonEditForm , which extends PersonAddForm . The language item wcf.person.birthday used in the label is the only new one for this package: language/de.xml 1 2 3 4 5 6 <? xml version = \"1.0\" encoding = \"UTF-8\" ?> < language xmlns = \"http://www.woltlab.com\" xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi : schemaLocation = \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode = \"de\" > < category name = \"wcf.person\" > < item name = \"wcf.person.birthday\" ><! [ CDATA [ Geburtstag ]] ></ item > </ category > </ language > language/en.xml 1 2 3 4 5 6 <? xml version = \"1.0\" encoding = \"UTF-8\" ?> < language xmlns = \"http://www.woltlab.com\" xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi : schemaLocation = \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode = \"en\" > < category name = \"wcf.person\" > < item name = \"wcf.person.birthday\" ><! [ CDATA [ Birthday ]] ></ item > </ category > </ language > Adding Birthday Table Column in ACP # To add a birthday column to the person list page in the ACP, we need three parts: an event listener that makes the birthday database table column a valid sort field, a template listener that adds the birthday column to the table\u2019s head, and a template listener that adds the birthday column to the table\u2019s rows. The first part is a very simple class: files/lib/system/event/listener/BirthdaySortFieldPersonListPageListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? php namespace wcf\\system\\event\\listener ; use wcf\\page\\SortablePage ; /** * Makes people's birthday a valid sort field in the ACP and the front end. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class BirthdaySortFieldPersonListPageListener extends AbstractEventListener { /** * @see SortablePage::validateSortField() */ public function onValidateSortField ( SortablePage $page ) : void { $page -> validSortFields [] = 'birthday' ; } } We use SortablePage as a type hint instead of wcf\\acp\\page\\PersonListPage because we will be using the same event listener class in the front end to also allow sorting that list by birthday. As the relevant template codes are only one line each, we will simply put them directly in the templateListener.xml file that will be shown later on . The code for the table head is similar to the other th elements: 1 <th class=\"columnDate columnBirthday { if $sortField == 'birthday' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=birthday&sortOrder= { if $sortField == 'birthday' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.birthday { /lang } </a></th> For the table body\u2019s column, we need to make sure that the birthday is only show if it is actually set: 1 <td class=\"columnDate columnBirthday\"> { if $person -> birthday }{ @ $person -> birthday | strtotime | date }{ /if } </td> Adding Birthday in Front End # In the front end, we also want to make the list sortable by birthday and show the birthday as part of each person\u2019s \u201cstatistics\u201d. To add the birthday as a valid sort field, we use BirthdaySortFieldPersonListPageListener just as in the ACP. In the front end, we will now use a template ( __personListBirthdaySortField.tpl ) instead of a directly putting the template code in the templateListener.xml file: templates/__personListBirthdaySortField.tpl 1 <option value=\"birthday\" { if $sortField == 'birthday' } selected { /if } > { lang } wcf.person.birthday { /lang } </option> You might have noticed the two underscores at the beginning of the template file. For templates that are included via template listeners, this is the naming convention we use. Putting the template code into a file has the advantage that in the administrator is able to edit the code directly via a custom template group, even though in this case this might not be very probable. To show the birthday, we use the following template code for the personStatistics template event, which again makes sure that the birthday is only shown if it is actually set: templates/__personListBirthday.tpl 1 2 3 4 { if $person -> birthday } <dt> { lang } wcf.person.birthday { /lang } </dt> <dd> { @ $person -> birthday | strtotime | date } </dd> { /if } templateListener.xml # The following code shows the templateListener.xml file used to install all mentioned template listeners: templateListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/tornado/5.4/templateListener.xsd\" > <import> <!-- admin --> <templatelistener name= \"personListBirthdayColumnHead\" > <eventname> columnHeads </eventname> <environment> admin </environment> <templatecode> <![CDATA[<th class=\"columnDate columnBirthday{if $sortField == 'birthday'} active {@$sortOrder}{/if}\"><a href=\"{link controller='PersonList'}pageNo={@$pageNo}&sortField=birthday&sortOrder={if $sortField == 'birthday' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}\">{lang}wcf.person.birthday{/lang}</a></th>]]> </templatecode> <templatename> personList </templatename> </templatelistener> <templatelistener name= \"personListBirthdayColumn\" > <eventname> columns </eventname> <environment> admin </environment> <templatecode> <![CDATA[<td class=\"columnDate columnBirthday\">{if $person->birthday}{@$person->birthday|strtotime|date}{/if}</td>]]> </templatecode> <templatename> personList </templatename> </templatelistener> <!-- /admin --> <!-- user --> <templatelistener name= \"personListBirthday\" > <eventname> personStatistics </eventname> <environment> user </environment> <templatecode> <![CDATA[{include file='__personListBirthday'}]]> </templatecode> <templatename> personList </templatename> </templatelistener> <templatelistener name= \"personListBirthdaySortField\" > <eventname> sortField </eventname> <environment> user </environment> <templatecode> <![CDATA[{include file='__personListBirthdaySortField'}]]> </templatecode> <templatename> personList </templatename> </templatelistener> <!-- /user --> </import> </data> In cases where a template is used, we simply use the include syntax to load the template. eventListener.xml # There are two event listeners that make birthday a valid sort field in the ACP and the front end, respectively, and the third event listener takes care of setting the birthday. eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd\" > <import> <!-- admin --> <eventlistener name= \"validateSortField@wcf\\acp\\page\\PersonListPage\" > <environment> admin </environment> <eventclassname> wcf\\acp\\page\\PersonListPage </eventclassname> <eventname> validateSortField </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdaySortFieldPersonListPageListener </listenerclassname> </eventlistener> <eventlistener name= \"createForm@wcf\\acp\\form\\PersonAddForm\" > <environment> admin </environment> <eventclassname> wcf\\acp\\form\\PersonAddForm </eventclassname> <eventname> createForm </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdayPersonAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> <!-- /admin --> <!-- user --> <eventlistener name= \"validateSortField@wcf\\page\\PersonListPage\" > <environment> user </environment> <eventclassname> wcf\\page\\PersonListPage </eventclassname> <eventname> validateSortField </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdaySortFieldPersonListPageListener </listenerclassname> </eventlistener> <!-- /user --> </import> </data> package.xml # The only relevant difference between the package.xml file of the base page from part 1 and the package.xml file of this package is that this package requires the base package com.woltlab.wcf.people (see <requiredpackages> ): package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.woltlab.wcf.people.birthday\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd\" > <packageinformation> <packagename> WoltLab Suite Core Tutorial: People (Birthday) </packagename> <packagedescription> Adds a birthday field to the people management system as part of a tutorial to create packages. </packagedescription> <version> 5.4.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> WoltLab GmbH </author> <authorurl> http://www.woltlab.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> <requiredpackage minversion= \"5.4.0\" > com.woltlab.wcf.people </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"database\" > acp/database/install_com.woltlab.wcf.people.birthday.php </instruction> <instruction type= \"template\" /> <instruction type= \"language\" /> <instruction type= \"eventListener\" /> <instruction type= \"templateListener\" /> </instructions> </package> This concludes the second part of our tutorial series after which you now have extended the base package using event listeners and template listeners that allow you to enter the birthday of the people. The complete source code of this part can be found on GitHub .","title":"Part 2"},{"location":"tutorial/series/part_2/#part-2-event-and-template-listeners","text":"In the first part of this tutorial series, we have created the base structure of our people management package. In further parts, we will use the package of the first part as a basis to directly add new features. In order to explain how event listeners and template works, however, we will not directly adding a new feature to the package by altering it in this part, but we will assume that somebody else created the package and that we want to extend it the \u201ccorrect\u201d way by creating a plugin. The goal of the small plugin that will be created in this part is to add the birthday of the managed people. As in the first part, we will not bother with careful validation of the entered date but just make sure that it is a valid date.","title":"Part 2: Event and Template Listeners"},{"location":"tutorial/series/part_2/#package-functionality","text":"The package should provide the following possibilities/functions: List person\u2019s birthday (if set) in people list in the ACP Sort people list by birthday in the ACP Add or remove birthday when adding or editing person List person\u2019s birthday (if set) in people list in the front end Sort people list by birthday in the front end","title":"Package Functionality"},{"location":"tutorial/series/part_2/#used-components","text":"We will use the following package installation plugins: database package installation plugin , eventListener package installation plugin , file package installation plugin , language package installation plugin , template package installation plugin , templateListener package installation plugin . For more information about the event system, please refer to the dedicated page on events .","title":"Used Components"},{"location":"tutorial/series/part_2/#package-structure","text":"The package will have the following file structure: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 \u251c\u2500\u2500 eventListener.xml \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.birthday.php \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 system \u2502 \u2514\u2500\u2500 event \u2502 \u2514\u2500\u2500 listener \u2502 \u251c\u2500\u2500 BirthdayPersonAddFormListener.class.php \u2502 \u2514\u2500\u2500 BirthdaySortFieldPersonListPageListener.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 templateListener.xml \u2514\u2500\u2500 templates \u251c\u2500\u2500 __personListBirthday.tpl \u2514\u2500\u2500 __personListBirthdaySortField.tpl","title":"Package Structure"},{"location":"tutorial/series/part_2/#extending-person-model","text":"The existing model of a person only contains the person\u2019s first name and their last name (in additional to the id used to identify created people). To add the birthday to the model, we need to create an additional database table column using the database package installation plugin : files/acp/database/install_com.woltlab.wcf.people.birthday.php 1 2 3 4 5 6 7 8 9 10 11 <? php use wcf \\ system \\ database \\ table \\ column \\ DateDatabaseTableColumn ; use wcf \\ system \\ database \\ table \\ PartialDatabaseTable ; return [ PartialDatabaseTable :: create ( 'wcf1_person' ) -> columns ([ DateDatabaseTableColumn :: create ( 'birthday' ), ]), ]; If we have a Person object , this new property can be accessed the same way as the personID property, the firstName property, or the lastName property from the base package: $person->birthday .","title":"Extending Person Model"},{"location":"tutorial/series/part_2/#setting-birthday-in-acp","text":"To set the birthday of a person, we only have to add another form field with an event listener: files/lib/system/event/listener/BirthdayPersonAddFormListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\form\\PersonAddForm ; use wcf\\form\\AbstractFormBuilderForm ; use wcf\\system\\form\\builder\\container\\FormContainer ; use wcf\\system\\form\\builder\\field\\DateFormField ; /** * Handles setting the birthday when adding and editing people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class BirthdayPersonAddFormListener extends AbstractEventListener { /** * @see AbstractFormBuilderForm::createForm() */ protected function onCreateForm ( PersonAddForm $form ) : void { /** @var FormContainer $dataContainer */ $dataContainer = $form -> form -> getNodeById ( 'data' ); $dataContainer -> appendChild ( DateFormField :: create ( 'birthday' ) -> label ( 'wcf.person.birthday' ) -> saveValueFormat ( 'Y-m-d' ) -> nullable () ); } } registered via 1 2 3 4 5 6 7 <eventlistener name= \"createForm@wcf\\acp\\form\\PersonAddForm\" > <environment> admin </environment> <eventclassname> wcf\\acp\\form\\PersonAddForm </eventclassname> <eventname> createForm </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdayPersonAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> in eventListener.xml , see below . As BirthdayPersonAddFormListener extends AbstractEventListener and as the name of relevant event is createForm , AbstractEventListener internally automatically calls onCreateForm() with the event object as the parameter. It is important to set <inherit>1</inherit> so that the event listener is also executed for PersonEditForm , which extends PersonAddForm . The language item wcf.person.birthday used in the label is the only new one for this package: language/de.xml 1 2 3 4 5 6 <? xml version = \"1.0\" encoding = \"UTF-8\" ?> < language xmlns = \"http://www.woltlab.com\" xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi : schemaLocation = \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode = \"de\" > < category name = \"wcf.person\" > < item name = \"wcf.person.birthday\" ><! [ CDATA [ Geburtstag ]] ></ item > </ category > </ language > language/en.xml 1 2 3 4 5 6 <? xml version = \"1.0\" encoding = \"UTF-8\" ?> < language xmlns = \"http://www.woltlab.com\" xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi : schemaLocation = \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd\" languagecode = \"en\" > < category name = \"wcf.person\" > < item name = \"wcf.person.birthday\" ><! [ CDATA [ Birthday ]] ></ item > </ category > </ language >","title":"Setting Birthday in ACP"},{"location":"tutorial/series/part_2/#adding-birthday-table-column-in-acp","text":"To add a birthday column to the person list page in the ACP, we need three parts: an event listener that makes the birthday database table column a valid sort field, a template listener that adds the birthday column to the table\u2019s head, and a template listener that adds the birthday column to the table\u2019s rows. The first part is a very simple class: files/lib/system/event/listener/BirthdaySortFieldPersonListPageListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? php namespace wcf\\system\\event\\listener ; use wcf\\page\\SortablePage ; /** * Makes people's birthday a valid sort field in the ACP and the front end. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class BirthdaySortFieldPersonListPageListener extends AbstractEventListener { /** * @see SortablePage::validateSortField() */ public function onValidateSortField ( SortablePage $page ) : void { $page -> validSortFields [] = 'birthday' ; } } We use SortablePage as a type hint instead of wcf\\acp\\page\\PersonListPage because we will be using the same event listener class in the front end to also allow sorting that list by birthday. As the relevant template codes are only one line each, we will simply put them directly in the templateListener.xml file that will be shown later on . The code for the table head is similar to the other th elements: 1 <th class=\"columnDate columnBirthday { if $sortField == 'birthday' } active { @ $sortOrder }{ /if } \"><a href=\" { link controller = 'PersonList' } pageNo= { @ $pageNo } &sortField=birthday&sortOrder= { if $sortField == 'birthday' && $sortOrder == 'ASC' } DESC { else } ASC { /if }{ /link } \"> { lang } wcf.person.birthday { /lang } </a></th> For the table body\u2019s column, we need to make sure that the birthday is only show if it is actually set: 1 <td class=\"columnDate columnBirthday\"> { if $person -> birthday }{ @ $person -> birthday | strtotime | date }{ /if } </td>","title":"Adding Birthday Table Column in ACP"},{"location":"tutorial/series/part_2/#adding-birthday-in-front-end","text":"In the front end, we also want to make the list sortable by birthday and show the birthday as part of each person\u2019s \u201cstatistics\u201d. To add the birthday as a valid sort field, we use BirthdaySortFieldPersonListPageListener just as in the ACP. In the front end, we will now use a template ( __personListBirthdaySortField.tpl ) instead of a directly putting the template code in the templateListener.xml file: templates/__personListBirthdaySortField.tpl 1 <option value=\"birthday\" { if $sortField == 'birthday' } selected { /if } > { lang } wcf.person.birthday { /lang } </option> You might have noticed the two underscores at the beginning of the template file. For templates that are included via template listeners, this is the naming convention we use. Putting the template code into a file has the advantage that in the administrator is able to edit the code directly via a custom template group, even though in this case this might not be very probable. To show the birthday, we use the following template code for the personStatistics template event, which again makes sure that the birthday is only shown if it is actually set: templates/__personListBirthday.tpl 1 2 3 4 { if $person -> birthday } <dt> { lang } wcf.person.birthday { /lang } </dt> <dd> { @ $person -> birthday | strtotime | date } </dd> { /if }","title":"Adding Birthday in Front End"},{"location":"tutorial/series/part_2/#templatelistenerxml","text":"The following code shows the templateListener.xml file used to install all mentioned template listeners: templateListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/tornado/5.4/templateListener.xsd\" > <import> <!-- admin --> <templatelistener name= \"personListBirthdayColumnHead\" > <eventname> columnHeads </eventname> <environment> admin </environment> <templatecode> <![CDATA[<th class=\"columnDate columnBirthday{if $sortField == 'birthday'} active {@$sortOrder}{/if}\"><a href=\"{link controller='PersonList'}pageNo={@$pageNo}&sortField=birthday&sortOrder={if $sortField == 'birthday' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}\">{lang}wcf.person.birthday{/lang}</a></th>]]> </templatecode> <templatename> personList </templatename> </templatelistener> <templatelistener name= \"personListBirthdayColumn\" > <eventname> columns </eventname> <environment> admin </environment> <templatecode> <![CDATA[<td class=\"columnDate columnBirthday\">{if $person->birthday}{@$person->birthday|strtotime|date}{/if}</td>]]> </templatecode> <templatename> personList </templatename> </templatelistener> <!-- /admin --> <!-- user --> <templatelistener name= \"personListBirthday\" > <eventname> personStatistics </eventname> <environment> user </environment> <templatecode> <![CDATA[{include file='__personListBirthday'}]]> </templatecode> <templatename> personList </templatename> </templatelistener> <templatelistener name= \"personListBirthdaySortField\" > <eventname> sortField </eventname> <environment> user </environment> <templatecode> <![CDATA[{include file='__personListBirthdaySortField'}]]> </templatecode> <templatename> personList </templatename> </templatelistener> <!-- /user --> </import> </data> In cases where a template is used, we simply use the include syntax to load the template.","title":"templateListener.xml"},{"location":"tutorial/series/part_2/#eventlistenerxml","text":"There are two event listeners that make birthday a valid sort field in the ACP and the front end, respectively, and the third event listener takes care of setting the birthday. eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd\" > <import> <!-- admin --> <eventlistener name= \"validateSortField@wcf\\acp\\page\\PersonListPage\" > <environment> admin </environment> <eventclassname> wcf\\acp\\page\\PersonListPage </eventclassname> <eventname> validateSortField </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdaySortFieldPersonListPageListener </listenerclassname> </eventlistener> <eventlistener name= \"createForm@wcf\\acp\\form\\PersonAddForm\" > <environment> admin </environment> <eventclassname> wcf\\acp\\form\\PersonAddForm </eventclassname> <eventname> createForm </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdayPersonAddFormListener </listenerclassname> <inherit> 1 </inherit> </eventlistener> <!-- /admin --> <!-- user --> <eventlistener name= \"validateSortField@wcf\\page\\PersonListPage\" > <environment> user </environment> <eventclassname> wcf\\page\\PersonListPage </eventclassname> <eventname> validateSortField </eventname> <listenerclassname> wcf\\system\\event\\listener\\BirthdaySortFieldPersonListPageListener </listenerclassname> </eventlistener> <!-- /user --> </import> </data>","title":"eventListener.xml"},{"location":"tutorial/series/part_2/#packagexml","text":"The only relevant difference between the package.xml file of the base page from part 1 and the package.xml file of this package is that this package requires the base package com.woltlab.wcf.people (see <requiredpackages> ): package.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <package name= \"com.woltlab.wcf.people.birthday\" xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd\" > <packageinformation> <packagename> WoltLab Suite Core Tutorial: People (Birthday) </packagename> <packagedescription> Adds a birthday field to the people management system as part of a tutorial to create packages. </packagedescription> <version> 5.4.0 </version> <date> 2022-01-17 </date> </packageinformation> <authorinformation> <author> WoltLab GmbH </author> <authorurl> http://www.woltlab.com </authorurl> </authorinformation> <requiredpackages> <requiredpackage minversion= \"5.4.10\" > com.woltlab.wcf </requiredpackage> <requiredpackage minversion= \"5.4.0\" > com.woltlab.wcf.people </requiredpackage> </requiredpackages> <excludedpackages> <excludedpackage version= \"6.0.0 Alpha 1\" > com.woltlab.wcf </excludedpackage> </excludedpackages> <instructions type= \"install\" > <instruction type= \"file\" /> <instruction type= \"database\" > acp/database/install_com.woltlab.wcf.people.birthday.php </instruction> <instruction type= \"template\" /> <instruction type= \"language\" /> <instruction type= \"eventListener\" /> <instruction type= \"templateListener\" /> </instructions> </package> This concludes the second part of our tutorial series after which you now have extended the base package using event listeners and template listeners that allow you to enter the birthday of the people. The complete source code of this part can be found on GitHub .","title":"package.xml"},{"location":"tutorial/series/part_3/","text":"Part 3: Person Page and Comments # In this part of our tutorial series, we will add a new front end page to our package that is dedicated to each person and shows their personal details. To make good use of this new page and introduce a new API of WoltLab Suite, we will add the opportunity for users to comment on the person using WoltLab Suite\u2019s reusable comment functionality. Package Functionality # In addition to the existing functions from part 1 , the package will provide the following possibilities/functions after this part of the tutorial: Details page for each person linked in the front end person list Comment on people on their respective page (can be disabled per person) User online location for person details page with name and link to person details page Create menu items linking to specific person details pages Used Components # In addition to the components used in part 1 , we will use the objectType package installation plugin , use the comment API , create a runtime cache , and create a page handler. Package Structure # The complete package will have the following file structure (including the files from part 1 ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 \u251c\u2500\u2500 acpMenu.xml \u251c\u2500\u2500 acptemplates \u2502 \u251c\u2500\u2500 personAdd.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u251c\u2500\u2500 form \u2502 \u2502 \u2502 \u251c\u2500\u2500 PersonAddForm.class.php \u2502 \u2502 \u2502 \u2514\u2500\u2500 PersonEditForm.class.php \u2502 \u2502 \u2514\u2500\u2500 page \u2502 \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonList.class.php \u2502 \u251c\u2500\u2500 page \u2502 \u2502 \u251c\u2500\u2500 PersonListPage.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonPage.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 cache \u2502 \u2502 \u2514\u2500\u2500 runtime \u2502 \u2502 \u2514\u2500\u2500 PersonRuntimeCache.class.php \u2502 \u251c\u2500\u2500 comment \u2502 \u2502 \u2514\u2500\u2500 manager \u2502 \u2502 \u2514\u2500\u2500 PersonCommentManager.class.php \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 handler \u2502 \u2514\u2500\u2500 PersonPageHandler.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 menuItem.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u251c\u2500\u2500 templates \u2502 \u251c\u2500\u2500 person.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u2514\u2500\u2500 userGroupOption.xml We will not mention every code change between the first part and this part, as we only want to focus on the important, new parts of the code. For example, there is a new Person::getLink() method and new language items have been added. For all changes, please refer to the source code on GitHub . Runtime Cache # To reduce the number of database queries when different APIs require person objects, we implement a runtime cache for people: files/lib/system/cache/runtime/PersonRuntimeCache.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <? php namespace wcf\\system\\cache\\runtime ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonList ; /** * Runtime cache implementation for people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cache\\Runtime * * @method Person[] getCachedObjects() * @method Person getObject($objectID) * @method Person[] getObjects(array $objectIDs) */ class PersonRuntimeCache extends AbstractRuntimeCache { /** * @inheritDoc */ protected $listClassName = PersonList :: class ; } Comments # To allow users to comment on people, we need to tell the system that people support comments. This is done by registering a com.woltlab.wcf.comment.commentableContent object type whose processor implements ICommentManager : objectType.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/objectType.xsd\" > <import> <type> <name> com.woltlab.wcf.person.personComment </name> <definitionname> com.woltlab.wcf.comment.commentableContent </definitionname> <classname> wcf\\system\\comment\\manager\\PersonCommentManager </classname> </type> </import> </data> The PersonCommentManager class extended ICommentManager \u2019s default implementation AbstractCommentManager : files/lib/system/comment/manager/PersonCommentManager.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 <? php namespace wcf\\system\\comment\\manager ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonEditor ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\WCF ; /** * Comment manager implementation for people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Comment\\Manager */ class PersonCommentManager extends AbstractCommentManager { /** * @inheritDoc */ protected $permissionAdd = 'user.person.canAddComment' ; /** * @inheritDoc */ protected $permissionAddWithoutModeration = 'user.person.canAddCommentWithoutModeration' ; /** * @inheritDoc */ protected $permissionCanModerate = 'mod.person.canModerateComment' ; /** * @inheritDoc */ protected $permissionDelete = 'user.person.canDeleteComment' ; /** * @inheritDoc */ protected $permissionEdit = 'user.person.canEditComment' ; /** * @inheritDoc */ protected $permissionModDelete = 'mod.person.canDeleteComment' ; /** * @inheritDoc */ protected $permissionModEdit = 'mod.person.canEditComment' ; /** * @inheritDoc */ public function getLink ( $objectTypeID , $objectID ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) -> getLink (); } /** * @inheritDoc */ public function isAccessible ( $objectID , $validateWritePermission = false ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) !== null ; } /** * @inheritDoc */ public function getTitle ( $objectTypeID , $objectID , $isResponse = false ) { if ( $isResponse ) { return WCF :: getLanguage () -> get ( 'wcf.person.commentResponse' ); } return WCF :: getLanguage () -> getDynamicVariable ( 'wcf.person.comment' ); } /** * @inheritDoc */ public function updateCounter ( $objectID , $value ) { ( new PersonEditor ( new Person ( $objectID ))) -> updateCounters ([ 'comments' => $value ]); } } First, the system is told the names of the permissions via the $permission* properties. More information about comment permissions can be found here . The getLink() method returns the link to the person with the passed comment id. As in isAccessible() , PersonRuntimeCache is used to potentially save database queries. The isAccessible() method checks if the active user can access the relevant person. As we do not have any special restrictions for accessing people, we only need to check if the person exists. The getTitle() method returns the title used for comments and responses, which is just a generic language item in this case. The updateCounter() updates the comments\u2019 counter of the person. We have added a new comments database table column to the wcf1_person database table in order to keep track on the number of comments. Additionally, we have added a new enableComments database table column to the wcf1_person database table whose value can be set when creating or editing a person in the ACP. With this option, comments on individual people can be disabled. Liking comments is already built-in and only requires some extra code in the PersonPage class for showing the likes of pre-loaded comments. Person Page # PersonPage # files/lib/page/PersonPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 <? php namespace wcf\\page ; use wcf\\data\\comment\\StructuredCommentList ; use wcf\\data\\person\\Person ; use wcf\\system\\comment\\CommentHandler ; use wcf\\system\\comment\\manager\\PersonCommentManager ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\WCF ; /** * Shows the details of a certain person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Page */ class PersonPage extends AbstractPage { /** * list of comments * @var StructuredCommentList */ public $commentList ; /** * person comment manager object * @var PersonCommentManager */ public $commentManager ; /** * id of the person comment object type * @var int */ public $commentObjectTypeID = 0 ; /** * shown person * @var Person */ public $person ; /** * id of the shown person * @var int */ public $personID = 0 ; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'commentCanAdd' => WCF :: getSession () -> getPermission ( 'user.person.canAddComment' ), 'commentList' => $this -> commentList , 'commentObjectTypeID' => $this -> commentObjectTypeID , 'lastCommentTime' => $this -> commentList ? $this -> commentList -> getMinCommentTime () : 0 , 'likeData' => MODULE_LIKE && $this -> commentList ? $this -> commentList -> getLikeData () : [], 'person' => $this -> person , ]); } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( $this -> person -> enableComments ) { $this -> commentObjectTypeID = CommentHandler :: getInstance () -> getObjectTypeID ( 'com.woltlab.wcf.person.personComment' ); $this -> commentManager = CommentHandler :: getInstance () -> getObjectType ( $this -> commentObjectTypeID ) -> getProcessor (); $this -> commentList = CommentHandler :: getInstance () -> getCommentList ( $this -> commentManager , $this -> commentObjectTypeID , $this -> person -> personID ); } } /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> personID = \\intval ( $_REQUEST [ 'id' ]); } $this -> person = new Person ( $this -> personID ); if ( ! $this -> person -> personID ) { throw new IllegalLinkException (); } } } The PersonPage class is similar to the PersonEditForm in the ACP in that it reads the id of the requested person from the request data and validates the id in readParameters() . The rest of the code only handles fetching the list of comments on the requested person. In readData() , this list is fetched using CommentHandler::getCommentList() if comments are enabled for the person. The assignVariables() method assigns some additional template variables like $commentCanAdd , which is 1 if the active person can add comments and is 0 otherwise, $lastCommentTime , which contains the UNIX timestamp of the last comment, and $likeData , which contains data related to the likes for the disabled comments. person.tpl # templates/person.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 {capture assign='pageTitle'}{$person} - {lang}wcf.person.list{/lang}{/capture} {capture assign='contentTitle'}{$person}{/capture} {include file='header'} {if $person->enableComments} {if $commentList|count || $commentCanAdd} <section id=\"comments\" class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> {lang}wcf.person.comments{/lang} {if $person->comments}<span class=\"badge\">{#$person->comments}</span>{/if} </h2> </header> {include file='__commentJavaScript' commentContainerID='personCommentList'} <div class=\"personComments\"> <ul id=\"personCommentList\" class=\"commentList containerList\" {* *}data-can-add=\"{if $commentCanAdd}true{else}false{/if}\" {* *}data-object-id=\"{@$person->personID}\" {* *}data-object-type-id=\"{@$commentObjectTypeID}\" {* *}data-comments=\"{if $person->comments}{@$commentList->countObjects()}{else}0{/if}\" {* *}data-last-comment-time=\"{@$lastCommentTime}\" {* *}> {include file='commentListAddComment' wysiwygSelector='personCommentListAddComment'} {include file='commentList'} </ul> </div> </section> {/if} {/if} <footer class=\"contentFooter\"> {hascontent} <nav class=\"contentFooterNavigation\"> <ul> {content}{event name='contentFooterNavigation'}{/content} </ul> </nav> {/hascontent} </footer> {include file='footer'} For now, the person template is still very empty and only shows the comments in the content area. The template code shown for comments is very generic and used in this form in many locations as it only sets the header of the comment list and the container ul#personCommentList element for the comments shown by commentList template. The ul#personCommentList elements has five additional data- attributes required by the JavaScript API for comments for loading more comments or creating new ones. The commentListAddComment template adds the WYSIWYG support. The attribute wysiwygSelector should be the id of the comment list personCommentList with an additional AddComment suffix. page.xml # page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.people.PersonList\" > <pageType> system </pageType> <controller> wcf\\page\\PersonListPage </controller> <name language= \"de\" > Personen-Liste </name> <name language= \"en\" > Person List </name> <content language= \"de\" > <title> Personen </title> </content> <content language= \"en\" > <title> People </title> </content> </page> <page identifier= \"com.woltlab.wcf.people.Person\" > <pageType> system </pageType> <controller> wcf\\page\\PersonPage </controller> <handler> wcf\\system\\page\\handler\\PersonPageHandler </handler> <name language= \"de\" > Person </name> <name language= \"en\" > Person </name> <requireObjectID> 1 </requireObjectID> <parent> com.woltlab.wcf.people.PersonList </parent> </page> </import> </data> The page.xml file has been extended for the new person page with identifier com.woltlab.wcf.people.Person . Compared to the pre-existing com.woltlab.wcf.people.PersonList page, there are four differences: It has a <handler> element with a class name as value. This aspect will be discussed in more detail in the next section. There are no <content> elements because, both, the title and the content of the page are dynamically generated in the template. The <requireObjectID> tells the system that this page requires an object id to properly work, in this case a valid person id. This page has a <parent> page, the person list page. In general, the details page for any type of object that is listed on a different page has the list page as its parent. PersonPageHandler # files/lib/system/page/handler/PersonPageHandler.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 <? php namespace wcf\\system\\page\\handler ; use wcf\\data\\page\\Page ; use wcf\\data\\person\\PersonList ; use wcf\\data\\user\\online\\UserOnline ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\database\\util\\PreparedStatementConditionBuilder ; use wcf\\system\\WCF ; /** * Page handler implementation for person page. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Page\\Handler */ class PersonPageHandler extends AbstractLookupPageHandler implements IOnlineLocationPageHandler { use TOnlineLocationPageHandler ; /** * @inheritDoc */ public function getLink ( $objectID ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) -> getLink (); } /** * Returns the textual description if a user is currently online viewing this page. * * @see IOnlineLocationPageHandler::getOnlineLocation() * * @param Page $page visited page * @param UserOnline $user user online object with request data * @return string */ public function getOnlineLocation ( Page $page , UserOnline $user ) { if ( $user -> pageObjectID === null ) { return '' ; } $person = PersonRuntimeCache :: getInstance () -> getObject ( $user -> pageObjectID ); if ( $person === null ) { return '' ; } return WCF :: getLanguage () -> getDynamicVariable ( 'wcf.page.onlineLocation.' . $page -> identifier , [ 'person' => $person ]); } /** * @inheritDoc */ public function isValid ( $objectID = null ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) !== null ; } /** * @inheritDoc */ public function lookup ( $searchString ) { $conditionBuilder = new PreparedStatementConditionBuilder ( false , 'OR' ); $conditionBuilder -> add ( 'person.firstName LIKE ?' , [ '%' . $searchString . '%' ]); $conditionBuilder -> add ( 'person.lastName LIKE ?' , [ '%' . $searchString . '%' ]); $personList = new PersonList (); $personList -> getConditionBuilder () -> add ( $conditionBuilder , $conditionBuilder -> getParameters ()); $personList -> readObjects (); $results = []; foreach ( $personList as $person ) { $results [] = [ 'image' => 'fa-user' , 'link' => $person -> getLink (), 'objectID' => $person -> personID , 'title' => $person -> getTitle (), ]; } return $results ; } /** * Prepares fetching all necessary data for the textual description if a user is currently online * viewing this page. * * @see IOnlineLocationPageHandler::prepareOnlineLocation() * * @param Page $page visited page * @param UserOnline $user user online object with request data */ public function prepareOnlineLocation ( Page $page , UserOnline $user ) { if ( $user -> pageObjectID !== null ) { PersonRuntimeCache :: getInstance () -> cacheObjectID ( $user -> pageObjectID ); } } } Like any page handler, the PersonPageHandler class has to implement the IMenuPageHandler interface, which should be done by extending the AbstractMenuPageHandler class. As we want administrators to link to specific people in menus, for example, we have to also implement the ILookupPageHandler interface by extending the AbstractLookupPageHandler class. For the ILookupPageHandler interface, we need to implement three methods: getLink($objectID) returns the link to the person page with the given id. In this case, we simply delegate this method call to the Person object returned by PersonRuntimeCache::getObject() . isValid($objectID) returns true if the person with the given id exists, otherwise false . Here, we use PersonRuntimeCache::getObject() again and check if the return value is null , which is the case for non-existing people. lookup($searchString) is used when setting up an internal link and when searching for the linked person. This method simply searches the first and last name of the people and returns an array with the person data. While the link , the objectID , and the title element are self-explanatory, the image element can either contain an HTML <img> tag, which is displayed next to the search result (WoltLab Suite uses an image tag for users showing their avatar, for example), or a FontAwesome icon class (starting with fa- ). Additionally, the class also implements IOnlineLocationPageHandler which is used to determine the online location of users. To ensure upwards-compatibility if the IOnlineLocationPageHandler interface changes, the TOnlineLocationPageHandler trait is used. The IOnlineLocationPageHandler interface requires two methods to be implemented: getOnlineLocation(Page $page, UserOnline $user) returns the textual description of the online location. The language item for the user online locations should use the pattern wcf.page.onlineLocation.{page identifier} . prepareOnlineLocation(Page $page, UserOnline $user) is called for each user online before the getOnlineLocation() calls. In this case, calling prepareOnlineLocation() first enables us to add all relevant person ids to the person runtime cache so that for all getOnlineLocation() calls combined, only one database query is necessary to fetch all person objects. This concludes the third part of our tutorial series after which each person has a dedicated page on which people can comment on the person. The complete source code of this part can be found on GitHub .","title":"Part 3"},{"location":"tutorial/series/part_3/#part-3-person-page-and-comments","text":"In this part of our tutorial series, we will add a new front end page to our package that is dedicated to each person and shows their personal details. To make good use of this new page and introduce a new API of WoltLab Suite, we will add the opportunity for users to comment on the person using WoltLab Suite\u2019s reusable comment functionality.","title":"Part 3: Person Page and Comments"},{"location":"tutorial/series/part_3/#package-functionality","text":"In addition to the existing functions from part 1 , the package will provide the following possibilities/functions after this part of the tutorial: Details page for each person linked in the front end person list Comment on people on their respective page (can be disabled per person) User online location for person details page with name and link to person details page Create menu items linking to specific person details pages","title":"Package Functionality"},{"location":"tutorial/series/part_3/#used-components","text":"In addition to the components used in part 1 , we will use the objectType package installation plugin , use the comment API , create a runtime cache , and create a page handler.","title":"Used Components"},{"location":"tutorial/series/part_3/#package-structure","text":"The complete package will have the following file structure (including the files from part 1 ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 \u251c\u2500\u2500 acpMenu.xml \u251c\u2500\u2500 acptemplates \u2502 \u251c\u2500\u2500 personAdd.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u251c\u2500\u2500 form \u2502 \u2502 \u2502 \u251c\u2500\u2500 PersonAddForm.class.php \u2502 \u2502 \u2502 \u2514\u2500\u2500 PersonEditForm.class.php \u2502 \u2502 \u2514\u2500\u2500 page \u2502 \u2502 \u2514\u2500\u2500 PersonListPage.class.php \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonList.class.php \u2502 \u251c\u2500\u2500 page \u2502 \u2502 \u251c\u2500\u2500 PersonListPage.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonPage.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 cache \u2502 \u2502 \u2514\u2500\u2500 runtime \u2502 \u2502 \u2514\u2500\u2500 PersonRuntimeCache.class.php \u2502 \u251c\u2500\u2500 comment \u2502 \u2502 \u2514\u2500\u2500 manager \u2502 \u2502 \u2514\u2500\u2500 PersonCommentManager.class.php \u2502 \u2514\u2500\u2500 page \u2502 \u2514\u2500\u2500 handler \u2502 \u2514\u2500\u2500 PersonPageHandler.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 menuItem.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 package.xml \u251c\u2500\u2500 page.xml \u251c\u2500\u2500 templates \u2502 \u251c\u2500\u2500 person.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u2514\u2500\u2500 userGroupOption.xml We will not mention every code change between the first part and this part, as we only want to focus on the important, new parts of the code. For example, there is a new Person::getLink() method and new language items have been added. For all changes, please refer to the source code on GitHub .","title":"Package Structure"},{"location":"tutorial/series/part_3/#runtime-cache","text":"To reduce the number of database queries when different APIs require person objects, we implement a runtime cache for people: files/lib/system/cache/runtime/PersonRuntimeCache.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <? php namespace wcf\\system\\cache\\runtime ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonList ; /** * Runtime cache implementation for people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Cache\\Runtime * * @method Person[] getCachedObjects() * @method Person getObject($objectID) * @method Person[] getObjects(array $objectIDs) */ class PersonRuntimeCache extends AbstractRuntimeCache { /** * @inheritDoc */ protected $listClassName = PersonList :: class ; }","title":"Runtime Cache"},{"location":"tutorial/series/part_3/#comments","text":"To allow users to comment on people, we need to tell the system that people support comments. This is done by registering a com.woltlab.wcf.comment.commentableContent object type whose processor implements ICommentManager : objectType.xml 1 2 3 4 5 6 7 8 9 10 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/objectType.xsd\" > <import> <type> <name> com.woltlab.wcf.person.personComment </name> <definitionname> com.woltlab.wcf.comment.commentableContent </definitionname> <classname> wcf\\system\\comment\\manager\\PersonCommentManager </classname> </type> </import> </data> The PersonCommentManager class extended ICommentManager \u2019s default implementation AbstractCommentManager : files/lib/system/comment/manager/PersonCommentManager.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 <? php namespace wcf\\system\\comment\\manager ; use wcf\\data\\person\\Person ; use wcf\\data\\person\\PersonEditor ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\WCF ; /** * Comment manager implementation for people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Comment\\Manager */ class PersonCommentManager extends AbstractCommentManager { /** * @inheritDoc */ protected $permissionAdd = 'user.person.canAddComment' ; /** * @inheritDoc */ protected $permissionAddWithoutModeration = 'user.person.canAddCommentWithoutModeration' ; /** * @inheritDoc */ protected $permissionCanModerate = 'mod.person.canModerateComment' ; /** * @inheritDoc */ protected $permissionDelete = 'user.person.canDeleteComment' ; /** * @inheritDoc */ protected $permissionEdit = 'user.person.canEditComment' ; /** * @inheritDoc */ protected $permissionModDelete = 'mod.person.canDeleteComment' ; /** * @inheritDoc */ protected $permissionModEdit = 'mod.person.canEditComment' ; /** * @inheritDoc */ public function getLink ( $objectTypeID , $objectID ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) -> getLink (); } /** * @inheritDoc */ public function isAccessible ( $objectID , $validateWritePermission = false ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) !== null ; } /** * @inheritDoc */ public function getTitle ( $objectTypeID , $objectID , $isResponse = false ) { if ( $isResponse ) { return WCF :: getLanguage () -> get ( 'wcf.person.commentResponse' ); } return WCF :: getLanguage () -> getDynamicVariable ( 'wcf.person.comment' ); } /** * @inheritDoc */ public function updateCounter ( $objectID , $value ) { ( new PersonEditor ( new Person ( $objectID ))) -> updateCounters ([ 'comments' => $value ]); } } First, the system is told the names of the permissions via the $permission* properties. More information about comment permissions can be found here . The getLink() method returns the link to the person with the passed comment id. As in isAccessible() , PersonRuntimeCache is used to potentially save database queries. The isAccessible() method checks if the active user can access the relevant person. As we do not have any special restrictions for accessing people, we only need to check if the person exists. The getTitle() method returns the title used for comments and responses, which is just a generic language item in this case. The updateCounter() updates the comments\u2019 counter of the person. We have added a new comments database table column to the wcf1_person database table in order to keep track on the number of comments. Additionally, we have added a new enableComments database table column to the wcf1_person database table whose value can be set when creating or editing a person in the ACP. With this option, comments on individual people can be disabled. Liking comments is already built-in and only requires some extra code in the PersonPage class for showing the likes of pre-loaded comments.","title":"Comments"},{"location":"tutorial/series/part_3/#person-page","text":"","title":"Person Page"},{"location":"tutorial/series/part_3/#personpage","text":"files/lib/page/PersonPage.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 <? php namespace wcf\\page ; use wcf\\data\\comment\\StructuredCommentList ; use wcf\\data\\person\\Person ; use wcf\\system\\comment\\CommentHandler ; use wcf\\system\\comment\\manager\\PersonCommentManager ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\WCF ; /** * Shows the details of a certain person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Page */ class PersonPage extends AbstractPage { /** * list of comments * @var StructuredCommentList */ public $commentList ; /** * person comment manager object * @var PersonCommentManager */ public $commentManager ; /** * id of the person comment object type * @var int */ public $commentObjectTypeID = 0 ; /** * shown person * @var Person */ public $person ; /** * id of the shown person * @var int */ public $personID = 0 ; /** * @inheritDoc */ public function assignVariables () { parent :: assignVariables (); WCF :: getTPL () -> assign ([ 'commentCanAdd' => WCF :: getSession () -> getPermission ( 'user.person.canAddComment' ), 'commentList' => $this -> commentList , 'commentObjectTypeID' => $this -> commentObjectTypeID , 'lastCommentTime' => $this -> commentList ? $this -> commentList -> getMinCommentTime () : 0 , 'likeData' => MODULE_LIKE && $this -> commentList ? $this -> commentList -> getLikeData () : [], 'person' => $this -> person , ]); } /** * @inheritDoc */ public function readData () { parent :: readData (); if ( $this -> person -> enableComments ) { $this -> commentObjectTypeID = CommentHandler :: getInstance () -> getObjectTypeID ( 'com.woltlab.wcf.person.personComment' ); $this -> commentManager = CommentHandler :: getInstance () -> getObjectType ( $this -> commentObjectTypeID ) -> getProcessor (); $this -> commentList = CommentHandler :: getInstance () -> getCommentList ( $this -> commentManager , $this -> commentObjectTypeID , $this -> person -> personID ); } } /** * @inheritDoc */ public function readParameters () { parent :: readParameters (); if ( isset ( $_REQUEST [ 'id' ])) { $this -> personID = \\intval ( $_REQUEST [ 'id' ]); } $this -> person = new Person ( $this -> personID ); if ( ! $this -> person -> personID ) { throw new IllegalLinkException (); } } } The PersonPage class is similar to the PersonEditForm in the ACP in that it reads the id of the requested person from the request data and validates the id in readParameters() . The rest of the code only handles fetching the list of comments on the requested person. In readData() , this list is fetched using CommentHandler::getCommentList() if comments are enabled for the person. The assignVariables() method assigns some additional template variables like $commentCanAdd , which is 1 if the active person can add comments and is 0 otherwise, $lastCommentTime , which contains the UNIX timestamp of the last comment, and $likeData , which contains data related to the likes for the disabled comments.","title":"PersonPage"},{"location":"tutorial/series/part_3/#persontpl","text":"templates/person.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 {capture assign='pageTitle'}{$person} - {lang}wcf.person.list{/lang}{/capture} {capture assign='contentTitle'}{$person}{/capture} {include file='header'} {if $person->enableComments} {if $commentList|count || $commentCanAdd} <section id=\"comments\" class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> {lang}wcf.person.comments{/lang} {if $person->comments}<span class=\"badge\">{#$person->comments}</span>{/if} </h2> </header> {include file='__commentJavaScript' commentContainerID='personCommentList'} <div class=\"personComments\"> <ul id=\"personCommentList\" class=\"commentList containerList\" {* *}data-can-add=\"{if $commentCanAdd}true{else}false{/if}\" {* *}data-object-id=\"{@$person->personID}\" {* *}data-object-type-id=\"{@$commentObjectTypeID}\" {* *}data-comments=\"{if $person->comments}{@$commentList->countObjects()}{else}0{/if}\" {* *}data-last-comment-time=\"{@$lastCommentTime}\" {* *}> {include file='commentListAddComment' wysiwygSelector='personCommentListAddComment'} {include file='commentList'} </ul> </div> </section> {/if} {/if} <footer class=\"contentFooter\"> {hascontent} <nav class=\"contentFooterNavigation\"> <ul> {content}{event name='contentFooterNavigation'}{/content} </ul> </nav> {/hascontent} </footer> {include file='footer'} For now, the person template is still very empty and only shows the comments in the content area. The template code shown for comments is very generic and used in this form in many locations as it only sets the header of the comment list and the container ul#personCommentList element for the comments shown by commentList template. The ul#personCommentList elements has five additional data- attributes required by the JavaScript API for comments for loading more comments or creating new ones. The commentListAddComment template adds the WYSIWYG support. The attribute wysiwygSelector should be the id of the comment list personCommentList with an additional AddComment suffix.","title":"person.tpl"},{"location":"tutorial/series/part_3/#pagexml","text":"page.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/page.xsd\" > <import> <page identifier= \"com.woltlab.wcf.people.PersonList\" > <pageType> system </pageType> <controller> wcf\\page\\PersonListPage </controller> <name language= \"de\" > Personen-Liste </name> <name language= \"en\" > Person List </name> <content language= \"de\" > <title> Personen </title> </content> <content language= \"en\" > <title> People </title> </content> </page> <page identifier= \"com.woltlab.wcf.people.Person\" > <pageType> system </pageType> <controller> wcf\\page\\PersonPage </controller> <handler> wcf\\system\\page\\handler\\PersonPageHandler </handler> <name language= \"de\" > Person </name> <name language= \"en\" > Person </name> <requireObjectID> 1 </requireObjectID> <parent> com.woltlab.wcf.people.PersonList </parent> </page> </import> </data> The page.xml file has been extended for the new person page with identifier com.woltlab.wcf.people.Person . Compared to the pre-existing com.woltlab.wcf.people.PersonList page, there are four differences: It has a <handler> element with a class name as value. This aspect will be discussed in more detail in the next section. There are no <content> elements because, both, the title and the content of the page are dynamically generated in the template. The <requireObjectID> tells the system that this page requires an object id to properly work, in this case a valid person id. This page has a <parent> page, the person list page. In general, the details page for any type of object that is listed on a different page has the list page as its parent.","title":"page.xml"},{"location":"tutorial/series/part_3/#personpagehandler","text":"files/lib/system/page/handler/PersonPageHandler.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 <? php namespace wcf\\system\\page\\handler ; use wcf\\data\\page\\Page ; use wcf\\data\\person\\PersonList ; use wcf\\data\\user\\online\\UserOnline ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\database\\util\\PreparedStatementConditionBuilder ; use wcf\\system\\WCF ; /** * Page handler implementation for person page. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Page\\Handler */ class PersonPageHandler extends AbstractLookupPageHandler implements IOnlineLocationPageHandler { use TOnlineLocationPageHandler ; /** * @inheritDoc */ public function getLink ( $objectID ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) -> getLink (); } /** * Returns the textual description if a user is currently online viewing this page. * * @see IOnlineLocationPageHandler::getOnlineLocation() * * @param Page $page visited page * @param UserOnline $user user online object with request data * @return string */ public function getOnlineLocation ( Page $page , UserOnline $user ) { if ( $user -> pageObjectID === null ) { return '' ; } $person = PersonRuntimeCache :: getInstance () -> getObject ( $user -> pageObjectID ); if ( $person === null ) { return '' ; } return WCF :: getLanguage () -> getDynamicVariable ( 'wcf.page.onlineLocation.' . $page -> identifier , [ 'person' => $person ]); } /** * @inheritDoc */ public function isValid ( $objectID = null ) { return PersonRuntimeCache :: getInstance () -> getObject ( $objectID ) !== null ; } /** * @inheritDoc */ public function lookup ( $searchString ) { $conditionBuilder = new PreparedStatementConditionBuilder ( false , 'OR' ); $conditionBuilder -> add ( 'person.firstName LIKE ?' , [ '%' . $searchString . '%' ]); $conditionBuilder -> add ( 'person.lastName LIKE ?' , [ '%' . $searchString . '%' ]); $personList = new PersonList (); $personList -> getConditionBuilder () -> add ( $conditionBuilder , $conditionBuilder -> getParameters ()); $personList -> readObjects (); $results = []; foreach ( $personList as $person ) { $results [] = [ 'image' => 'fa-user' , 'link' => $person -> getLink (), 'objectID' => $person -> personID , 'title' => $person -> getTitle (), ]; } return $results ; } /** * Prepares fetching all necessary data for the textual description if a user is currently online * viewing this page. * * @see IOnlineLocationPageHandler::prepareOnlineLocation() * * @param Page $page visited page * @param UserOnline $user user online object with request data */ public function prepareOnlineLocation ( Page $page , UserOnline $user ) { if ( $user -> pageObjectID !== null ) { PersonRuntimeCache :: getInstance () -> cacheObjectID ( $user -> pageObjectID ); } } } Like any page handler, the PersonPageHandler class has to implement the IMenuPageHandler interface, which should be done by extending the AbstractMenuPageHandler class. As we want administrators to link to specific people in menus, for example, we have to also implement the ILookupPageHandler interface by extending the AbstractLookupPageHandler class. For the ILookupPageHandler interface, we need to implement three methods: getLink($objectID) returns the link to the person page with the given id. In this case, we simply delegate this method call to the Person object returned by PersonRuntimeCache::getObject() . isValid($objectID) returns true if the person with the given id exists, otherwise false . Here, we use PersonRuntimeCache::getObject() again and check if the return value is null , which is the case for non-existing people. lookup($searchString) is used when setting up an internal link and when searching for the linked person. This method simply searches the first and last name of the people and returns an array with the person data. While the link , the objectID , and the title element are self-explanatory, the image element can either contain an HTML <img> tag, which is displayed next to the search result (WoltLab Suite uses an image tag for users showing their avatar, for example), or a FontAwesome icon class (starting with fa- ). Additionally, the class also implements IOnlineLocationPageHandler which is used to determine the online location of users. To ensure upwards-compatibility if the IOnlineLocationPageHandler interface changes, the TOnlineLocationPageHandler trait is used. The IOnlineLocationPageHandler interface requires two methods to be implemented: getOnlineLocation(Page $page, UserOnline $user) returns the textual description of the online location. The language item for the user online locations should use the pattern wcf.page.onlineLocation.{page identifier} . prepareOnlineLocation(Page $page, UserOnline $user) is called for each user online before the getOnlineLocation() calls. In this case, calling prepareOnlineLocation() first enables us to add all relevant person ids to the person runtime cache so that for all getOnlineLocation() calls combined, only one database query is necessary to fetch all person objects. This concludes the third part of our tutorial series after which each person has a dedicated page on which people can comment on the person. The complete source code of this part can be found on GitHub .","title":"PersonPageHandler"},{"location":"tutorial/series/part_4/","text":"Part 4: Box and Box Conditions # In this part of our tutorial series, we add support for creating boxes listing people. Package Functionality # In addition to the existing functions from part 3 , the package will provide the following functionality after this part of the tutorial: Creating boxes dynamically listing people Filtering the people listed in boxes using conditions Used Components # In addition to the components used in previous parts, we will use the objectTypeDefinition package installation plugin and use the box and condition APIs. To pre-install a specific person list box, we refer to the documentation of the box package installation plugin . Package Structure # The complete package will have the following file structure ( excluding unchanged files from part 3 ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 box \u2502 \u2502 \u2514\u2500\u2500 PersonListBoxController.class.php \u2502 \u2514\u2500\u2500 condition \u2502 \u2514\u2500\u2500 person \u2502 \u251c\u2500\u2500 PersonFirstNameTextPropertyCondition.class.php \u2502 \u2514\u2500\u2500 PersonLastNameTextPropertyCondition.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 objectTypeDefinition.xml \u2514\u2500\u2500 templates \u2514\u2500\u2500 boxPersonList.tpl For all changes, please refer to the source code on GitHub . Box Controller # In addition to static boxes with fixed contents, administrators are able to create dynamic boxes with contents from the database. In our case here, we want administrators to be able to create boxes listing people. To do so, we first have to register a new object type for this person list box controller for the object type definition com.woltlab.wcf.boxController : 1 2 3 4 5 <type> <name> com.woltlab.wcf.personList </name> <definitionname> com.woltlab.wcf.boxController </definitionname> <classname> wcf\\system\\box\\PersonListBoxController </classname> </type> The com.woltlab.wcf.boxController object type definition requires the provided class to implement wcf\\system\\box\\IBoxController : files/lib/system/box/PersonListBoxController.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <? php namespace wcf\\system\\box ; use wcf\\data\\person\\PersonList ; use wcf\\system\\WCF ; /** * Dynamic box controller implementation for a list of persons. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Box */ class PersonListBoxController extends AbstractDatabaseObjectListBoxController { /** * @inheritDoc */ protected $conditionDefinition = 'com.woltlab.wcf.box.personList.condition' ; /** * @inheritDoc */ public $defaultLimit = 5 ; /** * @inheritDoc */ protected $sortFieldLanguageItemPrefix = 'wcf.person' ; /** * @inheritDoc */ protected static $supportedPositions = [ 'sidebarLeft' , 'sidebarRight' , ]; /** * @inheritDoc */ public $validSortFields = [ 'firstName' , 'lastName' , 'comments' , ]; /** * @inheritDoc */ protected function getObjectList () { return new PersonList (); } /** * @inheritDoc */ protected function getTemplate () { return WCF :: getTPL () -> fetch ( 'boxPersonList' , 'wcf' , [ 'boxPersonList' => $this -> objectList , 'boxSortField' => $this -> sortField , 'boxPosition' => $this -> box -> position , ], true ); } } By extending AbstractDatabaseObjectListBoxController , we only have to provide minimal data ourself and rely mostly on the default implementation provided by AbstractDatabaseObjectListBoxController : As we will support conditions for the listed people, we have to set the relevant condition definition via $conditionDefinition . AbstractDatabaseObjectListBoxController already supports restricting the number of listed objects. To do so, you only have to specify the default number of listed objects via $defaultLimit . AbstractDatabaseObjectListBoxController also supports setting the sort order of the listed objects. You have to provide the supported sort fields via $validSortFields and specify the prefix used for the language items of the sort fields via $sortFieldLanguageItemPrefix so that for every $validSortField in $validSortFields , the language item {$sortFieldLanguageItemPrefix}.{$validSortField} must exist. The box system supports different positions . Each box controller specifies the positions it supports via $supportedPositions . To keep the implementation simple here as different positions might require different output in the template, we restrict ourselves to sidebars. getObjectList() returns an instance of DatabaseObjectList that is used to read the listed objects. getObjectList() itself must not call readObjects() , as AbstractDatabaseObjectListBoxController takes care of calling the method after adding the conditions and setting the sort order. getTemplate() returns the contents of the box relying on the boxPersonList template here: templates/boxPersonList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <ul class=\"sidebarItemList\"> { foreach from = $boxPersonList item = boxPerson } <li class=\"box24\"> <span class=\"icon icon24 fa-user\"></span> <div class=\"sidebarItemTitle\"> <h3> { anchor object = $boxPerson } </h3> { capture assign = '__boxPersonDescription' }{ lang __optional = true } wcf.person.boxList.description. { $boxSortField }{ /lang }{ /capture } { if $__boxPersonDescription } <small> { @ $__boxPersonDescription } </small> { /if } </div> </li> { /foreach } </ul> The template relies on a .sidebarItemList element, which is generally used for sidebar listings. (If different box positions were supported, we either have to generate different output by considering the value of $boxPosition in the template or by using different templates in getTemplate() .) One specific piece of code is the $__boxPersonDescription variable, which supports an optional description below the person's name relying on the optional language item wcf.person.boxList.description.{$boxSortField} . We only add one such language item when sorting the people by comments: In such a case, the number of comments will be shown. (When sorting by first and last name, there are no additional useful information that could be shown here, though the plugin from part 2 adding support for birthdays might also show the birthday when sorting by first or last name.) Lastly, we also provide the language item wcf.acp.box.boxController.com.woltlab.wcf.personList , which is used in the list of available box controllers. Conditions # The condition system can be used to generally filter a list of objects. In our case, the box system supports conditions to filter the objects shown in a specific box. Admittedly, our current person implementation only contains minimal data so that filtering might not make the most sense here but it will still show how to use the condition system for boxes. We will support filtering the people by their first and last name so that, for example, a box can be created listing all people with a specific first name. The first step for condition support is to register a object type definition for the relevant conditions requiring the IObjectListCondition interface: objectTypeDefinition.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/objectTypeDefinition.xsd\" > <import> <definition> <name> com.woltlab.wcf.box.personList.condition </name> <interfacename> wcf\\system\\condition\\IObjectListCondition </interfacename> </definition> </import> </data> Next, we register the specific conditions for filtering by the first and last name using this object type condition: 1 2 3 4 5 6 7 8 9 10 <type> <name> com.woltlab.wcf.people.firstName </name> <definitionname> com.woltlab.wcf.box.personList.condition </definitionname> <classname> wcf\\system\\condition\\person\\PersonFirstNameTextPropertyCondition </classname> </type> <type> <name> com.woltlab.wcf.people.lastName </name> <definitionname> com.woltlab.wcf.box.personList.condition </definitionname> <classname> wcf\\system\\condition\\person\\PersonLastNameTextPropertyCondition </classname> </type> PersonFirstNameTextPropertyCondition and PersonLastNameTextPropertyCondition only differ minimally so that we only focus on PersonFirstNameTextPropertyCondition here, which relies on the default implementation AbstractObjectTextPropertyCondition and only requires specifying different object properties: files/lib/system/condition/person/PersonFirstNameTextPropertyCondition.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <? php namespace wcf\\system\\condition\\person ; use wcf\\data\\person\\Person ; use wcf\\system\\condition\\AbstractObjectTextPropertyCondition ; /** * Condition implementation for the first name of a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Core\\System\\Condition */ class PersonFirstNameTextPropertyCondition extends AbstractObjectTextPropertyCondition { /** * @inheritDoc */ protected $className = Person :: class ; /** * @inheritDoc */ protected $description = 'wcf.person.condition.firstName.description' ; /** * @inheritDoc */ protected $fieldName = 'personFirstName' ; /** * @inheritDoc */ protected $label = 'wcf.person.firstName' ; /** * @inheritDoc */ protected $propertyName = 'firstName' ; /** * @inheritDoc */ protected $supportsMultipleValues = true ; } $className contains the class name of the relevant database object from which the class name of the database object list is derived and $propertyName is the name of the database object's property that contains the value used for filtering. By setting $supportsMultipleValues to true , multiple comma-separated values can be specified so that, for example, a box can also only list people with either of two specific first names. $description (optional), $fieldName , and $label are used in the output of the form field. (The implementation here is specific for AbstractObjectTextPropertyCondition . The wcf\\system\\condition namespace also contains several other default condition implementations.)","title":"Part 4"},{"location":"tutorial/series/part_4/#part-4-box-and-box-conditions","text":"In this part of our tutorial series, we add support for creating boxes listing people.","title":"Part 4: Box and Box Conditions"},{"location":"tutorial/series/part_4/#package-functionality","text":"In addition to the existing functions from part 3 , the package will provide the following functionality after this part of the tutorial: Creating boxes dynamically listing people Filtering the people listed in boxes using conditions","title":"Package Functionality"},{"location":"tutorial/series/part_4/#used-components","text":"In addition to the components used in previous parts, we will use the objectTypeDefinition package installation plugin and use the box and condition APIs. To pre-install a specific person list box, we refer to the documentation of the box package installation plugin .","title":"Used Components"},{"location":"tutorial/series/part_4/#package-structure","text":"The complete package will have the following file structure ( excluding unchanged files from part 3 ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 box \u2502 \u2502 \u2514\u2500\u2500 PersonListBoxController.class.php \u2502 \u2514\u2500\u2500 condition \u2502 \u2514\u2500\u2500 person \u2502 \u251c\u2500\u2500 PersonFirstNameTextPropertyCondition.class.php \u2502 \u2514\u2500\u2500 PersonLastNameTextPropertyCondition.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 objectTypeDefinition.xml \u2514\u2500\u2500 templates \u2514\u2500\u2500 boxPersonList.tpl For all changes, please refer to the source code on GitHub .","title":"Package Structure"},{"location":"tutorial/series/part_4/#box-controller","text":"In addition to static boxes with fixed contents, administrators are able to create dynamic boxes with contents from the database. In our case here, we want administrators to be able to create boxes listing people. To do so, we first have to register a new object type for this person list box controller for the object type definition com.woltlab.wcf.boxController : 1 2 3 4 5 <type> <name> com.woltlab.wcf.personList </name> <definitionname> com.woltlab.wcf.boxController </definitionname> <classname> wcf\\system\\box\\PersonListBoxController </classname> </type> The com.woltlab.wcf.boxController object type definition requires the provided class to implement wcf\\system\\box\\IBoxController : files/lib/system/box/PersonListBoxController.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <? php namespace wcf\\system\\box ; use wcf\\data\\person\\PersonList ; use wcf\\system\\WCF ; /** * Dynamic box controller implementation for a list of persons. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Box */ class PersonListBoxController extends AbstractDatabaseObjectListBoxController { /** * @inheritDoc */ protected $conditionDefinition = 'com.woltlab.wcf.box.personList.condition' ; /** * @inheritDoc */ public $defaultLimit = 5 ; /** * @inheritDoc */ protected $sortFieldLanguageItemPrefix = 'wcf.person' ; /** * @inheritDoc */ protected static $supportedPositions = [ 'sidebarLeft' , 'sidebarRight' , ]; /** * @inheritDoc */ public $validSortFields = [ 'firstName' , 'lastName' , 'comments' , ]; /** * @inheritDoc */ protected function getObjectList () { return new PersonList (); } /** * @inheritDoc */ protected function getTemplate () { return WCF :: getTPL () -> fetch ( 'boxPersonList' , 'wcf' , [ 'boxPersonList' => $this -> objectList , 'boxSortField' => $this -> sortField , 'boxPosition' => $this -> box -> position , ], true ); } } By extending AbstractDatabaseObjectListBoxController , we only have to provide minimal data ourself and rely mostly on the default implementation provided by AbstractDatabaseObjectListBoxController : As we will support conditions for the listed people, we have to set the relevant condition definition via $conditionDefinition . AbstractDatabaseObjectListBoxController already supports restricting the number of listed objects. To do so, you only have to specify the default number of listed objects via $defaultLimit . AbstractDatabaseObjectListBoxController also supports setting the sort order of the listed objects. You have to provide the supported sort fields via $validSortFields and specify the prefix used for the language items of the sort fields via $sortFieldLanguageItemPrefix so that for every $validSortField in $validSortFields , the language item {$sortFieldLanguageItemPrefix}.{$validSortField} must exist. The box system supports different positions . Each box controller specifies the positions it supports via $supportedPositions . To keep the implementation simple here as different positions might require different output in the template, we restrict ourselves to sidebars. getObjectList() returns an instance of DatabaseObjectList that is used to read the listed objects. getObjectList() itself must not call readObjects() , as AbstractDatabaseObjectListBoxController takes care of calling the method after adding the conditions and setting the sort order. getTemplate() returns the contents of the box relying on the boxPersonList template here: templates/boxPersonList.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <ul class=\"sidebarItemList\"> { foreach from = $boxPersonList item = boxPerson } <li class=\"box24\"> <span class=\"icon icon24 fa-user\"></span> <div class=\"sidebarItemTitle\"> <h3> { anchor object = $boxPerson } </h3> { capture assign = '__boxPersonDescription' }{ lang __optional = true } wcf.person.boxList.description. { $boxSortField }{ /lang }{ /capture } { if $__boxPersonDescription } <small> { @ $__boxPersonDescription } </small> { /if } </div> </li> { /foreach } </ul> The template relies on a .sidebarItemList element, which is generally used for sidebar listings. (If different box positions were supported, we either have to generate different output by considering the value of $boxPosition in the template or by using different templates in getTemplate() .) One specific piece of code is the $__boxPersonDescription variable, which supports an optional description below the person's name relying on the optional language item wcf.person.boxList.description.{$boxSortField} . We only add one such language item when sorting the people by comments: In such a case, the number of comments will be shown. (When sorting by first and last name, there are no additional useful information that could be shown here, though the plugin from part 2 adding support for birthdays might also show the birthday when sorting by first or last name.) Lastly, we also provide the language item wcf.acp.box.boxController.com.woltlab.wcf.personList , which is used in the list of available box controllers.","title":"Box Controller"},{"location":"tutorial/series/part_4/#conditions","text":"The condition system can be used to generally filter a list of objects. In our case, the box system supports conditions to filter the objects shown in a specific box. Admittedly, our current person implementation only contains minimal data so that filtering might not make the most sense here but it will still show how to use the condition system for boxes. We will support filtering the people by their first and last name so that, for example, a box can be created listing all people with a specific first name. The first step for condition support is to register a object type definition for the relevant conditions requiring the IObjectListCondition interface: objectTypeDefinition.xml 1 2 3 4 5 6 7 8 9 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/objectTypeDefinition.xsd\" > <import> <definition> <name> com.woltlab.wcf.box.personList.condition </name> <interfacename> wcf\\system\\condition\\IObjectListCondition </interfacename> </definition> </import> </data> Next, we register the specific conditions for filtering by the first and last name using this object type condition: 1 2 3 4 5 6 7 8 9 10 <type> <name> com.woltlab.wcf.people.firstName </name> <definitionname> com.woltlab.wcf.box.personList.condition </definitionname> <classname> wcf\\system\\condition\\person\\PersonFirstNameTextPropertyCondition </classname> </type> <type> <name> com.woltlab.wcf.people.lastName </name> <definitionname> com.woltlab.wcf.box.personList.condition </definitionname> <classname> wcf\\system\\condition\\person\\PersonLastNameTextPropertyCondition </classname> </type> PersonFirstNameTextPropertyCondition and PersonLastNameTextPropertyCondition only differ minimally so that we only focus on PersonFirstNameTextPropertyCondition here, which relies on the default implementation AbstractObjectTextPropertyCondition and only requires specifying different object properties: files/lib/system/condition/person/PersonFirstNameTextPropertyCondition.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <? php namespace wcf\\system\\condition\\person ; use wcf\\data\\person\\Person ; use wcf\\system\\condition\\AbstractObjectTextPropertyCondition ; /** * Condition implementation for the first name of a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license WoltLab License <http://www.woltlab.com/license-agreement.html> * @package WoltLabSuite\\Core\\System\\Condition */ class PersonFirstNameTextPropertyCondition extends AbstractObjectTextPropertyCondition { /** * @inheritDoc */ protected $className = Person :: class ; /** * @inheritDoc */ protected $description = 'wcf.person.condition.firstName.description' ; /** * @inheritDoc */ protected $fieldName = 'personFirstName' ; /** * @inheritDoc */ protected $label = 'wcf.person.firstName' ; /** * @inheritDoc */ protected $propertyName = 'firstName' ; /** * @inheritDoc */ protected $supportsMultipleValues = true ; } $className contains the class name of the relevant database object from which the class name of the database object list is derived and $propertyName is the name of the database object's property that contains the value used for filtering. By setting $supportsMultipleValues to true , multiple comma-separated values can be specified so that, for example, a box can also only list people with either of two specific first names. $description (optional), $fieldName , and $label are used in the output of the form field. (The implementation here is specific for AbstractObjectTextPropertyCondition . The wcf\\system\\condition namespace also contains several other default condition implementations.)","title":"Conditions"},{"location":"tutorial/series/part_5/","text":"Part 5: Person Information # This part of our tutorial series lays the foundation for future parts in which we will be using additional APIs, which we have not used in this series yet. To make use of those APIs, we need content generated by users in the frontend. Package Functionality # In addition to the existing functions from part 4 , the package will provide the following functionality after this part of the tutorial: Users are able to add information on the people in the frontend. Users are able to edit and delete the pieces of information they added. Moderators are able to edit and delete all pieces of information. Used Components # In addition to the components used in previous parts, we will use the form builder API to create forms shown in dialogs instead of dedicated pages and we will, for the first time, add TypeScript code . Package Structure # The package will have the following file structure excluding unchanged files from previous parts: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u251c\u2500\u2500 js \u2502 \u2502 \u2514\u2500\u2500 WoltLabSuite \u2502 \u2502 \u2514\u2500\u2500 Core \u2502 \u2502 \u2514\u2500\u2500 Controller \u2502 \u2502 \u2514\u2500\u2500 Person.js \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u2514\u2500\u2500 information \u2502 \u2502 \u251c\u2500\u2500 PersonInformation.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonInformationAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonInformationEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonInformationList.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u2514\u2500\u2500 worker \u2502 \u2514\u2500\u2500 PersonRebuildDataWorker.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 templates \u2502 \u251c\u2500\u2500 person.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 ts \u2502 \u2514\u2500\u2500 WoltLabSuite \u2502 \u2514\u2500\u2500 Core \u2502 \u2514\u2500\u2500 Controller \u2502 \u2514\u2500\u2500 Person.ts \u2514\u2500\u2500 userGroupOption.xml For all changes, please refer to the source code on GitHub . Miscellaneous # Before we focus on the main aspects of this part, we mention some minor aspects that will be used later on: Several new user group options and the relevant language items have been added related to creating, editing, and deleting information: mod.person.canEditInformation and mod.person.canDeleteInformation are moderative permissions to edit and delete any piece of information, regardless of who created it. user.person.canAddInformation is the permission for users to add new pieces of information. user.person.canEditInformation and user.person.canDeleteInformation are the user permissions to edit and the piece of information they created. The actual information text will be entered via a WYSIWYG editor, which requires an object type of the definition com.woltlab.wcf.message : com.woltlab.wcf.people.information . personList.tpl has been adjusted to show the number of pieces of information in the person statistics section. We have not updated the person list box to also support sorting by the number of pieces of information added for each person. Person Information Model # The PHP file with the database layout has been updated as follows: files/acp/database/install_com.woltlab.wcf.people.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 <? php use wcf\\system\\database\\table\\column\\DefaultTrueBooleanDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\IntDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\NotNullInt10DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\NotNullVarchar255DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\ObjectIdDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\SmallintDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\TextDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\VarcharDatabaseTableColumn ; use wcf\\system\\database\\table\\DatabaseTable ; use wcf\\system\\database\\table\\index\\DatabaseTableForeignKey ; use wcf\\system\\database\\table\\index\\DatabaseTablePrimaryIndex ; return [ DatabaseTable :: create ( 'wcf1_person' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'personID' ), NotNullVarchar255DatabaseTableColumn :: create ( 'firstName' ), NotNullVarchar255DatabaseTableColumn :: create ( 'lastName' ), NotNullInt10DatabaseTableColumn :: create ( 'informationCount' ) -> defaultValue ( 0 ), SmallintDatabaseTableColumn :: create ( 'comments' ) -> length ( 5 ) -> notNull () -> defaultValue ( 0 ), DefaultTrueBooleanDatabaseTableColumn :: create ( 'enableComments' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'personID' ]), ]), DatabaseTable :: create ( 'wcf1_person_information' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'informationID' ), NotNullInt10DatabaseTableColumn :: create ( 'personID' ), TextDatabaseTableColumn :: create ( 'information' ), IntDatabaseTableColumn :: create ( 'userID' ) -> length ( 10 ), NotNullVarchar255DatabaseTableColumn :: create ( 'username' ), VarcharDatabaseTableColumn :: create ( 'ipAddress' ) -> length ( 39 ) -> notNull ( true ) -> defaultValue ( '' ), NotNullInt10DatabaseTableColumn :: create ( 'time' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'informationID' ]), ]) -> foreignKeys ([ DatabaseTableForeignKey :: create () -> columns ([ 'personID' ]) -> referencedTable ( 'wcf1_person' ) -> referencedColumns ([ 'personID' ]) -> onDelete ( 'CASCADE' ), DatabaseTableForeignKey :: create () -> columns ([ 'userID' ]) -> referencedTable ( 'wcf1_user' ) -> referencedColumns ([ 'userID' ]) -> onDelete ( 'SET NULL' ), ]), ]; The number of pieces of information per person is tracked via the new informationCount column. The wcf1_person_information table has been added for the PersonInformation model. The meaning of the different columns is explained in the property documentation part of PersonInformation 's documentation (see below). The two foreign keys ensure that if a person is deleted, all of their information is also deleted, and that if a user is deleted, the userID column is set to NULL . files/lib/data/person/information/PersonInformation.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\DatabaseObject ; use wcf\\data\\person\\Person ; use wcf\\data\\user\\UserProfile ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\cache\\runtime\\UserProfileRuntimeCache ; use wcf\\system\\html\\output\\HtmlOutputProcessor ; use wcf\\system\\WCF ; /** * Represents a piece of information for a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person\\Information * * @property-read int $informationID unique id of the information * @property-read int $personID id of the person the information belongs to * @property-read string $information information text * @property-read int|null $userID id of the user who added the information or `null` if the user no longer exists * @property-read string $username name of the user who added the information * @property-read int $time timestamp at which the information was created */ class PersonInformation extends DatabaseObject { /** * Returns `true` if the active user can delete this piece of information and `false` otherwise. */ public function canDelete () : bool { if ( WCF :: getUser () -> userID && WCF :: getUser () -> userID == $this -> userID && WCF :: getSession () -> getPermission ( 'user.person.canDeleteInformation' ) ) { return true ; } return WCF :: getSession () -> getPermission ( 'mod.person.canDeleteInformation' ); } /** * Returns `true` if the active user can edit this piece of information and `false` otherwise. */ public function canEdit () : bool { if ( WCF :: getUser () -> userID && WCF :: getUser () -> userID == $this -> userID && WCF :: getSession () -> getPermission ( 'user.person.canEditInformation' ) ) { return true ; } return WCF :: getSession () -> getPermission ( 'mod.person.canEditInformation' ); } /** * Returns the formatted information. */ public function getFormattedInformation () : string { $processor = new HtmlOutputProcessor (); $processor -> process ( $this -> information , 'com.woltlab.wcf.people.information' , $this -> informationID ); return $processor -> getHtml (); } /** * Returns the person the information belongs to. */ public function getPerson () : Person { return PersonRuntimeCache :: getInstance () -> getObject ( $this -> personID ); } /** * Returns the user profile of the user who added the information. */ public function getUserProfile () : UserProfile { if ( $this -> userID ) { return UserProfileRuntimeCache :: getInstance () -> getObject ( $this -> userID ); } else { return UserProfile :: getGuestUserProfile ( $this -> username ); } } } PersonInformation provides two methods, canDelete() and canEdit() , to check whether the active user can delete or edit a specific piece of information. In both cases, it is checked if the current user has created the relevant piece of information to check the user-specific permissions or to fall back to the moderator-specific permissions. There also two getter methods for the person, the piece of information belongs to ( getPerson() ), and for the user profile of the user who created the information ( getUserProfile() ). In both cases, we use runtime caches, though in getUserProfile() , we also have to consider the case of the user who created the information being deleted, i.e. userID being null . For such a case, we also save the name of the user who created the information in username , so that we can return a guest user profile object in this case. The most interesting method is getFormattedInformation() , which returns the HTML code of the information text meant for output. To generate such an output, HtmlOutputProcessor::process() is used and here is where we first use the associated message object type com.woltlab.wcf.people.information mentioned before . While PersonInformationEditor is simply the default implementation and thus not explicitly shown here, PersonInformationList::readObjects() caches the relevant ids of the associated people and users who created the pieces of information using runtime caches: files/lib/data/person/information/PersonInformationList.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\DatabaseObjectList ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\cache\\runtime\\UserProfileRuntimeCache ; /** * Represents a list of person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\PersonInformation * * @method PersonInformation current() * @method PersonInformation[] getObjects() * @method PersonInformation|null search($objectID) * @property PersonInformation[] $objects */ class PersonInformationList extends DatabaseObjectList { public function readObjects () { parent :: readObjects (); UserProfileRuntimeCache :: getInstance () -> cacheObjectIDs ( \\array_unique ( \\array_filter ( \\array_column ( $this -> objects , 'userID' )))); PersonRuntimeCache :: getInstance () -> cacheObjectIDs ( \\array_unique ( \\array_column ( $this -> objects , 'personID' ))); } } Listing and Deleting Person Information # The person.tpl template has been updated to include a block for listing the information at the beginning: templates/person.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 { capture assign = 'pageTitle' }{ $person } - { lang } wcf.person.list { /lang }{ /capture } { capture assign = 'contentTitle' }{ $person }{ /capture } { include file = 'header' } { if $person -> informationCount || $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } <section class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> { lang } wcf.person.information.list { /lang } { if $person -> informationCount } <span class=\"badge\"> { # $person -> informationCount } </span> { /if } </h2> </header> <ul class=\"commentList containerList personInformationList jsObjectActionContainer\" { * * } data-object-action-class-name=\"wcf\\data\\person\\information\\PersonInformationAction\" { * * } > { if $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } <li class=\"containerListButtonGroup\"> <ul class=\"buttonGroup\"> <li> <a href=\"#\" class=\"button\" id=\"personInformationAddButton\"> <span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.person.information.add { /lang } </span> </a> </li> </ul> </li> { /if } { foreach from = $person -> getInformation () item = $information } <li class=\"comment personInformation jsObjectActionObject\" data-object-id=\" { @ $information -> getObjectID () } \"> <div class=\"box48 { if $__wcf -> getUserProfileHandler ()-> isIgnoredUser ( $information -> userID , 2 ) } ignoredUserContent { /if } \"> { user object = $information -> getUserProfile () type = 'avatar48' ariaHidden = 'true' tabindex = '-1' } <div class=\"commentContentContainer\"> <div class=\"commentContent\"> <div class=\"containerHeadline\"> <h3> { if $information -> userID } { user object = $information -> getUserProfile () } { else } <span> { $information -> username } </span> { /if } <small class=\"separatorLeft\"> { @ $information -> time | time } </small> </h3> </div> <div class=\"htmlContent userMessage\" id=\"personInformation { @ $information -> getObjectID () } \"> { @ $information -> getFormattedInformation () } </div> <nav class=\"jsMobileNavigation buttonGroupNavigation\"> <ul class=\"buttonList iconList\"> { if $information -> canEdit () } <li class=\"jsOnly\"> <a href=\"#\" title=\" { lang } wcf.global.button.edit { /lang } \" class=\"jsEditInformation jsTooltip\"> <span class=\"icon icon16 fa-pencil\"></span> <span class=\"invisible\"> { lang } wcf.global.button.edit { /lang } </span> </a> </li> { /if } { if $information -> canDelete () } <li class=\"jsOnly\"> <a href=\"#\" title=\" { lang } wcf.global.button.delete { /lang } \" class=\"jsObjectAction jsTooltip\" data-object-action=\"delete\" data-confirm-message=\" { lang } wcf.person.information.delete.confirmMessage { /lang } \"> <span class=\"icon icon16 fa-times\"></span> <span class=\"invisible\"> { lang } wcf.global.button.edit { /lang } </span> </a> </li> { /if } { event name = 'informationOptions' } </ul> </nav> </div> </div> </div> </li> { /foreach } </ul> </section> { /if } { if $person -> enableComments } { if $commentList | count || $commentCanAdd } <section id=\"comments\" class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> { lang } wcf.person.comments { /lang } { if $person -> comments } <span class=\"badge\"> { # $person -> comments } </span> { /if } </h2> </header> { include file = '__commentJavaScript' commentContainerID = 'personCommentList' } <div class=\"personComments\"> <ul id=\"personCommentList\" class=\"commentList containerList\" { * * } data-can-add=\" { if $commentCanAdd } true { else } false { /if } \" { * * } data-object-id=\" { @ $person -> personID } \" { * * } data-object-type-id=\" { @ $commentObjectTypeID } \" { * * } data-comments=\" { if $person -> comments }{ @ $commentList -> countObjects () }{ else } 0 { /if } \" { * * } data-last-comment-time=\" { @ $lastCommentTime } \" { * * } > { include file = 'commentListAddComment' wysiwygSelector = 'personCommentListAddComment' } { include file = 'commentList' } </ul> </div> </section> { /if } { /if } <footer class=\"contentFooter\"> { hascontent } <nav class=\"contentFooterNavigation\"> <ul> { content }{ event name = 'contentFooterNavigation' }{ /content } </ul> </nav> { /hascontent } </footer> <script data-relocate=\"true\"> require(['Language', 'WoltLabSuite/Core/Controller/Person'], (Language, ControllerPerson) => { Language . addObject ( { 'wcf.person.information.add' : '{jslang}wcf.person.information.add{/jslang}' , 'wcf.person.information.add.success' : '{jslang}wcf.person.information.add.success{/jslang}' , 'wcf.person.information.edit' : '{jslang}wcf.person.information.edit{/jslang}' , 'wcf.person.information.edit.success' : '{jslang}wcf.person.information.edit.success{/jslang}' , } ); ControllerPerson . init ( { @ $person -> personID } , { canAddInformation : { if $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } true { else } false { / if } , } ); } ); </script> { include file = 'footer' } To keep things simple here, we reuse the structure and CSS classes used for comments. Additionally, we always list all pieces of information. If there are many pieces of information, a nicer solution would be a pagination or loading more pieces of information with JavaScript. First, we note the jsObjectActionContainer class in combination with the data-object-action-class-name attribute, which are needed for the delete button for each piece of information, as explained here . In PersonInformationAction , we have overridden the default implementations of validateDelete() and delete() which are called after clicking on a delete button. In validateDelete() , we call PersonInformation::canDelete() on all pieces of information to be deleted for proper permission validation, and in delete() , we update the informationCount values of the people the deleted pieces of information belong to (see below). The button to add a new piece of information, #personInformationAddButton , and the buttons to edit existing pieces of information, .jsEditInformation , are controlled with JavaScript code initialized at the very end of the template. Lastly, in create() we provide default values for the time , userID , username , and ipAddress for cases like here when creating a new piece of information, where do not explicitly provide this data. Additionally, we extract the information text from the information_htmlInputProcessor parameter provided by the associated WYSIWYG form field and update the number of pieces of information created for the relevant person. Creating and Editing Person Information # To create new pieces of information or editing existing ones, we do not add new form controllers but instead use dialogs generated by the form builder API so that the user does not have to leave the person page. When clicking on the add button or on any of the edit buttons, a dialog opens with the relevant form: ts/WoltLabSuite/Core/Controller/Person.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 /** * Provides the JavaScript code for the person page. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @module WoltLabSuite/Core/Controller/Person */ import FormBuilderDialog from \"WoltLabSuite/Core/Form/Builder/Dialog\" ; import * as Language from \"WoltLabSuite/Core/Language\" ; import * as UiNotification from \"WoltLabSuite/Core/Ui/Notification\" ; let addDialog : FormBuilderDialog ; const editDialogs = new Map < string , FormBuilderDialog > (); interface EditReturnValues { formattedInformation : string ; informationID : number ; } interface Options { canAddInformation : true ; } /** * Opens the edit dialog after clicking on the edit button for a piece of information. */ function editInformation ( event : Event ) : void { event . preventDefault (); const currentTarget = event . currentTarget as HTMLElement ; const information = currentTarget . closest ( \".jsObjectActionObject\" ) as HTMLElement ; const informationId = information . dataset . objectId ! ; if ( ! editDialogs . has ( informationId )) { editDialogs . set ( informationId , new FormBuilderDialog ( `personInformationEditDialog ${ informationId } ` , \"wcf\\\\data\\\\person\\\\information\\\\PersonInformationAction\" , \"getEditDialog\" , { actionParameters : { informationID : informationId , }, dialog : { title : Language.get ( \"wcf.person.information.edit\" ), }, submitActionName : \"submitEditDialog\" , successCallback ( returnValues : EditReturnValues ) { document . getElementById ( `personInformation ${ returnValues . informationID } ` ) ! . innerHTML = returnValues . formattedInformation ; UiNotification . show ( Language . get ( \"wcf.person.information.edit.success\" )); }, }, ), ); } editDialogs . get ( informationId ) ! . open (); } /** * Initializes the JavaScript code for the person page. */ export function init ( personId : number , options : Options ) : void { if ( options . canAddInformation ) { // Initialize the dialog to add new information. addDialog = new FormBuilderDialog ( \"personInformationAddDialog\" , \"wcf\\\\data\\\\person\\\\information\\\\PersonInformationAction\" , \"getAddDialog\" , { actionParameters : { personID : personId , }, dialog : { title : Language.get ( \"wcf.person.information.add\" ), }, submitActionName : \"submitAddDialog\" , successCallback () { UiNotification . show ( Language . get ( \"wcf.person.information.add.success\" ), () => window . location . reload ()); }, }, ); document . getElementById ( \"personInformationAddButton\" ) ! . addEventListener ( \"click\" , ( event ) => { event . preventDefault (); addDialog . open (); }); } document . querySelectorAll ( \".jsEditInformation\" ) . forEach (( el ) => el . addEventListener ( \"click\" , ( ev ) => editInformation ( ev ))); } We use the WoltLabSuite/Core/Form/Builder/Dialog module , which takes care of the internal handling with regard to these dialogs. We only have to provide some data during for initializing these objects and call the open() function after a button has been clicked. Explanation of the initialization arguments for WoltLabSuite/Core/Form/Builder/Dialog used here: The first argument is the id of the dialog used to identify it. The second argument is the PHP class name which provides the contents of the dialog's form and handles the data after the form is submitted. The third argument is the name of the method in the referenced PHP class in the previous argument that returns the dialog form. The fourth argument contains additional options: actionParameters are additional parameters send during each AJAX request. Here, we either pass the id of the person for who a new piece of information is added or the id of the edited piece of information. dialog contains the options for the dialog, see the DialogOptions interface. Here, we only provide the title of the dialog. submitActionName is the name of the method in the referenced PHP class that is called with the form data after submitting the form. successCallback is called after the submit AJAX request was successful. After adding a new piece of information, we reload the page, and after editing an existing piece of information, we update the existing information text with the updated text. (Dynamically inserting a newly added piece of information instead of reloading the page would also be possible, of course, but for this tutorial series, we kept things simple.) Next, we focus on PersonInformationAction , which actually provides the contents of these dialogs and creates and edits the information: files/lib/data/person/information/PersonInformationAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\AbstractDatabaseObjectAction ; use wcf\\data\\person\\PersonAction ; use wcf\\data\\person\\PersonEditor ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\event\\EventHandler ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\exception\\PermissionDeniedException ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\form\\builder\\container\\wysiwyg\\WysiwygFormContainer ; use wcf\\system\\form\\builder\\DialogFormDocument ; use wcf\\system\\html\\input\\HtmlInputProcessor ; use wcf\\system\\WCF ; use wcf\\util\\UserUtil ; /** * Executes person information-related actions. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person\\Information * * @method PersonInformationEditor[] getObjects() * @method PersonInformationEditor getSingleObject() */ class PersonInformationAction extends AbstractDatabaseObjectAction { /** * @var DialogFormDocument */ public $dialog ; /** * @var PersonInformation */ public $information ; /** * @return PersonInformation */ public function create () { if ( ! isset ( $this -> parameters [ 'data' ][ 'time' ])) { $this -> parameters [ 'data' ][ 'time' ] = TIME_NOW ; } if ( ! isset ( $this -> parameters [ 'data' ][ 'userID' ])) { $this -> parameters [ 'data' ][ 'userID' ] = WCF :: getUser () -> userID ; $this -> parameters [ 'data' ][ 'username' ] = WCF :: getUser () -> username ; } if ( LOG_IP_ADDRESS ) { if ( ! isset ( $this -> parameters [ 'data' ][ 'ipAddress' ])) { $this -> parameters [ 'data' ][ 'ipAddress' ] = UserUtil :: getIpAddress (); } } else { unset ( $this -> parameters [ 'data' ][ 'ipAddress' ]); } if ( ! empty ( $this -> parameters [ 'information_htmlInputProcessor' ])) { /** @var HtmlInputProcessor $htmlInputProcessor */ $htmlInputProcessor = $this -> parameters [ 'information_htmlInputProcessor' ]; $this -> parameters [ 'data' ][ 'information' ] = $htmlInputProcessor -> getHtml (); } /** @var PersonInformation $information */ $information = parent :: create (); ( new PersonAction ([ $information -> personID ], 'update' , [ 'counters' => [ 'informationCount' => 1 , ], ])) -> executeAction (); return $information ; } /** * @inheritDoc */ public function update () { if ( ! empty ( $this -> parameters [ 'information_htmlInputProcessor' ])) { /** @var HtmlInputProcessor $htmlInputProcessor */ $htmlInputProcessor = $this -> parameters [ 'information_htmlInputProcessor' ]; $this -> parameters [ 'data' ][ 'information' ] = $htmlInputProcessor -> getHtml (); } parent :: update (); } /** * @inheritDoc */ public function validateDelete () { if ( empty ( $this -> objects )) { $this -> readObjects (); if ( empty ( $this -> objects )) { throw new UserInputException ( 'objectIDs' ); } } foreach ( $this -> getObjects () as $informationEditor ) { if ( ! $informationEditor -> canDelete ()) { throw new PermissionDeniedException (); } } } /** * @inheritDoc */ public function delete () { $deleteCount = parent :: delete (); if ( ! $deleteCount ) { return $deleteCount ; } $counterUpdates = []; foreach ( $this -> getObjects () as $informationEditor ) { if ( ! isset ( $counterUpdates [ $informationEditor -> personID ])) { $counterUpdates [ $informationEditor -> personID ] = 0 ; } $counterUpdates [ $informationEditor -> personID ] -- ; } WCF :: getDB () -> beginTransaction (); foreach ( $counterUpdates as $personID => $counterUpdate ) { ( new PersonEditor ( PersonRuntimeCache :: getInstance () -> getObject ( $personID ))) -> updateCounters ([ 'informationCount' => $counterUpdate , ]); } WCF :: getDB () -> commitTransaction (); return $deleteCount ; } /** * Validates the `getAddDialog` action. */ public function validateGetAddDialog () : void { WCF :: getSession () -> checkPermissions ([ 'user.person.canAddInformation' ]); $this -> readInteger ( 'personID' ); if ( PersonRuntimeCache :: getInstance () -> getObject ( $this -> parameters [ 'personID' ]) === null ) { throw new UserInputException ( 'personID' ); } } /** * Returns the data to show the dialog to add a new piece of information on a person. * * @return string[] */ public function getAddDialog () : array { $this -> buildDialog (); return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } /** * Validates the `submitAddDialog` action. */ public function validateSubmitAddDialog () : void { $this -> validateGetAddDialog (); $this -> buildDialog (); $this -> dialog -> requestData ( $_POST [ 'parameters' ][ 'data' ] ?? []); $this -> dialog -> readValues (); $this -> dialog -> validate (); } /** * Creates a new piece of information on a person after submitting the dialog. * * @return string[] */ public function submitAddDialog () : array { // If there are any validation errors, show the form again. if ( $this -> dialog -> hasValidationErrors ()) { return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } ( new static ([], 'create' , \\array_merge ( $this -> dialog -> getData (), [ 'data' => [ 'personID' => $this -> parameters [ 'personID' ], ], ]))) -> executeAction (); return []; } /** * Validates the `getEditDialog` action. */ public function validateGetEditDialog () : void { WCF :: getSession () -> checkPermissions ([ 'user.person.canAddInformation' ]); $this -> readInteger ( 'informationID' ); $this -> information = new PersonInformation ( $this -> parameters [ 'informationID' ]); if ( ! $this -> information -> getObjectID ()) { throw new UserInputException ( 'informationID' ); } if ( ! $this -> information -> canEdit ()) { throw new IllegalLinkException (); } } /** * Returns the data to show the dialog to edit a piece of information on a person. * * @return string[] */ public function getEditDialog () : array { $this -> buildDialog (); $this -> dialog -> updatedObject ( $this -> information ); return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } /** * Validates the `submitEditDialog` action. */ public function validateSubmitEditDialog () : void { $this -> validateGetEditDialog (); $this -> buildDialog (); $this -> dialog -> updatedObject ( $this -> information , false ); $this -> dialog -> requestData ( $_POST [ 'parameters' ][ 'data' ] ?? []); $this -> dialog -> readValues (); $this -> dialog -> validate (); } /** * Updates a piece of information on a person after submitting the edit dialog. * * @return string[] */ public function submitEditDialog () : array { // If there are any validation errors, show the form again. if ( $this -> dialog -> hasValidationErrors ()) { return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } ( new static ([ $this -> information ], 'update' , $this -> dialog -> getData ())) -> executeAction (); // Reload the information with the updated data. $information = new PersonInformation ( $this -> information -> getObjectID ()); return [ 'formattedInformation' => $information -> getFormattedInformation (), 'informationID' => $this -> information -> getObjectID (), ]; } /** * Builds the dialog to create or edit person information. */ protected function buildDialog () : void { if ( $this -> dialog !== null ) { return ; } $this -> dialog = DialogFormDocument :: create ( 'personInformationAddDialog' ) -> appendChild ( WysiwygFormContainer :: create ( 'information' ) -> messageObjectType ( 'com.woltlab.wcf.people.information' ) -> required () ); EventHandler :: getInstance () -> fireAction ( $this , 'buildDialog' ); $this -> dialog -> build (); } } When setting up the WoltLabSuite/Core/Form/Builder/Dialog object for adding new pieces of information, we specified getAddDialog and submitAddDialog as the names of the dialog getter and submit handler. In addition to these two methods, the matching validation methods validateGetAddDialog() and validateGetAddDialog() are also added. As the forms for adding and editing pieces of information have the same structure, this form is created in buildDialog() using a DialogFormDocument object, which is intended for forms in dialogs. We fire an event in buildDialog() so that plugins are able to easily extend the dialog with additional data. validateGetAddDialog() checks if the user has the permission to create new pieces of information and if a valid id for the person, the information will belong to, is given. The method configured in the WoltLabSuite/Core/Form/Builder/Dialog object returning the dialog is expected to return two values: the id of the form ( formId ) and the contents of form shown in the dialog ( dialog ). This data is returned by getAddDialog using the dialog build previously by buildDialog() . After the form is submitted, validateSubmitAddDialog() has to do the same basic validation as validateGetAddDialog() so that validateGetAddDialog() is simply called. Additionally, the form data is read and validated. In submitAddDialog() , we first check if there have been any validation errors: If any error occured during validation, we return the same data as in getAddDialog() so that the dialog is shown again with the erroneous fields marked as such. Otherwise, if the validation succeeded, the form data is used to create the new piece of information. In addition to the form data, we manually add the id of the person to whom the information belongs to. Lastly, we could return some data that we could access in the JavaScript callback function after successfully submitting the dialog. As we will simply be reloading the page, no such data is returned. An alternative to reloading to the page would be dynamically inserting the new piece of information in the list so that we would have to return the rendered list item for the new piece of information. The process for getting and submitting the dialog to edit existing pieces of information is similar to the process for adding new pieces of information. Instead of the id of the person, however, we now pass the id of the edited piece of information and in submitEditDialog() , we update the edited information instead of creating a new one like in submitAddDialog() . After editing a piece of information, we do not reload the page but dynamically update the text of the information in the TypeScript code so that we return the updated rendered information text and id of the edited pieced of information in submitAddDialog() . Rebuild Data Worker # To ensure the integrity of the person data, PersonRebuildDataWorker updates the informationCount counter: files/lib/system/worker/PersonRebuildDataWorker.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 <? php namespace wcf\\system\\worker ; use wcf\\data\\person\\PersonList ; use wcf\\system\\WCF ; /** * Worker implementation for updating people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Worker * * @method PersonList getObjectList() */ class PersonRebuildDataWorker extends AbstractRebuildDataWorker { /** * @inheritDoc */ protected $limit = 500 ; /** * @inheritDoc */ protected $objectListClassName = PersonList :: class ; /** * @inheritDoc */ protected function initObjectList () { parent :: initObjectList (); $this -> objectList -> sqlOrderBy = 'person.personID' ; } /** * @inheritDoc */ public function execute () { parent :: execute (); if ( ! \\count ( $this -> objectList )) { return ; } $sql = \"UPDATE wcf\" . WCF_N . \"_person person SET informationCount = ( SELECT COUNT(*) FROM wcf\" . WCF_N . \"_person_information person_information WHERE person_information.personID = person.personID ) WHERE person.personID = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); WCF :: getDB () -> beginTransaction (); foreach ( $this -> getObjectList () as $person ) { $statement -> execute ([ $person -> personID ]); } WCF :: getDB () -> commitTransaction (); } } Username and IP Address Event Listeners # As we store the name of the user who create a new piece of information and store their IP address, we have to add event listeners to properly handle the following scenarios: If the user is renamed, the value of username stored with the person information has to be updated, which can be achieved by a simple event listener that only has to specify the name of relevant database table if AbstractUserActionRenameListener is extended: files/lib/system/event/listener/PersonUserActionRenameListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; /** * Updates person information during user renaming. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserActionRenameListener extends AbstractUserActionRenameListener { /** * @inheritDoc */ protected $databaseTables = [ 'wcf{WCF_N}_person_information' , ]; } If users are merged, all pieces of information need to be assigned to the target user of the merging. Again, we only have to specify the name of relevant database table if AbstractUserMergeListener is extended: files/lib/system/event/listener/PersonUserMergeListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; /** * Updates person information during user merging. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserMergeListener extends AbstractUserMergeListener { /** * @inheritDoc */ protected $databaseTables = [ 'wcf{WCF_N}_person_information' , ]; } If the option to prune stored ip addresses after a certain period of time is enabled, we also have to prune them in the person information database table. Here we also only have to specify the name of the relevant database table and provide the mapping from the ipAddress column to the time column: files/lib/system/event/listener/PersonPruneIpAddressesCronjobListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\cronjob\\PruneIpAddressesCronjob ; /** * Prunes old ip addresses. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonPruneIpAddressesCronjobListener extends AbstractEventListener { protected function onExecute ( PruneIpAddressesCronjob $cronjob ) : void { $cronjob -> columns [ 'wcf' . WCF_N . '_person_information' ][ 'ipAddress' ] = 'time' ; } } The ip addresses in the person information database table also have to be considered for the user data export which can also be done with minimal effort by providing the name of the relevant database table: files/lib/system/event/listener/PersonUserExportGdprListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\action\\UserExportGdprAction ; /** * Adds the ip addresses stored with the person information during user data export. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserExportGdprListener extends AbstractEventListener { protected function onExport ( UserExportGdprAction $action ) : void { $action -> ipAddresses [ 'com.woltlab.wcf.people' ] = [ 'wcf' . WCF_N . '_person_information' ]; } } Lastly, we present the updated eventListener.xml file with new entries for all of these event listeners: eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd\" > <import> <eventlistener name= \"rename@wcf\\data\\user\\UserAction\" > <eventclassname> wcf\\data\\user\\UserAction </eventclassname> <eventname> rename </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserActionRenameListener </listenerclassname> <environment> all </environment> </eventlistener> <eventlistener name= \"save@wcf\\acp\\form\\UserMergeForm\" > <eventclassname> wcf\\acp\\form\\UserMergeForm </eventclassname> <eventname> save </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserMergeListener </listenerclassname> <environment> admin </environment> </eventlistener> <eventlistener name= \"execute@wcf\\system\\cronjob\\PruneIpAddressesCronjob\" > <eventclassname> wcf\\system\\cronjob\\PruneIpAddressesCronjob </eventclassname> <eventname> execute </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonPruneIpAddressesCronjobListener </listenerclassname> <environment> all </environment> </eventlistener> <eventlistener name= \"export@wcf\\acp\\action\\UserExportGdprAction\" > <eventclassname> wcf\\acp\\action\\UserExportGdprAction </eventclassname> <eventname> export </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserExportGdprListener </listenerclassname> <environment> admin </environment> </eventlistener> </import> </data>","title":"Part 5"},{"location":"tutorial/series/part_5/#part-5-person-information","text":"This part of our tutorial series lays the foundation for future parts in which we will be using additional APIs, which we have not used in this series yet. To make use of those APIs, we need content generated by users in the frontend.","title":"Part 5: Person Information"},{"location":"tutorial/series/part_5/#package-functionality","text":"In addition to the existing functions from part 4 , the package will provide the following functionality after this part of the tutorial: Users are able to add information on the people in the frontend. Users are able to edit and delete the pieces of information they added. Moderators are able to edit and delete all pieces of information.","title":"Package Functionality"},{"location":"tutorial/series/part_5/#used-components","text":"In addition to the components used in previous parts, we will use the form builder API to create forms shown in dialogs instead of dedicated pages and we will, for the first time, add TypeScript code .","title":"Used Components"},{"location":"tutorial/series/part_5/#package-structure","text":"The package will have the following file structure excluding unchanged files from previous parts: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 \u251c\u2500\u2500 files \u2502 \u251c\u2500\u2500 acp \u2502 \u2502 \u2514\u2500\u2500 database \u2502 \u2502 \u2514\u2500\u2500 install_com.woltlab.wcf.people.php \u2502 \u251c\u2500\u2500 js \u2502 \u2502 \u2514\u2500\u2500 WoltLabSuite \u2502 \u2502 \u2514\u2500\u2500 Core \u2502 \u2502 \u2514\u2500\u2500 Controller \u2502 \u2502 \u2514\u2500\u2500 Person.js \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 Person.class.php \u2502 \u2502 \u2514\u2500\u2500 information \u2502 \u2502 \u251c\u2500\u2500 PersonInformation.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonInformationAction.class.php \u2502 \u2502 \u251c\u2500\u2500 PersonInformationEditor.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonInformationList.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u2514\u2500\u2500 worker \u2502 \u2514\u2500\u2500 PersonRebuildDataWorker.class.php \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u251c\u2500\u2500 objectType.xml \u251c\u2500\u2500 templates \u2502 \u251c\u2500\u2500 person.tpl \u2502 \u2514\u2500\u2500 personList.tpl \u251c\u2500\u2500 ts \u2502 \u2514\u2500\u2500 WoltLabSuite \u2502 \u2514\u2500\u2500 Core \u2502 \u2514\u2500\u2500 Controller \u2502 \u2514\u2500\u2500 Person.ts \u2514\u2500\u2500 userGroupOption.xml For all changes, please refer to the source code on GitHub .","title":"Package Structure"},{"location":"tutorial/series/part_5/#miscellaneous","text":"Before we focus on the main aspects of this part, we mention some minor aspects that will be used later on: Several new user group options and the relevant language items have been added related to creating, editing, and deleting information: mod.person.canEditInformation and mod.person.canDeleteInformation are moderative permissions to edit and delete any piece of information, regardless of who created it. user.person.canAddInformation is the permission for users to add new pieces of information. user.person.canEditInformation and user.person.canDeleteInformation are the user permissions to edit and the piece of information they created. The actual information text will be entered via a WYSIWYG editor, which requires an object type of the definition com.woltlab.wcf.message : com.woltlab.wcf.people.information . personList.tpl has been adjusted to show the number of pieces of information in the person statistics section. We have not updated the person list box to also support sorting by the number of pieces of information added for each person.","title":"Miscellaneous"},{"location":"tutorial/series/part_5/#person-information-model","text":"The PHP file with the database layout has been updated as follows: files/acp/database/install_com.woltlab.wcf.people.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 <? php use wcf\\system\\database\\table\\column\\DefaultTrueBooleanDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\IntDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\NotNullInt10DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\NotNullVarchar255DatabaseTableColumn ; use wcf\\system\\database\\table\\column\\ObjectIdDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\SmallintDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\TextDatabaseTableColumn ; use wcf\\system\\database\\table\\column\\VarcharDatabaseTableColumn ; use wcf\\system\\database\\table\\DatabaseTable ; use wcf\\system\\database\\table\\index\\DatabaseTableForeignKey ; use wcf\\system\\database\\table\\index\\DatabaseTablePrimaryIndex ; return [ DatabaseTable :: create ( 'wcf1_person' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'personID' ), NotNullVarchar255DatabaseTableColumn :: create ( 'firstName' ), NotNullVarchar255DatabaseTableColumn :: create ( 'lastName' ), NotNullInt10DatabaseTableColumn :: create ( 'informationCount' ) -> defaultValue ( 0 ), SmallintDatabaseTableColumn :: create ( 'comments' ) -> length ( 5 ) -> notNull () -> defaultValue ( 0 ), DefaultTrueBooleanDatabaseTableColumn :: create ( 'enableComments' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'personID' ]), ]), DatabaseTable :: create ( 'wcf1_person_information' ) -> columns ([ ObjectIdDatabaseTableColumn :: create ( 'informationID' ), NotNullInt10DatabaseTableColumn :: create ( 'personID' ), TextDatabaseTableColumn :: create ( 'information' ), IntDatabaseTableColumn :: create ( 'userID' ) -> length ( 10 ), NotNullVarchar255DatabaseTableColumn :: create ( 'username' ), VarcharDatabaseTableColumn :: create ( 'ipAddress' ) -> length ( 39 ) -> notNull ( true ) -> defaultValue ( '' ), NotNullInt10DatabaseTableColumn :: create ( 'time' ), ]) -> indices ([ DatabaseTablePrimaryIndex :: create () -> columns ([ 'informationID' ]), ]) -> foreignKeys ([ DatabaseTableForeignKey :: create () -> columns ([ 'personID' ]) -> referencedTable ( 'wcf1_person' ) -> referencedColumns ([ 'personID' ]) -> onDelete ( 'CASCADE' ), DatabaseTableForeignKey :: create () -> columns ([ 'userID' ]) -> referencedTable ( 'wcf1_user' ) -> referencedColumns ([ 'userID' ]) -> onDelete ( 'SET NULL' ), ]), ]; The number of pieces of information per person is tracked via the new informationCount column. The wcf1_person_information table has been added for the PersonInformation model. The meaning of the different columns is explained in the property documentation part of PersonInformation 's documentation (see below). The two foreign keys ensure that if a person is deleted, all of their information is also deleted, and that if a user is deleted, the userID column is set to NULL . files/lib/data/person/information/PersonInformation.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\DatabaseObject ; use wcf\\data\\person\\Person ; use wcf\\data\\user\\UserProfile ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\cache\\runtime\\UserProfileRuntimeCache ; use wcf\\system\\html\\output\\HtmlOutputProcessor ; use wcf\\system\\WCF ; /** * Represents a piece of information for a person. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person\\Information * * @property-read int $informationID unique id of the information * @property-read int $personID id of the person the information belongs to * @property-read string $information information text * @property-read int|null $userID id of the user who added the information or `null` if the user no longer exists * @property-read string $username name of the user who added the information * @property-read int $time timestamp at which the information was created */ class PersonInformation extends DatabaseObject { /** * Returns `true` if the active user can delete this piece of information and `false` otherwise. */ public function canDelete () : bool { if ( WCF :: getUser () -> userID && WCF :: getUser () -> userID == $this -> userID && WCF :: getSession () -> getPermission ( 'user.person.canDeleteInformation' ) ) { return true ; } return WCF :: getSession () -> getPermission ( 'mod.person.canDeleteInformation' ); } /** * Returns `true` if the active user can edit this piece of information and `false` otherwise. */ public function canEdit () : bool { if ( WCF :: getUser () -> userID && WCF :: getUser () -> userID == $this -> userID && WCF :: getSession () -> getPermission ( 'user.person.canEditInformation' ) ) { return true ; } return WCF :: getSession () -> getPermission ( 'mod.person.canEditInformation' ); } /** * Returns the formatted information. */ public function getFormattedInformation () : string { $processor = new HtmlOutputProcessor (); $processor -> process ( $this -> information , 'com.woltlab.wcf.people.information' , $this -> informationID ); return $processor -> getHtml (); } /** * Returns the person the information belongs to. */ public function getPerson () : Person { return PersonRuntimeCache :: getInstance () -> getObject ( $this -> personID ); } /** * Returns the user profile of the user who added the information. */ public function getUserProfile () : UserProfile { if ( $this -> userID ) { return UserProfileRuntimeCache :: getInstance () -> getObject ( $this -> userID ); } else { return UserProfile :: getGuestUserProfile ( $this -> username ); } } } PersonInformation provides two methods, canDelete() and canEdit() , to check whether the active user can delete or edit a specific piece of information. In both cases, it is checked if the current user has created the relevant piece of information to check the user-specific permissions or to fall back to the moderator-specific permissions. There also two getter methods for the person, the piece of information belongs to ( getPerson() ), and for the user profile of the user who created the information ( getUserProfile() ). In both cases, we use runtime caches, though in getUserProfile() , we also have to consider the case of the user who created the information being deleted, i.e. userID being null . For such a case, we also save the name of the user who created the information in username , so that we can return a guest user profile object in this case. The most interesting method is getFormattedInformation() , which returns the HTML code of the information text meant for output. To generate such an output, HtmlOutputProcessor::process() is used and here is where we first use the associated message object type com.woltlab.wcf.people.information mentioned before . While PersonInformationEditor is simply the default implementation and thus not explicitly shown here, PersonInformationList::readObjects() caches the relevant ids of the associated people and users who created the pieces of information using runtime caches: files/lib/data/person/information/PersonInformationList.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\DatabaseObjectList ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\cache\\runtime\\UserProfileRuntimeCache ; /** * Represents a list of person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\PersonInformation * * @method PersonInformation current() * @method PersonInformation[] getObjects() * @method PersonInformation|null search($objectID) * @property PersonInformation[] $objects */ class PersonInformationList extends DatabaseObjectList { public function readObjects () { parent :: readObjects (); UserProfileRuntimeCache :: getInstance () -> cacheObjectIDs ( \\array_unique ( \\array_filter ( \\array_column ( $this -> objects , 'userID' )))); PersonRuntimeCache :: getInstance () -> cacheObjectIDs ( \\array_unique ( \\array_column ( $this -> objects , 'personID' ))); } }","title":"Person Information Model"},{"location":"tutorial/series/part_5/#listing-and-deleting-person-information","text":"The person.tpl template has been updated to include a block for listing the information at the beginning: templates/person.tpl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 { capture assign = 'pageTitle' }{ $person } - { lang } wcf.person.list { /lang }{ /capture } { capture assign = 'contentTitle' }{ $person }{ /capture } { include file = 'header' } { if $person -> informationCount || $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } <section class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> { lang } wcf.person.information.list { /lang } { if $person -> informationCount } <span class=\"badge\"> { # $person -> informationCount } </span> { /if } </h2> </header> <ul class=\"commentList containerList personInformationList jsObjectActionContainer\" { * * } data-object-action-class-name=\"wcf\\data\\person\\information\\PersonInformationAction\" { * * } > { if $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } <li class=\"containerListButtonGroup\"> <ul class=\"buttonGroup\"> <li> <a href=\"#\" class=\"button\" id=\"personInformationAddButton\"> <span class=\"icon icon16 fa-plus\"></span> <span> { lang } wcf.person.information.add { /lang } </span> </a> </li> </ul> </li> { /if } { foreach from = $person -> getInformation () item = $information } <li class=\"comment personInformation jsObjectActionObject\" data-object-id=\" { @ $information -> getObjectID () } \"> <div class=\"box48 { if $__wcf -> getUserProfileHandler ()-> isIgnoredUser ( $information -> userID , 2 ) } ignoredUserContent { /if } \"> { user object = $information -> getUserProfile () type = 'avatar48' ariaHidden = 'true' tabindex = '-1' } <div class=\"commentContentContainer\"> <div class=\"commentContent\"> <div class=\"containerHeadline\"> <h3> { if $information -> userID } { user object = $information -> getUserProfile () } { else } <span> { $information -> username } </span> { /if } <small class=\"separatorLeft\"> { @ $information -> time | time } </small> </h3> </div> <div class=\"htmlContent userMessage\" id=\"personInformation { @ $information -> getObjectID () } \"> { @ $information -> getFormattedInformation () } </div> <nav class=\"jsMobileNavigation buttonGroupNavigation\"> <ul class=\"buttonList iconList\"> { if $information -> canEdit () } <li class=\"jsOnly\"> <a href=\"#\" title=\" { lang } wcf.global.button.edit { /lang } \" class=\"jsEditInformation jsTooltip\"> <span class=\"icon icon16 fa-pencil\"></span> <span class=\"invisible\"> { lang } wcf.global.button.edit { /lang } </span> </a> </li> { /if } { if $information -> canDelete () } <li class=\"jsOnly\"> <a href=\"#\" title=\" { lang } wcf.global.button.delete { /lang } \" class=\"jsObjectAction jsTooltip\" data-object-action=\"delete\" data-confirm-message=\" { lang } wcf.person.information.delete.confirmMessage { /lang } \"> <span class=\"icon icon16 fa-times\"></span> <span class=\"invisible\"> { lang } wcf.global.button.edit { /lang } </span> </a> </li> { /if } { event name = 'informationOptions' } </ul> </nav> </div> </div> </div> </li> { /foreach } </ul> </section> { /if } { if $person -> enableComments } { if $commentList | count || $commentCanAdd } <section id=\"comments\" class=\"section sectionContainerList\"> <header class=\"sectionHeader\"> <h2 class=\"sectionTitle\"> { lang } wcf.person.comments { /lang } { if $person -> comments } <span class=\"badge\"> { # $person -> comments } </span> { /if } </h2> </header> { include file = '__commentJavaScript' commentContainerID = 'personCommentList' } <div class=\"personComments\"> <ul id=\"personCommentList\" class=\"commentList containerList\" { * * } data-can-add=\" { if $commentCanAdd } true { else } false { /if } \" { * * } data-object-id=\" { @ $person -> personID } \" { * * } data-object-type-id=\" { @ $commentObjectTypeID } \" { * * } data-comments=\" { if $person -> comments }{ @ $commentList -> countObjects () }{ else } 0 { /if } \" { * * } data-last-comment-time=\" { @ $lastCommentTime } \" { * * } > { include file = 'commentListAddComment' wysiwygSelector = 'personCommentListAddComment' } { include file = 'commentList' } </ul> </div> </section> { /if } { /if } <footer class=\"contentFooter\"> { hascontent } <nav class=\"contentFooterNavigation\"> <ul> { content }{ event name = 'contentFooterNavigation' }{ /content } </ul> </nav> { /hascontent } </footer> <script data-relocate=\"true\"> require(['Language', 'WoltLabSuite/Core/Controller/Person'], (Language, ControllerPerson) => { Language . addObject ( { 'wcf.person.information.add' : '{jslang}wcf.person.information.add{/jslang}' , 'wcf.person.information.add.success' : '{jslang}wcf.person.information.add.success{/jslang}' , 'wcf.person.information.edit' : '{jslang}wcf.person.information.edit{/jslang}' , 'wcf.person.information.edit.success' : '{jslang}wcf.person.information.edit.success{/jslang}' , } ); ControllerPerson . init ( { @ $person -> personID } , { canAddInformation : { if $__wcf -> session -> getPermission ( 'user.person.canAddInformation' ) } true { else } false { / if } , } ); } ); </script> { include file = 'footer' } To keep things simple here, we reuse the structure and CSS classes used for comments. Additionally, we always list all pieces of information. If there are many pieces of information, a nicer solution would be a pagination or loading more pieces of information with JavaScript. First, we note the jsObjectActionContainer class in combination with the data-object-action-class-name attribute, which are needed for the delete button for each piece of information, as explained here . In PersonInformationAction , we have overridden the default implementations of validateDelete() and delete() which are called after clicking on a delete button. In validateDelete() , we call PersonInformation::canDelete() on all pieces of information to be deleted for proper permission validation, and in delete() , we update the informationCount values of the people the deleted pieces of information belong to (see below). The button to add a new piece of information, #personInformationAddButton , and the buttons to edit existing pieces of information, .jsEditInformation , are controlled with JavaScript code initialized at the very end of the template. Lastly, in create() we provide default values for the time , userID , username , and ipAddress for cases like here when creating a new piece of information, where do not explicitly provide this data. Additionally, we extract the information text from the information_htmlInputProcessor parameter provided by the associated WYSIWYG form field and update the number of pieces of information created for the relevant person.","title":"Listing and Deleting Person Information"},{"location":"tutorial/series/part_5/#creating-and-editing-person-information","text":"To create new pieces of information or editing existing ones, we do not add new form controllers but instead use dialogs generated by the form builder API so that the user does not have to leave the person page. When clicking on the add button or on any of the edit buttons, a dialog opens with the relevant form: ts/WoltLabSuite/Core/Controller/Person.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 /** * Provides the JavaScript code for the person page. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @module WoltLabSuite/Core/Controller/Person */ import FormBuilderDialog from \"WoltLabSuite/Core/Form/Builder/Dialog\" ; import * as Language from \"WoltLabSuite/Core/Language\" ; import * as UiNotification from \"WoltLabSuite/Core/Ui/Notification\" ; let addDialog : FormBuilderDialog ; const editDialogs = new Map < string , FormBuilderDialog > (); interface EditReturnValues { formattedInformation : string ; informationID : number ; } interface Options { canAddInformation : true ; } /** * Opens the edit dialog after clicking on the edit button for a piece of information. */ function editInformation ( event : Event ) : void { event . preventDefault (); const currentTarget = event . currentTarget as HTMLElement ; const information = currentTarget . closest ( \".jsObjectActionObject\" ) as HTMLElement ; const informationId = information . dataset . objectId ! ; if ( ! editDialogs . has ( informationId )) { editDialogs . set ( informationId , new FormBuilderDialog ( `personInformationEditDialog ${ informationId } ` , \"wcf\\\\data\\\\person\\\\information\\\\PersonInformationAction\" , \"getEditDialog\" , { actionParameters : { informationID : informationId , }, dialog : { title : Language.get ( \"wcf.person.information.edit\" ), }, submitActionName : \"submitEditDialog\" , successCallback ( returnValues : EditReturnValues ) { document . getElementById ( `personInformation ${ returnValues . informationID } ` ) ! . innerHTML = returnValues . formattedInformation ; UiNotification . show ( Language . get ( \"wcf.person.information.edit.success\" )); }, }, ), ); } editDialogs . get ( informationId ) ! . open (); } /** * Initializes the JavaScript code for the person page. */ export function init ( personId : number , options : Options ) : void { if ( options . canAddInformation ) { // Initialize the dialog to add new information. addDialog = new FormBuilderDialog ( \"personInformationAddDialog\" , \"wcf\\\\data\\\\person\\\\information\\\\PersonInformationAction\" , \"getAddDialog\" , { actionParameters : { personID : personId , }, dialog : { title : Language.get ( \"wcf.person.information.add\" ), }, submitActionName : \"submitAddDialog\" , successCallback () { UiNotification . show ( Language . get ( \"wcf.person.information.add.success\" ), () => window . location . reload ()); }, }, ); document . getElementById ( \"personInformationAddButton\" ) ! . addEventListener ( \"click\" , ( event ) => { event . preventDefault (); addDialog . open (); }); } document . querySelectorAll ( \".jsEditInformation\" ) . forEach (( el ) => el . addEventListener ( \"click\" , ( ev ) => editInformation ( ev ))); } We use the WoltLabSuite/Core/Form/Builder/Dialog module , which takes care of the internal handling with regard to these dialogs. We only have to provide some data during for initializing these objects and call the open() function after a button has been clicked. Explanation of the initialization arguments for WoltLabSuite/Core/Form/Builder/Dialog used here: The first argument is the id of the dialog used to identify it. The second argument is the PHP class name which provides the contents of the dialog's form and handles the data after the form is submitted. The third argument is the name of the method in the referenced PHP class in the previous argument that returns the dialog form. The fourth argument contains additional options: actionParameters are additional parameters send during each AJAX request. Here, we either pass the id of the person for who a new piece of information is added or the id of the edited piece of information. dialog contains the options for the dialog, see the DialogOptions interface. Here, we only provide the title of the dialog. submitActionName is the name of the method in the referenced PHP class that is called with the form data after submitting the form. successCallback is called after the submit AJAX request was successful. After adding a new piece of information, we reload the page, and after editing an existing piece of information, we update the existing information text with the updated text. (Dynamically inserting a newly added piece of information instead of reloading the page would also be possible, of course, but for this tutorial series, we kept things simple.) Next, we focus on PersonInformationAction , which actually provides the contents of these dialogs and creates and edits the information: files/lib/data/person/information/PersonInformationAction.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 <? php namespace wcf\\data\\person\\information ; use wcf\\data\\AbstractDatabaseObjectAction ; use wcf\\data\\person\\PersonAction ; use wcf\\data\\person\\PersonEditor ; use wcf\\system\\cache\\runtime\\PersonRuntimeCache ; use wcf\\system\\event\\EventHandler ; use wcf\\system\\exception\\IllegalLinkException ; use wcf\\system\\exception\\PermissionDeniedException ; use wcf\\system\\exception\\UserInputException ; use wcf\\system\\form\\builder\\container\\wysiwyg\\WysiwygFormContainer ; use wcf\\system\\form\\builder\\DialogFormDocument ; use wcf\\system\\html\\input\\HtmlInputProcessor ; use wcf\\system\\WCF ; use wcf\\util\\UserUtil ; /** * Executes person information-related actions. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\Data\\Person\\Information * * @method PersonInformationEditor[] getObjects() * @method PersonInformationEditor getSingleObject() */ class PersonInformationAction extends AbstractDatabaseObjectAction { /** * @var DialogFormDocument */ public $dialog ; /** * @var PersonInformation */ public $information ; /** * @return PersonInformation */ public function create () { if ( ! isset ( $this -> parameters [ 'data' ][ 'time' ])) { $this -> parameters [ 'data' ][ 'time' ] = TIME_NOW ; } if ( ! isset ( $this -> parameters [ 'data' ][ 'userID' ])) { $this -> parameters [ 'data' ][ 'userID' ] = WCF :: getUser () -> userID ; $this -> parameters [ 'data' ][ 'username' ] = WCF :: getUser () -> username ; } if ( LOG_IP_ADDRESS ) { if ( ! isset ( $this -> parameters [ 'data' ][ 'ipAddress' ])) { $this -> parameters [ 'data' ][ 'ipAddress' ] = UserUtil :: getIpAddress (); } } else { unset ( $this -> parameters [ 'data' ][ 'ipAddress' ]); } if ( ! empty ( $this -> parameters [ 'information_htmlInputProcessor' ])) { /** @var HtmlInputProcessor $htmlInputProcessor */ $htmlInputProcessor = $this -> parameters [ 'information_htmlInputProcessor' ]; $this -> parameters [ 'data' ][ 'information' ] = $htmlInputProcessor -> getHtml (); } /** @var PersonInformation $information */ $information = parent :: create (); ( new PersonAction ([ $information -> personID ], 'update' , [ 'counters' => [ 'informationCount' => 1 , ], ])) -> executeAction (); return $information ; } /** * @inheritDoc */ public function update () { if ( ! empty ( $this -> parameters [ 'information_htmlInputProcessor' ])) { /** @var HtmlInputProcessor $htmlInputProcessor */ $htmlInputProcessor = $this -> parameters [ 'information_htmlInputProcessor' ]; $this -> parameters [ 'data' ][ 'information' ] = $htmlInputProcessor -> getHtml (); } parent :: update (); } /** * @inheritDoc */ public function validateDelete () { if ( empty ( $this -> objects )) { $this -> readObjects (); if ( empty ( $this -> objects )) { throw new UserInputException ( 'objectIDs' ); } } foreach ( $this -> getObjects () as $informationEditor ) { if ( ! $informationEditor -> canDelete ()) { throw new PermissionDeniedException (); } } } /** * @inheritDoc */ public function delete () { $deleteCount = parent :: delete (); if ( ! $deleteCount ) { return $deleteCount ; } $counterUpdates = []; foreach ( $this -> getObjects () as $informationEditor ) { if ( ! isset ( $counterUpdates [ $informationEditor -> personID ])) { $counterUpdates [ $informationEditor -> personID ] = 0 ; } $counterUpdates [ $informationEditor -> personID ] -- ; } WCF :: getDB () -> beginTransaction (); foreach ( $counterUpdates as $personID => $counterUpdate ) { ( new PersonEditor ( PersonRuntimeCache :: getInstance () -> getObject ( $personID ))) -> updateCounters ([ 'informationCount' => $counterUpdate , ]); } WCF :: getDB () -> commitTransaction (); return $deleteCount ; } /** * Validates the `getAddDialog` action. */ public function validateGetAddDialog () : void { WCF :: getSession () -> checkPermissions ([ 'user.person.canAddInformation' ]); $this -> readInteger ( 'personID' ); if ( PersonRuntimeCache :: getInstance () -> getObject ( $this -> parameters [ 'personID' ]) === null ) { throw new UserInputException ( 'personID' ); } } /** * Returns the data to show the dialog to add a new piece of information on a person. * * @return string[] */ public function getAddDialog () : array { $this -> buildDialog (); return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } /** * Validates the `submitAddDialog` action. */ public function validateSubmitAddDialog () : void { $this -> validateGetAddDialog (); $this -> buildDialog (); $this -> dialog -> requestData ( $_POST [ 'parameters' ][ 'data' ] ?? []); $this -> dialog -> readValues (); $this -> dialog -> validate (); } /** * Creates a new piece of information on a person after submitting the dialog. * * @return string[] */ public function submitAddDialog () : array { // If there are any validation errors, show the form again. if ( $this -> dialog -> hasValidationErrors ()) { return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } ( new static ([], 'create' , \\array_merge ( $this -> dialog -> getData (), [ 'data' => [ 'personID' => $this -> parameters [ 'personID' ], ], ]))) -> executeAction (); return []; } /** * Validates the `getEditDialog` action. */ public function validateGetEditDialog () : void { WCF :: getSession () -> checkPermissions ([ 'user.person.canAddInformation' ]); $this -> readInteger ( 'informationID' ); $this -> information = new PersonInformation ( $this -> parameters [ 'informationID' ]); if ( ! $this -> information -> getObjectID ()) { throw new UserInputException ( 'informationID' ); } if ( ! $this -> information -> canEdit ()) { throw new IllegalLinkException (); } } /** * Returns the data to show the dialog to edit a piece of information on a person. * * @return string[] */ public function getEditDialog () : array { $this -> buildDialog (); $this -> dialog -> updatedObject ( $this -> information ); return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } /** * Validates the `submitEditDialog` action. */ public function validateSubmitEditDialog () : void { $this -> validateGetEditDialog (); $this -> buildDialog (); $this -> dialog -> updatedObject ( $this -> information , false ); $this -> dialog -> requestData ( $_POST [ 'parameters' ][ 'data' ] ?? []); $this -> dialog -> readValues (); $this -> dialog -> validate (); } /** * Updates a piece of information on a person after submitting the edit dialog. * * @return string[] */ public function submitEditDialog () : array { // If there are any validation errors, show the form again. if ( $this -> dialog -> hasValidationErrors ()) { return [ 'dialog' => $this -> dialog -> getHtml (), 'formId' => $this -> dialog -> getId (), ]; } ( new static ([ $this -> information ], 'update' , $this -> dialog -> getData ())) -> executeAction (); // Reload the information with the updated data. $information = new PersonInformation ( $this -> information -> getObjectID ()); return [ 'formattedInformation' => $information -> getFormattedInformation (), 'informationID' => $this -> information -> getObjectID (), ]; } /** * Builds the dialog to create or edit person information. */ protected function buildDialog () : void { if ( $this -> dialog !== null ) { return ; } $this -> dialog = DialogFormDocument :: create ( 'personInformationAddDialog' ) -> appendChild ( WysiwygFormContainer :: create ( 'information' ) -> messageObjectType ( 'com.woltlab.wcf.people.information' ) -> required () ); EventHandler :: getInstance () -> fireAction ( $this , 'buildDialog' ); $this -> dialog -> build (); } } When setting up the WoltLabSuite/Core/Form/Builder/Dialog object for adding new pieces of information, we specified getAddDialog and submitAddDialog as the names of the dialog getter and submit handler. In addition to these two methods, the matching validation methods validateGetAddDialog() and validateGetAddDialog() are also added. As the forms for adding and editing pieces of information have the same structure, this form is created in buildDialog() using a DialogFormDocument object, which is intended for forms in dialogs. We fire an event in buildDialog() so that plugins are able to easily extend the dialog with additional data. validateGetAddDialog() checks if the user has the permission to create new pieces of information and if a valid id for the person, the information will belong to, is given. The method configured in the WoltLabSuite/Core/Form/Builder/Dialog object returning the dialog is expected to return two values: the id of the form ( formId ) and the contents of form shown in the dialog ( dialog ). This data is returned by getAddDialog using the dialog build previously by buildDialog() . After the form is submitted, validateSubmitAddDialog() has to do the same basic validation as validateGetAddDialog() so that validateGetAddDialog() is simply called. Additionally, the form data is read and validated. In submitAddDialog() , we first check if there have been any validation errors: If any error occured during validation, we return the same data as in getAddDialog() so that the dialog is shown again with the erroneous fields marked as such. Otherwise, if the validation succeeded, the form data is used to create the new piece of information. In addition to the form data, we manually add the id of the person to whom the information belongs to. Lastly, we could return some data that we could access in the JavaScript callback function after successfully submitting the dialog. As we will simply be reloading the page, no such data is returned. An alternative to reloading to the page would be dynamically inserting the new piece of information in the list so that we would have to return the rendered list item for the new piece of information. The process for getting and submitting the dialog to edit existing pieces of information is similar to the process for adding new pieces of information. Instead of the id of the person, however, we now pass the id of the edited piece of information and in submitEditDialog() , we update the edited information instead of creating a new one like in submitAddDialog() . After editing a piece of information, we do not reload the page but dynamically update the text of the information in the TypeScript code so that we return the updated rendered information text and id of the edited pieced of information in submitAddDialog() .","title":"Creating and Editing Person Information"},{"location":"tutorial/series/part_5/#rebuild-data-worker","text":"To ensure the integrity of the person data, PersonRebuildDataWorker updates the informationCount counter: files/lib/system/worker/PersonRebuildDataWorker.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 <? php namespace wcf\\system\\worker ; use wcf\\data\\person\\PersonList ; use wcf\\system\\WCF ; /** * Worker implementation for updating people. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Worker * * @method PersonList getObjectList() */ class PersonRebuildDataWorker extends AbstractRebuildDataWorker { /** * @inheritDoc */ protected $limit = 500 ; /** * @inheritDoc */ protected $objectListClassName = PersonList :: class ; /** * @inheritDoc */ protected function initObjectList () { parent :: initObjectList (); $this -> objectList -> sqlOrderBy = 'person.personID' ; } /** * @inheritDoc */ public function execute () { parent :: execute (); if ( ! \\count ( $this -> objectList )) { return ; } $sql = \"UPDATE wcf\" . WCF_N . \"_person person SET informationCount = ( SELECT COUNT(*) FROM wcf\" . WCF_N . \"_person_information person_information WHERE person_information.personID = person.personID ) WHERE person.personID = ?\" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); WCF :: getDB () -> beginTransaction (); foreach ( $this -> getObjectList () as $person ) { $statement -> execute ([ $person -> personID ]); } WCF :: getDB () -> commitTransaction (); } }","title":"Rebuild Data Worker"},{"location":"tutorial/series/part_5/#username-and-ip-address-event-listeners","text":"As we store the name of the user who create a new piece of information and store their IP address, we have to add event listeners to properly handle the following scenarios: If the user is renamed, the value of username stored with the person information has to be updated, which can be achieved by a simple event listener that only has to specify the name of relevant database table if AbstractUserActionRenameListener is extended: files/lib/system/event/listener/PersonUserActionRenameListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; /** * Updates person information during user renaming. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserActionRenameListener extends AbstractUserActionRenameListener { /** * @inheritDoc */ protected $databaseTables = [ 'wcf{WCF_N}_person_information' , ]; } If users are merged, all pieces of information need to be assigned to the target user of the merging. Again, we only have to specify the name of relevant database table if AbstractUserMergeListener is extended: files/lib/system/event/listener/PersonUserMergeListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; /** * Updates person information during user merging. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserMergeListener extends AbstractUserMergeListener { /** * @inheritDoc */ protected $databaseTables = [ 'wcf{WCF_N}_person_information' , ]; } If the option to prune stored ip addresses after a certain period of time is enabled, we also have to prune them in the person information database table. Here we also only have to specify the name of the relevant database table and provide the mapping from the ipAddress column to the time column: files/lib/system/event/listener/PersonPruneIpAddressesCronjobListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\cronjob\\PruneIpAddressesCronjob ; /** * Prunes old ip addresses. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonPruneIpAddressesCronjobListener extends AbstractEventListener { protected function onExecute ( PruneIpAddressesCronjob $cronjob ) : void { $cronjob -> columns [ 'wcf' . WCF_N . '_person_information' ][ 'ipAddress' ] = 'time' ; } } The ip addresses in the person information database table also have to be considered for the user data export which can also be done with minimal effort by providing the name of the relevant database table: files/lib/system/event/listener/PersonUserExportGdprListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <? php namespace wcf\\system\\event\\listener ; use wcf\\acp\\action\\UserExportGdprAction ; /** * Adds the ip addresses stored with the person information during user data export. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserExportGdprListener extends AbstractEventListener { protected function onExport ( UserExportGdprAction $action ) : void { $action -> ipAddresses [ 'com.woltlab.wcf.people' ] = [ 'wcf' . WCF_N . '_person_information' ]; } } Lastly, we present the updated eventListener.xml file with new entries for all of these event listeners: eventListener.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> <data xmlns= \"http://www.woltlab.com\" xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd\" > <import> <eventlistener name= \"rename@wcf\\data\\user\\UserAction\" > <eventclassname> wcf\\data\\user\\UserAction </eventclassname> <eventname> rename </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserActionRenameListener </listenerclassname> <environment> all </environment> </eventlistener> <eventlistener name= \"save@wcf\\acp\\form\\UserMergeForm\" > <eventclassname> wcf\\acp\\form\\UserMergeForm </eventclassname> <eventname> save </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserMergeListener </listenerclassname> <environment> admin </environment> </eventlistener> <eventlistener name= \"execute@wcf\\system\\cronjob\\PruneIpAddressesCronjob\" > <eventclassname> wcf\\system\\cronjob\\PruneIpAddressesCronjob </eventclassname> <eventname> execute </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonPruneIpAddressesCronjobListener </listenerclassname> <environment> all </environment> </eventlistener> <eventlistener name= \"export@wcf\\acp\\action\\UserExportGdprAction\" > <eventclassname> wcf\\acp\\action\\UserExportGdprAction </eventclassname> <eventname> export </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserExportGdprListener </listenerclassname> <environment> admin </environment> </eventlistener> </import> </data>","title":"Username and IP Address Event Listeners"},{"location":"tutorial/series/part_6/","text":"Part 6: Activity Points and Activity Events # In this part of our tutorial series, we use the person information added in the previous part to award activity points to users adding new pieces of information and to also create activity events for these pieces of information. Package Functionality # In addition to the existing functions from part 5 , the package will provide the following functionality after this part of the tutorial: Users are awarded activity points for adding new pieces of information for people. If users add new pieces of information for people, activity events are added which are then shown in the list of recent activities. Used Components # In addition to the components used in previous parts, we will use the user activity points API and the user activity events API. Package Structure # The package will have the following file structure excluding unchanged files from previous parts: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u2514\u2500\u2500 information \u2502 \u2502 \u251c\u2500\u2500 PersonInformation.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonInformationAction.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 user \u2502 \u2502 \u2514\u2500\u2500 activity \u2502 \u2502 \u2514\u2500\u2500 event \u2502 \u2502 \u2514\u2500\u2500 PersonInformationUserActivityEvent.class.php \u2502 \u2514\u2500\u2500 worker \u2502 \u251c\u2500\u2500 PersonInformationRebuildDataWorker.class.php \u2502 \u2514\u2500\u2500 PersonRebuildDataWorker.class.php \u251c\u2500\u2500 eventListener.xml \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u2514\u2500\u2500 objectType.xml For all changes, please refer to the source code on GitHub . User Activity Points # The first step to support activity points is to register an object type for the com.woltlab.wcf.user.activityPointEvent object type definition for created person information and specify the default number of points awarded per piece of information: objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.user.activityPointEvent </definitionname> <points> 2 </points> </type> Additionally, the phrase wcf.user.activityPoint.objectType.com.woltlab.wcf.people.information (in general: wcf.user.activityPoint.objectType.{objectType} ) has to be added. The activity points are awarded when new pieces are created via PersonInformation::create() using UserActivityPointHandler::fireEvent() and removed in PersonInformation::create() via UserActivityPointHandler::removeEvents() if pieces of information are deleted. Lastly, we have to add two components for updating data: First, we register a new rebuild data worker objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.rebuildData </definitionname> <classname> wcf\\system\\worker\\PersonInformationRebuildDataWorker </classname> </type> files/lib/system/worker/PersonInformationRebuildDataWorker.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 <? php namespace wcf\\system\\worker ; use wcf\\data\\person\\information\\PersonInformationList ; use wcf\\system\\user\\activity\\point\\UserActivityPointHandler ; /** * Worker implementation for updating person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Worker * * @method PersonInformationList getObjectList() */ class PersonInformationRebuildDataWorker extends AbstractRebuildDataWorker { /** * @inheritDoc */ protected $objectListClassName = PersonInformationList :: class ; /** * @inheritDoc */ protected $limit = 500 ; /** * @inheritDoc */ protected function initObjectList () { parent :: initObjectList (); $this -> objectList -> sqlOrderBy = 'person_information.personID' ; } /** * @inheritDoc */ public function execute () { parent :: execute (); if ( ! $this -> loopCount ) { UserActivityPointHandler :: getInstance () -> reset ( 'com.woltlab.wcf.people.information' ); } if ( ! \\count ( $this -> objectList )) { return ; } $itemsToUser = []; foreach ( $this -> getObjectList () as $personInformation ) { if ( $personInformation -> userID ) { if ( ! isset ( $itemsToUser [ $personInformation -> userID ])) { $itemsToUser [ $personInformation -> userID ] = 0 ; } $itemsToUser [ $personInformation -> userID ] ++ ; } } UserActivityPointHandler :: getInstance () -> fireEvents ( 'com.woltlab.wcf.people.information' , $itemsToUser , false ); } } which updates the number of instances for which any user received person information activity points. (This data worker also requires the phrases wcf.acp.rebuildData.com.woltlab.wcf.people.information and wcf.acp.rebuildData.com.woltlab.wcf.people.information.description ). Second, we add an event listener for UserActivityPointItemsRebuildDataWorker to update the total user activity points awarded for person information: eventListener.xml 1 2 3 4 5 6 <eventlistener name= \"execute@wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker\" > <eventclassname> wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker </eventclassname> <eventname> execute </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserActivityPointItemsRebuildDataWorkerListener </listenerclassname> <environment> admin </environment> </eventlistener> files/lib/system/event/listener/PersonUserActivityPointItemsRebuildDataWorkerListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\database\\util\\PreparedStatementConditionBuilder ; use wcf\\system\\user\\activity\\point\\UserActivityPointHandler ; use wcf\\system\\WCF ; use wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker ; /** * Updates the user activity point items counter for person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserActivityPointItemsRebuildDataWorkerListener extends AbstractEventListener { protected function onExecute ( UserActivityPointItemsRebuildDataWorker $worker ) : void { $objectType = UserActivityPointHandler :: getInstance () -> getObjectTypeByName ( 'com.woltlab.wcf.people.information' ); $conditionBuilder = new PreparedStatementConditionBuilder (); $conditionBuilder -> add ( 'user_activity_point.objectTypeID = ?' , [ $objectType -> objectTypeID ]); $conditionBuilder -> add ( 'user_activity_point.userID IN (?)' , [ $worker -> getObjectList () -> getObjectIDs ()]); $sql = \"UPDATE wcf\" . WCF_N . \"_user_activity_point user_activity_point SET user_activity_point.items = ( SELECT COUNT(*) FROM wcf\" . WCF_N . \"_person_information person_information WHERE person_information.userID = user_activity_point.userID ), user_activity_point.activityPoints = user_activity_point.items * ? { $conditionBuilder } \" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ( \\array_merge ( [ $objectType -> points ], $conditionBuilder -> getParameters () )); } } User Activity Events # To support user activity events, an object type for com.woltlab.wcf.user.recentActivityEvent has to be registered with a class implementing wcf\\system\\user\\activity\\event\\IUserActivityEvent : objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.user.recentActivityEvent </definitionname> <classname> wcf\\system\\user\\activity\\event\\PersonInformationUserActivityEvent </classname> </type> files/lib/system/user/activity/event/PersonInformationUserActivityEvent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <? php namespace wcf\\system\\user\\activity\\event ; use wcf\\data\\person\\information\\PersonInformationList ; use wcf\\system\\SingletonFactory ; use wcf\\system\\WCF ; /** * User activity event implementation for person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\User\\Activity\\Event */ class PersonInformationUserActivityEvent extends SingletonFactory implements IUserActivityEvent { /** * @inheritDoc */ public function prepare ( array $events ) { $objectIDs = \\array_column ( $events , 'objectID' ); $informationList = new PersonInformationList (); $informationList -> setObjectIDs ( $objectIDs ); $informationList -> readObjects (); $information = $informationList -> getObjects (); foreach ( $events as $event ) { if ( isset ( $information [ $event -> objectID ])) { $personInformation = $information [ $event -> objectID ]; $event -> setIsAccessible (); $event -> setTitle ( WCF :: getLanguage () -> getDynamicVariable ( 'wcf.user.profile.recentActivity.personInformation' , [ 'person' => $personInformation -> getPerson (), 'personInformation' => $personInformation , ] ) ); $event -> setDescription ( $personInformation -> getFormattedExcerpt ()); } } } } PersonInformationUserActivityEvent::prepare() must check for all events whether the associated piece of information still exists and if it is the case, mark the event as accessible via the setIsAccessible() method, set the title of the activity event via setTitle() , and set a description of the event via setDescription() for which we use the newly added PersonInformation::getFormattedExcerpt() method. Lastly, we have to add the phrase wcf.user.recentActivity.com.woltlab.wcf.people.information , which is shown in the list of activity events as the type of activity event.","title":"Part 6"},{"location":"tutorial/series/part_6/#part-6-activity-points-and-activity-events","text":"In this part of our tutorial series, we use the person information added in the previous part to award activity points to users adding new pieces of information and to also create activity events for these pieces of information.","title":"Part 6: Activity Points and Activity Events"},{"location":"tutorial/series/part_6/#package-functionality","text":"In addition to the existing functions from part 5 , the package will provide the following functionality after this part of the tutorial: Users are awarded activity points for adding new pieces of information for people. If users add new pieces of information for people, activity events are added which are then shown in the list of recent activities.","title":"Package Functionality"},{"location":"tutorial/series/part_6/#used-components","text":"In addition to the components used in previous parts, we will use the user activity points API and the user activity events API.","title":"Used Components"},{"location":"tutorial/series/part_6/#package-structure","text":"The package will have the following file structure excluding unchanged files from previous parts: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 \u251c\u2500\u2500 files \u2502 \u2514\u2500\u2500 lib \u2502 \u251c\u2500\u2500 data \u2502 \u2502 \u2514\u2500\u2500 person \u2502 \u2502 \u251c\u2500\u2500 PersonAction.class.php \u2502 \u2502 \u2514\u2500\u2500 information \u2502 \u2502 \u251c\u2500\u2500 PersonInformation.class.php \u2502 \u2502 \u2514\u2500\u2500 PersonInformationAction.class.php \u2502 \u2514\u2500\u2500 system \u2502 \u251c\u2500\u2500 user \u2502 \u2502 \u2514\u2500\u2500 activity \u2502 \u2502 \u2514\u2500\u2500 event \u2502 \u2502 \u2514\u2500\u2500 PersonInformationUserActivityEvent.class.php \u2502 \u2514\u2500\u2500 worker \u2502 \u251c\u2500\u2500 PersonInformationRebuildDataWorker.class.php \u2502 \u2514\u2500\u2500 PersonRebuildDataWorker.class.php \u251c\u2500\u2500 eventListener.xml \u251c\u2500\u2500 language \u2502 \u251c\u2500\u2500 de.xml \u2502 \u2514\u2500\u2500 en.xml \u2514\u2500\u2500 objectType.xml For all changes, please refer to the source code on GitHub .","title":"Package Structure"},{"location":"tutorial/series/part_6/#user-activity-points","text":"The first step to support activity points is to register an object type for the com.woltlab.wcf.user.activityPointEvent object type definition for created person information and specify the default number of points awarded per piece of information: objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.user.activityPointEvent </definitionname> <points> 2 </points> </type> Additionally, the phrase wcf.user.activityPoint.objectType.com.woltlab.wcf.people.information (in general: wcf.user.activityPoint.objectType.{objectType} ) has to be added. The activity points are awarded when new pieces are created via PersonInformation::create() using UserActivityPointHandler::fireEvent() and removed in PersonInformation::create() via UserActivityPointHandler::removeEvents() if pieces of information are deleted. Lastly, we have to add two components for updating data: First, we register a new rebuild data worker objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.rebuildData </definitionname> <classname> wcf\\system\\worker\\PersonInformationRebuildDataWorker </classname> </type> files/lib/system/worker/PersonInformationRebuildDataWorker.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 <? php namespace wcf\\system\\worker ; use wcf\\data\\person\\information\\PersonInformationList ; use wcf\\system\\user\\activity\\point\\UserActivityPointHandler ; /** * Worker implementation for updating person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Worker * * @method PersonInformationList getObjectList() */ class PersonInformationRebuildDataWorker extends AbstractRebuildDataWorker { /** * @inheritDoc */ protected $objectListClassName = PersonInformationList :: class ; /** * @inheritDoc */ protected $limit = 500 ; /** * @inheritDoc */ protected function initObjectList () { parent :: initObjectList (); $this -> objectList -> sqlOrderBy = 'person_information.personID' ; } /** * @inheritDoc */ public function execute () { parent :: execute (); if ( ! $this -> loopCount ) { UserActivityPointHandler :: getInstance () -> reset ( 'com.woltlab.wcf.people.information' ); } if ( ! \\count ( $this -> objectList )) { return ; } $itemsToUser = []; foreach ( $this -> getObjectList () as $personInformation ) { if ( $personInformation -> userID ) { if ( ! isset ( $itemsToUser [ $personInformation -> userID ])) { $itemsToUser [ $personInformation -> userID ] = 0 ; } $itemsToUser [ $personInformation -> userID ] ++ ; } } UserActivityPointHandler :: getInstance () -> fireEvents ( 'com.woltlab.wcf.people.information' , $itemsToUser , false ); } } which updates the number of instances for which any user received person information activity points. (This data worker also requires the phrases wcf.acp.rebuildData.com.woltlab.wcf.people.information and wcf.acp.rebuildData.com.woltlab.wcf.people.information.description ). Second, we add an event listener for UserActivityPointItemsRebuildDataWorker to update the total user activity points awarded for person information: eventListener.xml 1 2 3 4 5 6 <eventlistener name= \"execute@wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker\" > <eventclassname> wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker </eventclassname> <eventname> execute </eventname> <listenerclassname> wcf\\system\\event\\listener\\PersonUserActivityPointItemsRebuildDataWorkerListener </listenerclassname> <environment> admin </environment> </eventlistener> files/lib/system/event/listener/PersonUserActivityPointItemsRebuildDataWorkerListener.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <? php namespace wcf\\system\\event\\listener ; use wcf\\system\\database\\util\\PreparedStatementConditionBuilder ; use wcf\\system\\user\\activity\\point\\UserActivityPointHandler ; use wcf\\system\\WCF ; use wcf\\system\\worker\\UserActivityPointItemsRebuildDataWorker ; /** * Updates the user activity point items counter for person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\Event\\Listener */ class PersonUserActivityPointItemsRebuildDataWorkerListener extends AbstractEventListener { protected function onExecute ( UserActivityPointItemsRebuildDataWorker $worker ) : void { $objectType = UserActivityPointHandler :: getInstance () -> getObjectTypeByName ( 'com.woltlab.wcf.people.information' ); $conditionBuilder = new PreparedStatementConditionBuilder (); $conditionBuilder -> add ( 'user_activity_point.objectTypeID = ?' , [ $objectType -> objectTypeID ]); $conditionBuilder -> add ( 'user_activity_point.userID IN (?)' , [ $worker -> getObjectList () -> getObjectIDs ()]); $sql = \"UPDATE wcf\" . WCF_N . \"_user_activity_point user_activity_point SET user_activity_point.items = ( SELECT COUNT(*) FROM wcf\" . WCF_N . \"_person_information person_information WHERE person_information.userID = user_activity_point.userID ), user_activity_point.activityPoints = user_activity_point.items * ? { $conditionBuilder } \" ; $statement = WCF :: getDB () -> prepareStatement ( $sql ); $statement -> execute ( \\array_merge ( [ $objectType -> points ], $conditionBuilder -> getParameters () )); } }","title":"User Activity Points"},{"location":"tutorial/series/part_6/#user-activity-events","text":"To support user activity events, an object type for com.woltlab.wcf.user.recentActivityEvent has to be registered with a class implementing wcf\\system\\user\\activity\\event\\IUserActivityEvent : objectType.xml 1 2 3 4 5 <type> <name> com.woltlab.wcf.people.information </name> <definitionname> com.woltlab.wcf.user.recentActivityEvent </definitionname> <classname> wcf\\system\\user\\activity\\event\\PersonInformationUserActivityEvent </classname> </type> files/lib/system/user/activity/event/PersonInformationUserActivityEvent.class.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <? php namespace wcf\\system\\user\\activity\\event ; use wcf\\data\\person\\information\\PersonInformationList ; use wcf\\system\\SingletonFactory ; use wcf\\system\\WCF ; /** * User activity event implementation for person information. * * @author Matthias Schmidt * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\\Core\\System\\User\\Activity\\Event */ class PersonInformationUserActivityEvent extends SingletonFactory implements IUserActivityEvent { /** * @inheritDoc */ public function prepare ( array $events ) { $objectIDs = \\array_column ( $events , 'objectID' ); $informationList = new PersonInformationList (); $informationList -> setObjectIDs ( $objectIDs ); $informationList -> readObjects (); $information = $informationList -> getObjects (); foreach ( $events as $event ) { if ( isset ( $information [ $event -> objectID ])) { $personInformation = $information [ $event -> objectID ]; $event -> setIsAccessible (); $event -> setTitle ( WCF :: getLanguage () -> getDynamicVariable ( 'wcf.user.profile.recentActivity.personInformation' , [ 'person' => $personInformation -> getPerson (), 'personInformation' => $personInformation , ] ) ); $event -> setDescription ( $personInformation -> getFormattedExcerpt ()); } } } } PersonInformationUserActivityEvent::prepare() must check for all events whether the associated piece of information still exists and if it is the case, mark the event as accessible via the setIsAccessible() method, set the title of the activity event via setTitle() , and set a description of the event via setDescription() for which we use the newly added PersonInformation::getFormattedExcerpt() method. Lastly, we have to add the phrase wcf.user.recentActivity.com.woltlab.wcf.people.information , which is shown in the list of activity events as the type of activity event.","title":"User Activity Events"},{"location":"view/css/","text":"CSS # SCSS and CSS # SCSS is a scripting language that features a syntax similar to CSS and compiles into native CSS at runtime. It provides many great additions to CSS such as declaration nesting and variables, it is recommended to read the official guide to learn more. You can create .scss files containing only pure CSS code and it will work just fine, you are at no point required to write actual SCSS code. File Location # Please place your style files in a subdirectory of the style/ directory of the target application or the Core's style directory, for example style/layout/pageHeader.scss . Variables # You can access variables with $myVariable , variable interpolation (variables inside strings) is accomplished with #{$myVariable} . Linking images # Images used within a style must be located in the style's image folder. To get the folder name within the CSS the SCSS variable #{$style_image_path} can be used. The value will contain a trailing slash. Media Breakpoints # Media breakpoints instruct the browser to apply different CSS depending on the viewport dimensions, e.g. serving a desktop PC a different view than when viewed on a smartphone. 1 2 3 4 5 6 7 8 9 10 11 12 13 /* red background color for desktop pc */ @include screen-lg { body { background-color : red ; } } /* green background color on smartphones and tablets */ @include screen-md-down { body { background-color : green ; } } Available Breakpoints # Some very large smartphones, for example the Apple iPhone 7 Plus, do match the media query for Tablets (portrait) when viewed in landscape mode. Name Devices @media equivalent screen-xs Smartphones only (max-width: 544px) screen-sm Tablets (portrait) (min-width: 545px) and (max-width: 768px) screen-sm-down Tablets (portrait) and smartphones (max-width: 768px) screen-sm-up Tablets and desktop PC (min-width: 545px) screen-sm-md Tablets only (min-width: 545px) and (max-width: 1024px) screen-md Tablets (landscape) (min-width: 769px) and (max-width: 1024px) screen-md-down Smartphones and tablets (max-width: 1024px) screen-md-up Tablets (landscape) and desktop PC (min-width: 769px) screen-lg Desktop PC (min-width: 1025px) screen-lg-only Desktop PC (min-width: 1025px) and (max-width: 1280px) screen-lg-down Smartphones, tablets, and desktop PC (max-width: 1280px) screen-xl Desktop PC (min-width: 1281px) Asset Preloading # WoltLab Suite\u2019s SCSS compiler supports adding preloading metadata to the CSS. To communicate the preloading intent to the compiler, the --woltlab-suite-preload CSS variable is set to the result of the preload() function: 1 2 3 4 5 6 7 8 9 10 .fooBar { --woltlab-suite-preload : # { preload ( ' #{ $style_image_path } custom/background.png' , $ as : \"image\" , $ crossorigin : false , $ type : \"image/png\" ) } ; background : url ( ' #{ $style_image_path } custom/background.png' ); } The parameters of the preload() function map directly to the preloading properties that are used within the <link> tag and the link: HTTP response header. The above example will result in a <link> similar to the following being added to the generated HTML: 1 <link rel=\"preload\" href=\"https://example.com/images/style-1/custom/background.png\" as=\"image\" type=\"image/png\"> Use preloading sparingly for the most important resources where you can be certain that the browser will need them. Unused preloaded resources will unnecessarily waste bandwidth.","title":"CSS"},{"location":"view/css/#css","text":"","title":"CSS"},{"location":"view/css/#scss-and-css","text":"SCSS is a scripting language that features a syntax similar to CSS and compiles into native CSS at runtime. It provides many great additions to CSS such as declaration nesting and variables, it is recommended to read the official guide to learn more. You can create .scss files containing only pure CSS code and it will work just fine, you are at no point required to write actual SCSS code.","title":"SCSS and CSS"},{"location":"view/css/#file-location","text":"Please place your style files in a subdirectory of the style/ directory of the target application or the Core's style directory, for example style/layout/pageHeader.scss .","title":"File Location"},{"location":"view/css/#variables","text":"You can access variables with $myVariable , variable interpolation (variables inside strings) is accomplished with #{$myVariable} .","title":"Variables"},{"location":"view/css/#linking-images","text":"Images used within a style must be located in the style's image folder. To get the folder name within the CSS the SCSS variable #{$style_image_path} can be used. The value will contain a trailing slash.","title":"Linking images"},{"location":"view/css/#media-breakpoints","text":"Media breakpoints instruct the browser to apply different CSS depending on the viewport dimensions, e.g. serving a desktop PC a different view than when viewed on a smartphone. 1 2 3 4 5 6 7 8 9 10 11 12 13 /* red background color for desktop pc */ @include screen-lg { body { background-color : red ; } } /* green background color on smartphones and tablets */ @include screen-md-down { body { background-color : green ; } }","title":"Media Breakpoints"},{"location":"view/css/#available-breakpoints","text":"Some very large smartphones, for example the Apple iPhone 7 Plus, do match the media query for Tablets (portrait) when viewed in landscape mode. Name Devices @media equivalent screen-xs Smartphones only (max-width: 544px) screen-sm Tablets (portrait) (min-width: 545px) and (max-width: 768px) screen-sm-down Tablets (portrait) and smartphones (max-width: 768px) screen-sm-up Tablets and desktop PC (min-width: 545px) screen-sm-md Tablets only (min-width: 545px) and (max-width: 1024px) screen-md Tablets (landscape) (min-width: 769px) and (max-width: 1024px) screen-md-down Smartphones and tablets (max-width: 1024px) screen-md-up Tablets (landscape) and desktop PC (min-width: 769px) screen-lg Desktop PC (min-width: 1025px) screen-lg-only Desktop PC (min-width: 1025px) and (max-width: 1280px) screen-lg-down Smartphones, tablets, and desktop PC (max-width: 1280px) screen-xl Desktop PC (min-width: 1281px)","title":"Available Breakpoints"},{"location":"view/css/#asset-preloading","text":"WoltLab Suite\u2019s SCSS compiler supports adding preloading metadata to the CSS. To communicate the preloading intent to the compiler, the --woltlab-suite-preload CSS variable is set to the result of the preload() function: 1 2 3 4 5 6 7 8 9 10 .fooBar { --woltlab-suite-preload : # { preload ( ' #{ $style_image_path } custom/background.png' , $ as : \"image\" , $ crossorigin : false , $ type : \"image/png\" ) } ; background : url ( ' #{ $style_image_path } custom/background.png' ); } The parameters of the preload() function map directly to the preloading properties that are used within the <link> tag and the link: HTTP response header. The above example will result in a <link> similar to the following being added to the generated HTML: 1 <link rel=\"preload\" href=\"https://example.com/images/style-1/custom/background.png\" as=\"image\" type=\"image/png\"> Use preloading sparingly for the most important resources where you can be certain that the browser will need them. Unused preloaded resources will unnecessarily waste bandwidth.","title":"Asset Preloading"},{"location":"view/languages-naming-conventions/","text":"Language Naming Conventions # This page contains general rules for naming language items and for their values. API-specific rules are listed on the relevant API page: Comments Forms # Fields # If you have an application foo and a database object foo\\data\\bar\\Bar with a property baz that can be set via a form field, the name of the corresponding language item has to be foo.bar.baz . If you want to add an additional description below the field, use the language item foo.bar.baz.description . Error Texts # If an error of type {error type} for the previously mentioned form field occurs during validation, you have to use the language item foo.bar.baz.error.{error type} for the language item describing the error. Exception to this rule: There are several general error messages like wcf.global.form.error.empty that have to be used for general errors like an empty field that may not be empty to avoid duplication of the same error message text over and over again in different language items. Naming Conventions # If the entered text does not conform to some special rules, i.e. if the text is invalid, use invalid as error type. If the entered text is required to be unique but is already used for another object, use notUnique as error type. Confirmation messages # If the language item for an action is foo.bar.action , the language item for the confirmation message has to be foo.bar.action.confirmMessage instead of foo.bar.action.sure which is still used by some older language items. Type-Specific Deletion Confirmation Message # German # 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} {element type} wirklich l\u00f6schen? Example: 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} das Icon wirklich l\u00f6schen? English # 1 Do you really want delete the {element type}? Example: 1 Do you really want delete the icon? Object-Specific Deletion Confirmation Message # German # 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} {element type} <span class=\"confirmationObject\">{object name}</span> wirklich l\u00f6schen? Example: 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} den Artikel <span class=\"confirmationObject\">{$article->getTitle()}</span> wirklich l\u00f6schen? English # 1 Do you really want to delete the {element type} <span class=\"confirmationObject\">{object name}</span>? Example: 1 Do you really want to delete the article <span class=\"confirmationObject\">{$article->getTitle()}</span>? User Group Options # Comments # German # group type action example permission name language item user adding user.foo.canAddComment Kann Kommentare erstellen user deleting user.foo.canDeleteComment Kann eigene Kommentare l\u00f6schen user editing user.foo.canEditComment Kann eigene Kommentare bearbeiten moderator deleting mod.foo.canDeleteComment Kann Kommentare l\u00f6schen moderator editing mod.foo.canEditComment Kann Kommentare bearbeiten moderator moderating mod.foo.canModerateComment Kann Kommentare moderieren English # group type action example permission name language item user adding user.foo.canAddComment Can create comments user deleting user.foo.canDeleteComment Can delete their comments user editing user.foo.canEditComment Can edit their comments moderator deleting mod.foo.canDeleteComment Can delete comments moderator editing mod.foo.canEditComment Can edit comments moderator moderating mod.foo.canModerateComment Can moderate comments","title":"Language Naming Conventions"},{"location":"view/languages-naming-conventions/#language-naming-conventions","text":"This page contains general rules for naming language items and for their values. API-specific rules are listed on the relevant API page: Comments","title":"Language Naming Conventions"},{"location":"view/languages-naming-conventions/#forms","text":"","title":"Forms"},{"location":"view/languages-naming-conventions/#fields","text":"If you have an application foo and a database object foo\\data\\bar\\Bar with a property baz that can be set via a form field, the name of the corresponding language item has to be foo.bar.baz . If you want to add an additional description below the field, use the language item foo.bar.baz.description .","title":"Fields"},{"location":"view/languages-naming-conventions/#error-texts","text":"If an error of type {error type} for the previously mentioned form field occurs during validation, you have to use the language item foo.bar.baz.error.{error type} for the language item describing the error. Exception to this rule: There are several general error messages like wcf.global.form.error.empty that have to be used for general errors like an empty field that may not be empty to avoid duplication of the same error message text over and over again in different language items.","title":"Error Texts"},{"location":"view/languages-naming-conventions/#naming-conventions","text":"If the entered text does not conform to some special rules, i.e. if the text is invalid, use invalid as error type. If the entered text is required to be unique but is already used for another object, use notUnique as error type.","title":"Naming Conventions"},{"location":"view/languages-naming-conventions/#confirmation-messages","text":"If the language item for an action is foo.bar.action , the language item for the confirmation message has to be foo.bar.action.confirmMessage instead of foo.bar.action.sure which is still used by some older language items.","title":"Confirmation messages"},{"location":"view/languages-naming-conventions/#type-specific-deletion-confirmation-message","text":"","title":"Type-Specific Deletion Confirmation Message"},{"location":"view/languages-naming-conventions/#german","text":"1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} {element type} wirklich l\u00f6schen? Example: 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} das Icon wirklich l\u00f6schen?","title":"German"},{"location":"view/languages-naming-conventions/#english","text":"1 Do you really want delete the {element type}? Example: 1 Do you really want delete the icon?","title":"English"},{"location":"view/languages-naming-conventions/#object-specific-deletion-confirmation-message","text":"","title":"Object-Specific Deletion Confirmation Message"},{"location":"view/languages-naming-conventions/#german_1","text":"1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} {element type} <span class=\"confirmationObject\">{object name}</span> wirklich l\u00f6schen? Example: 1 {if LANGUAGE_USE_INFORMAL_VARIANT}Willst du{else}Wollen Sie{/if} den Artikel <span class=\"confirmationObject\">{$article->getTitle()}</span> wirklich l\u00f6schen?","title":"German"},{"location":"view/languages-naming-conventions/#english_1","text":"1 Do you really want to delete the {element type} <span class=\"confirmationObject\">{object name}</span>? Example: 1 Do you really want to delete the article <span class=\"confirmationObject\">{$article->getTitle()}</span>?","title":"English"},{"location":"view/languages-naming-conventions/#user-group-options","text":"","title":"User Group Options"},{"location":"view/languages-naming-conventions/#comments","text":"","title":"Comments"},{"location":"view/languages-naming-conventions/#german_2","text":"group type action example permission name language item user adding user.foo.canAddComment Kann Kommentare erstellen user deleting user.foo.canDeleteComment Kann eigene Kommentare l\u00f6schen user editing user.foo.canEditComment Kann eigene Kommentare bearbeiten moderator deleting mod.foo.canDeleteComment Kann Kommentare l\u00f6schen moderator editing mod.foo.canEditComment Kann Kommentare bearbeiten moderator moderating mod.foo.canModerateComment Kann Kommentare moderieren","title":"German"},{"location":"view/languages-naming-conventions/#english_2","text":"group type action example permission name language item user adding user.foo.canAddComment Can create comments user deleting user.foo.canDeleteComment Can delete their comments user editing user.foo.canEditComment Can edit their comments moderator deleting mod.foo.canDeleteComment Can delete comments moderator editing mod.foo.canEditComment Can edit comments moderator moderating mod.foo.canModerateComment Can moderate comments","title":"English"},{"location":"view/languages/","text":"Languages # WoltLab Suite offers full i18n support with its integrated language system, including but not limited to dynamic phrases using template scripting and the built-in support for right-to-left languages. Phrases are deployed using the language package installation plugin, please also read the naming conventions for language items . Special Phrases # wcf.date.dateFormat # Many characters in the format have a special meaning and will be replaced with date fragments. If you want to include a literal character, you'll have to use the backslash \\ as an escape sequence to indicate that the character should be output as-is rather than being replaced. For example, Y-m-d will be output as 2018-03-30 , but \\Y-m-d will result in Y-03-30 . Defaults to M jS Y . The date format without time using PHP's format characters for the date() function. This value is also used inside the JavaScript implementation, where the characters are mapped to an equivalent representation. wcf.date.timeFormat # Defaults to g:i a . The date format that is used to represent a time, but not a date. Please see the explanation on wcf.date.dateFormat to learn more about the format characters. wcf.date.firstDayOfTheWeek # Defaults to 0 . Sets the first day of the week: * 0 - Sunday * 1 - Monday wcf.global.pageDirection - RTL support # Defaults to ltr . Changing this value to rtl will reverse the page direction and enable the right-to-left support for phrases. Additionally, a special version of the stylesheet is loaded that contains all necessary adjustments for the reverse direction.","title":"Languages"},{"location":"view/languages/#languages","text":"WoltLab Suite offers full i18n support with its integrated language system, including but not limited to dynamic phrases using template scripting and the built-in support for right-to-left languages. Phrases are deployed using the language package installation plugin, please also read the naming conventions for language items .","title":"Languages"},{"location":"view/languages/#special-phrases","text":"","title":"Special Phrases"},{"location":"view/languages/#wcfdatedateformat","text":"Many characters in the format have a special meaning and will be replaced with date fragments. If you want to include a literal character, you'll have to use the backslash \\ as an escape sequence to indicate that the character should be output as-is rather than being replaced. For example, Y-m-d will be output as 2018-03-30 , but \\Y-m-d will result in Y-03-30 . Defaults to M jS Y . The date format without time using PHP's format characters for the date() function. This value is also used inside the JavaScript implementation, where the characters are mapped to an equivalent representation.","title":"wcf.date.dateFormat"},{"location":"view/languages/#wcfdatetimeformat","text":"Defaults to g:i a . The date format that is used to represent a time, but not a date. Please see the explanation on wcf.date.dateFormat to learn more about the format characters.","title":"wcf.date.timeFormat"},{"location":"view/languages/#wcfdatefirstdayoftheweek","text":"Defaults to 0 . Sets the first day of the week: * 0 - Sunday * 1 - Monday","title":"wcf.date.firstDayOfTheWeek"},{"location":"view/languages/#wcfglobalpagedirection-rtl-support","text":"Defaults to ltr . Changing this value to rtl will reverse the page direction and enable the right-to-left support for phrases. Additionally, a special version of the stylesheet is loaded that contains all necessary adjustments for the reverse direction.","title":"wcf.global.pageDirection - RTL support"},{"location":"view/template-plugins/","text":"Template Plugins # 5.3+ anchor # The anchor template plugin creates a HTML elements. The easiest way to use the template plugin is to pass it an instance of ITitledLinkObject : 1 { anchor object = $object } generates the same output as 1 <a href=\" { $object -> getLink () } \"> { $object -> getTitle () } </a> Instead of an object parameter, a link and content parameter can be used: 1 { anchor link = $linkObject content = $content } where $linkObject implements ILinkableObject and $content is either an object implementing ITitledObject or having a __toString() method or $content is a string or a number. The last special attribute is append whose contents are appended to the href attribute of the generated anchor element. All of the other attributes matching ~^[a-z]+([A-z]+)+$~ , expect for href which is disallowed, are added as attributes to the anchor element. If an object attribute is present, the object also implements IPopoverObject and if the return value of IPopoverObject::getPopoverLinkClass() is included in the class attribute of the anchor tag, data-object-id is automatically added. This functionality makes it easy to generate links with popover support. Instead of 1 <a href=\" { $entry -> getLink () } \" class=\"blogEntryLink\" data-object-id=\" { @ $entry -> entryID } \"> { $entry -> subject } </a> using 1 { anchor object = $entry class = 'blogEntryLink' } is sufficient if Entry::getPopoverLinkClass() returns blogEntryLink . 5.3+ anchorAttributes # anchorAttributes compliments the StringUtil::getAnchorTagAttributes(string, bool): string method. It allows to easily generate the necessary attributes for an anchor tag based off the destination URL. 1 <a href=\"https://www.example.com\" { anchorAttributes url = 'https://www.example.com' appendHref = false appendClassname = true isUgc = true } > Attribute Description url destination URL appendHref whether the href attribute should be generated; true by default isUgc whether the rel=\"ugc\" attribute should be generated; false by default appendClassname whether the class=\"externalURL\" attribute should be generated; true by default append # If a string should be appended to the value of a variable, append can be used: 1 2 3 4 5 6 7 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } { append var = templateVariable value = '2' } { $templateVariable } { * now prints 'newValue2 * } If the variables does not exist yet, append creates a new one with the given value. If append is used on an array as the variable, the value is appended to all elements of the array. assign # New template variables can be declared and new values can be assigned to existing template variables using assign : 1 2 3 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } capture # In some situations, assign is not sufficient to assign values to variables in templates if the value is complex. Instead, capture can be used: 1 2 3 4 5 6 7 { capture var = templateVariable } { if $foo } <p> { $bar } </p> { else } <small> { $baz } </small> { /if } { /capture } concat # concat is a modifier used to concatenate multiple strings: 1 2 3 4 5 { assign var = foo value = 'foo' } { assign var = templateVariable value = 'bar' | concat : $foo } { $templateVariable } { * prints 'foobar * } counter # counter can be used to generate and optionally print a counter: 1 2 3 4 5 6 7 { counter name = fooCounter print = true } { * prints '1' * } { counter name = fooCounter print = true } { * prints '2' now * } { counter name = fooCounter } { * prints nothing, but counter value is '3' now internally * } { counter name = fooCounter print = true } { * prints '4' * } Counter supports the following attributes: Attribute Description assign optional name of the template variable the current counter value is assigned to direction counting direction, either up or down ; up by default name name of the counter, relevant if multiple counters are used simultaneously print if true , the current counter value is printed; false by default skip positive counting increment; 1 by default start start counter value; 1 by default 5.4+ csrfToken # {csrfToken} prints out the session's CSRF token (\u201cSecurity Token\u201d). 1 2 3 4 5 <form action=\" { link controller = \"Foo\" }{ /link } \" method=\"post\"> { * snip * } { csrfToken } </form> The {csrfToken} template plugin supports a type parameter. Specifying this parameter might be required in rare situations. Please check the implementation for details. currency # currency is a modifier used to format currency values with two decimals using language dependent thousands separators and decimal point: 1 2 3 { assign var = currencyValue value = 12.345 } { $currencyValue | currency } { * prints '12.34' * } cycle # cycle can be used to cycle between different values: 1 2 3 4 5 6 7 { cycle name = fooCycle values = 'bar,baz' } { * prints 'bar' * } { cycle name = fooCycle } { * prints 'baz' * } { cycle name = fooCycle advance = false } { * prints 'baz' again * } { cycle name = fooCycle } { * prints 'bar' * } The values attribute only has to be present for the first call. If cycle is used in a loop, the presence of the same values in consecutive calls has no effect. Only once the values change, the cycle is reset. Attribute Description advance if true , the current cycle value is advanced to the next value; true by default assign optional name of the template variable the current cycle value is assigned to; if used, print is set to false delimiter delimiter between the different cycle values; , by default name name of the cycle, relevant if multiple cycles are used simultaneously print if true , the current cycle value is printed, false by default reset if true , the current cycle value is set to the first value, false by default values string containing the different cycles values, also see delimiter date # date generated a formatted date using wcf\\util\\DateUtil::format() with DateUtil::DATE_FORMAT internally. 1 { $timestamp | date } 3.1+ dateInterval # dateInterval calculates the difference between two unix timestamps and generated a textual date interval. 1 { dateInterval start = $startTimestamp end = $endTimestamp full = true format = 'sentence' } Attribute Description end end of the time interval; current timestamp by default (though either start or end has to be set) format output format, either default , sentence , or plain ; defaults to default , see wcf\\util\\DateUtil::FORMAT_* constants full if true , full difference in minutes is shown; if false , only the longest time interval is shown; false by default start start of the time interval; current timestamp by default (though either start or end has to be set) encodeJS # encodeJS encodes a string to be used as a single-quoted string in JavaScript by replacing \\\\ with \\\\\\\\ , ' with \\' , linebreaks with \\n , and / with \\/ . 1 2 3 <script> var foo = ' { @ $foo | encodeJS } '; </script> escapeCDATA # escapeCDATA encodes a string to be used in a CDATA element by replacing ]]> with ]]]]><![CDATA[> . 1 <![CDATA[ { @ $foo | encodeCDATA } ]]> event # event provides extension points in templates that template listeners can use. 1 { event name = 'foo' } fetch # fetch fetches the contents of a file using file_get_contents . 1 2 3 { fetch file = 'foo.html' } { * prints the contents of `foo.html` * } { fetch file = 'bar.html' assign = bar } { * assigns the contents of `foo.html` to `$bar`; does not print the contents * } filesizeBinary # filesizeBinary formats the filesize using binary filesize (in bytes). 1 { $filesize | filesizeBinary } filesize # filesize formats the filesize using filesize (in bytes). 1 { $filesize | filesize } hascontent # In many cases, conditional statements can be used to determine if a certain section of a template is shown: 1 2 3 { if $foo === 'bar' } only shown if $foo is bar { /if } In some situations, however, such conditional statements are not sufficient. One prominent example is a template event: 1 2 3 4 5 6 7 8 9 { if $foo === 'bar' } <ul> { if $foo === 'bar' } <li>Bar</li> { /if } { event name = 'listItems' } </li> { /if } In this example, if $foo !== 'bar' , the list will not be shown, regardless of the additional template code provided by template listeners. In such a situation, hascontent has to be used: 1 2 3 4 5 6 7 8 9 10 11 { hascontent } <ul> { content } { if $foo === 'bar' } <li>Bar</li> { /if } { event name = 'listItems' } { /content } </ul> { /hascontent } If the part of the template wrapped in the content tags has any (trimmed) content, the part of the template wrapped by hascontent tags is shown (including the part wrapped by the content tags), otherwise nothing is shown. Thus, this construct avoids an empty list compared to the if solution above. Like foreach , hascontent also supports an else part: 1 2 3 4 5 6 7 8 9 { hascontent } <ul> { content } { * \u2026 * } { /content } </ul> { hascontentelse } no list { /hascontent } htmlCheckboxes # htmlCheckboxes generates a list of HTML checkboxes. 1 2 3 { htmlCheckboxes name = foo options = $fooOptions selected = $currentFoo } { htmlCheckboxes name = bar output = $barLabels values = $barValues selected = $currentBar } Attribute Description 5.2+ disabled if true , all checkboxes are disabled disableEncoding if true , the values are not passed through wcf\\util\\StringUtil::encodeHTML() ; false by default name name attribute of the input checkbox element output array used as keys and values for options if present; not present by default options array selectable options with the key used as value attribute and the value as the checkbox label selected current selected value(s) separator separator between the different checkboxes in the generated output; empty string by default values array with values used in combination with output , where output is only used as keys for options htmlOptions # htmlOptions generates an select HTML element. 1 2 3 4 5 6 { htmlOptions name = 'foo' options = $options selected = $selected } <select name=\"bar\"> <option value=\"\" { if ! $selected } selected { /if } > { lang } foo.bar.default { /lang } </option> { htmlOptions options = $options selected = $selected } { * no `name` attribute * } </select> Attribute Description disableEncoding if true , the values are not passed through wcf\\util\\StringUtil::encodeHTML() ; false by default object optional instance of wcf\\data\\DatabaseObjectList that provides the selectable options (overwrites options attribute internally) name name attribute of the select element; if not present, only the contents of the select element are printed output array used as keys and values for options if present; not present by default values array with values used in combination with output , where output is only used as keys for options options array selectable options with the key used as value attribute and the value as the option label; if a value is an array, an optgroup is generated with the array key as the optgroup label selected current selected value(s) All additional attributes are added as attributes of the select HTML element. implode # implodes transforms an array into a string and prints it. 1 { implode from = $array key = key item = item glue = \";\" }{ $key } : { $value }{ /implode } Attribute Description from array with the imploded values glue separator between the different array values; ', ' by default item template variable name where the current array value is stored during the iteration key optional template variable name where the current array key is stored during the iteration 5.2+ ipSearch # ipSearch generates a link to search for an IP address. 1 { \"127.0.0.1\" | ipSearch } js # js generates script tags based on whether ENABLE_DEBUG_MODE and VISITOR_USE_TINY_BUILD are enabled. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 { js application = 'wbb' file = 'WBB' } { * generates 'http://example.com/js/WBB.js' * } { js application = 'wcf' file = 'WCF.User' bundle = 'WCF.Combined' } { * generates 'http://example.com/wcf/js/WCF.User.js' if ENABLE_DEBUG_MODE=1 * } { * generates 'http://example.com/wcf/js/WCF.Combined.min.js' if ENABLE_DEBUG_MODE=0 * } { js application = 'wcf' lib = 'jquery' } { * generates 'http://example.com/wcf/js/3rdParty/jquery.js' * } { js application = 'wcf' lib = 'jquery-ui' file = 'awesomeWidget' } { * generates 'http://example.com/wcf/js/3rdParty/jquery-ui/awesomeWidget.js' * } { js application = 'wcf' file = 'WCF.User' bundle = 'WCF.Combined' hasTiny = true } { * generates 'http://example.com/wcf/js/WCF.User.js' if ENABLE_DEBUG_MODE=1 * } { * generates 'http://example.com/wcf/js/WCF.Combined.min.js' (ENABLE_DEBUG_MODE=0 * } { * generates 'http://example.com/wcf/js/WCF.Combined.tiny.min.js' if ENABLE_DEBUG_MODE=0 and VISITOR_USE_TINY_BUILD=1 * } 5.3+ jslang # jslang works like lang with the difference that the resulting string is automatically passed through encodeJS . 1 2 3 4 5 6 7 require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' , } ); // \u2026 } ); 5.5+ json # json JSON-encodes the given value. 1 2 3 <script> let data = { \"title\" : { @ $foo -> getTitle ()| json } } ; </script> lang # lang replaces a language items with its value. 1 2 3 4 5 6 7 { lang } foo.bar.baz { /lang } { lang __literal = true } foo.bar.baz { /lang } { lang foo = 'baz' } foo.bar.baz { /lang } { lang } foo.bar.baz. { $action }{ /lang } Attribute Description __encode if true , the output will be passed through StringUtil::encodeHTML() __literal if true , template variables will not resolved but printed as they are in the language item; false by default __optional if true and the language item does not exist, an empty string is printed; false by default All additional attributes are available when parsing the language item. language # language replaces a language items with its value. If the template variable __language exists, this language object will be used instead of WCF::getLanguage() . This modifier is useful when assigning the value directly to a variable. Note that template scripting is applied to the output of the variable, which can lead to unwanted side effects. Use phrase instead if you don't want to use template scripting. 1 2 3 { $languageItem | language } { assign var = foo value = $languageItem | language } link # link generates internal links using LinkHandler . 1 <a href=\" { link controller = 'FooList' application = 'bar' } param1=2¶m2=A { /link } \">Foo</a> Attribute Description application abbreviation of the application the controller belongs to; wcf by default controller name of the controller; if not present, the landing page is linked in the frontend and the index page in the ACP encode if true , the generated link is passed through wcf\\util\\StringUtil::encodeHTML() ; true by default isEmail sets encode=false and forces links to link to the frontend Additional attributes are passed to LinkHandler::getLink() . newlineToBreak # newlineToBreak transforms newlines into HTML <br> elements after encoding the content via wcf\\util\\StringUtil::encodeHTML() . 1 { $foo | newlineToBreak } 5.4+ objectAction # objectAction generates action buttons to be used in combination with the WoltLabSuite/Core/Ui/Object/Action API . For detailed information on its usage, we refer to the extensive documentation in the ObjectActionFunctionTemplatePlugin class itself. page # page generates an internal link to a CMS page. 1 2 3 4 5 6 7 { page } com.woltlab.wcf.CookiePolicy { /page } { page pageID = 1 }{ /page } { page language = 'de' } com.woltlab.wcf.CookiePolicy { /page } { page languageID = 2 } com.woltlab.wcf.CookiePolicy { /page } Attribute Description pageID unique id of the page (cannot be used together with a page identifier as value) languageID id of the page language (cannot be used together with language ) language language code of the page language (cannot be used together with languageID ) pages # pages generates a pagination. 1 2 3 { pages controller = 'FooList' link = \"pageNo=%d\" print = true assign = pagesLinks } { * prints pagination * } { @ $pagesLinks } { * prints same pagination again * } Attribute Description assign optional name of the template variable the pagination is assigned to controller controller name of the generated links link additional link parameter where %d will be replaced with the relevant page number pages maximum number of of pages; by default, the template variable $pages is used print if false and assign=true , the pagination is not printed application , id , object , title additional parameters passed to LinkHandler::getLink() to generate page links 5.5+ phrase # phrase replaces a language items with its value. If the template variable __language exists, this language object will be used instead of WCF::getLanguage() . This modifier is useful when assigning the value directly to a variable. phrase should be used instead of language unless you want to explicitly allow template scripting on a variable's output. 1 2 3 { $languageItem | phrase } { assign var = foo value = $languageItem | phrase } plainTime # plainTime formats a timestamp to include year, month, day, hour, and minutes. The exact formatting depends on the current language (via the language items wcf.date.dateTimeFormat , wcf.date.dateFormat , and wcf.date.timeFormat ). 1 { $timestamp | plainTime } 5.3+ plural # plural allows to easily select the correct plural form of a phrase based on a given value . The pluralization logic follows the Unicode Language Plural Rules for cardinal numbers. The # placeholder within the resulting phrase is replaced by the value . It is automatically formatted using StringUtil::formatNumeric . English: Note the use of 1 if the number ( # ) is not used within the phrase and the use of one otherwise. They are equivalent for English, but following this rule generalizes better to other languages, helping the translator. 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Hello { plural value = $numberOfWorlds 1 = 'World' other = 'Worlds' } !</h1> <p>There { plural value = $numberOfWorlds 1 = 'is one world' other = 'are # worlds' } !</p> <p>There { plural value = $numberOfWorlds one = 'is # world' other = 'are # worlds' } !</p> German: 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Hallo { plural value = $numberOfWorlds 1 = 'Welt' other = 'Welten' } !</h1> <p>Es gibt { plural value = $numberOfWorlds 1 = 'eine Welt' other = '# Welten' } !</p> <p>Es gibt { plural value = $numberOfWorlds one = '# Welt' other = '# Welten' } !</p> Romanian: Note the additional use of few which is not required in English or German. 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Salut { plural value = $numberOfWorlds 1 = 'lume' other = 'lumi' } !</h1> <p>Exist\u0103 { plural value = $numberOfWorlds 1 = 'o lume' few = '# lumi' other = '# de lumi' } !</p> <p>Exist\u0103 { plural value = $numberOfWorlds one = '# lume' few = '# lumi' other = '# de lumi' } !</p> Russian: Note the difference between 1 (exactly 1 ) and one (ending in 1 , except ending in 11 ). 1 2 3 { assign var = numberOfWorlds value = 2 } <h1>\u041f\u0440\u0438\u0432\u0435\u0442 { plural value = $numberOfWorld 1 = '\u043c\u0438\u0440' other = '\u043c\u0438\u0440\u044b' } !</h1> <p>\u0415\u0441\u0442\u044c { plural value = $numberOfWorlds 1 = '\u043c\u0438\u0440' one = '# \u043c\u0438\u0440' few = '# \u043c\u0438\u0440\u0430' many = '# \u043c\u0438\u0440\u043e\u0432' other = '# \u043c\u0438\u0440\u043e\u0432' } !</p> Attribute Description value The value that is used to select the proper phrase. other The phrase that is used when no other selector matches. Any Category Name The phrase that is used when value belongs to the named category. Available categories depend on the language. Any Integer The phrase that is used when value is that exact integer. prepend # If a string should be prepended to the value of a variable, prepend can be used: 1 2 3 4 5 6 7 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } { prepend var = templateVariable value = '2' } { $templateVariable } { * now prints '2newValue' * } If the variables does not exist yet, prepend creates a new one with the given value. If prepend is used on an array as the variable, the value is prepended to all elements of the array. shortUnit # shortUnit shortens numbers larger than 1000 by using unit suffixes: 1 2 { 10000 | shortUnit } { * prints 10k * } { 5400000 | shortUnit } { * prints 5.4M * } smallpages # smallpages generates a smaller version of pages by using adding the small CSS class to the generated <nav> element and only showing 7 instead of 9 links. tableWordwrap # tableWordwrap inserts zero width spaces every 30 characters in words longer than 30 characters. 1 { $foo | tableWordwrap } time # time generates an HTML time elements based on a timestamp that shows a relative time or the absolute time if the timestamp more than six days ago. 1 { $timestamp | time } { * prints a '<time>' element * } truncate # truncate truncates a long string into a shorter one: 1 2 3 { $foo | truncate : 35 } { $foo | truncate : 35 : '_' : true } Parameter Number Description 0 truncated string 1 truncated length; 80 by default 2 ellipsis symbol; wcf\\util\\StringUtil::HELLIP by default 3 if true , words can be broken up in the middle; false by default 5.3+ user # user generates links to user profiles. The mandatory object parameter requires an instances of UserProfile . The optional type parameter is responsible for what the generated link contains: type='default' (also applies if no type is given) outputs the formatted username relying on the \u201cUser Marking\u201d setting of the relevant user group. Additionally, the user popover card will be shown when hovering over the generated link. type='plain' outputs the username without additional formatting. type='avatar(\\d+)' outputs the user\u2019s avatar in the specified size, i.e., avatar48 outputs the avatar with a width and height of 48 pixels. The last special attribute is append whose contents are appended to the href attribute of the generated anchor element. All of the other attributes matching ~^[a-z]+([A-z]+)+$~ , except for href which may not be added, are added as attributes to the anchor element. Examples: 1 { user object = $user } generates 1 <a href=\" { $user -> getLink () } \" data-object-id=\" { $user -> userID } \" class=\"userLink\"> { @ $user -> getFormattedUsername () } </a> and 1 { user object = $user type = 'avatar48' foo = 'bar' } generates 1 <a href=\" { $user -> getLink () } \" foo=\"bar\"> { @ $object -> getAvatar ()-> getImageTag ( 48 ) } </a>","title":"Template Plugins"},{"location":"view/template-plugins/#template-plugins","text":"","title":"Template Plugins"},{"location":"view/template-plugins/#53-anchor","text":"The anchor template plugin creates a HTML elements. The easiest way to use the template plugin is to pass it an instance of ITitledLinkObject : 1 { anchor object = $object } generates the same output as 1 <a href=\" { $object -> getLink () } \"> { $object -> getTitle () } </a> Instead of an object parameter, a link and content parameter can be used: 1 { anchor link = $linkObject content = $content } where $linkObject implements ILinkableObject and $content is either an object implementing ITitledObject or having a __toString() method or $content is a string or a number. The last special attribute is append whose contents are appended to the href attribute of the generated anchor element. All of the other attributes matching ~^[a-z]+([A-z]+)+$~ , expect for href which is disallowed, are added as attributes to the anchor element. If an object attribute is present, the object also implements IPopoverObject and if the return value of IPopoverObject::getPopoverLinkClass() is included in the class attribute of the anchor tag, data-object-id is automatically added. This functionality makes it easy to generate links with popover support. Instead of 1 <a href=\" { $entry -> getLink () } \" class=\"blogEntryLink\" data-object-id=\" { @ $entry -> entryID } \"> { $entry -> subject } </a> using 1 { anchor object = $entry class = 'blogEntryLink' } is sufficient if Entry::getPopoverLinkClass() returns blogEntryLink .","title":"5.3+ anchor"},{"location":"view/template-plugins/#53-anchorattributes","text":"anchorAttributes compliments the StringUtil::getAnchorTagAttributes(string, bool): string method. It allows to easily generate the necessary attributes for an anchor tag based off the destination URL. 1 <a href=\"https://www.example.com\" { anchorAttributes url = 'https://www.example.com' appendHref = false appendClassname = true isUgc = true } > Attribute Description url destination URL appendHref whether the href attribute should be generated; true by default isUgc whether the rel=\"ugc\" attribute should be generated; false by default appendClassname whether the class=\"externalURL\" attribute should be generated; true by default","title":"5.3+ anchorAttributes"},{"location":"view/template-plugins/#append","text":"If a string should be appended to the value of a variable, append can be used: 1 2 3 4 5 6 7 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } { append var = templateVariable value = '2' } { $templateVariable } { * now prints 'newValue2 * } If the variables does not exist yet, append creates a new one with the given value. If append is used on an array as the variable, the value is appended to all elements of the array.","title":"append"},{"location":"view/template-plugins/#assign","text":"New template variables can be declared and new values can be assigned to existing template variables using assign : 1 2 3 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * }","title":"assign"},{"location":"view/template-plugins/#capture","text":"In some situations, assign is not sufficient to assign values to variables in templates if the value is complex. Instead, capture can be used: 1 2 3 4 5 6 7 { capture var = templateVariable } { if $foo } <p> { $bar } </p> { else } <small> { $baz } </small> { /if } { /capture }","title":"capture"},{"location":"view/template-plugins/#concat","text":"concat is a modifier used to concatenate multiple strings: 1 2 3 4 5 { assign var = foo value = 'foo' } { assign var = templateVariable value = 'bar' | concat : $foo } { $templateVariable } { * prints 'foobar * }","title":"concat"},{"location":"view/template-plugins/#counter","text":"counter can be used to generate and optionally print a counter: 1 2 3 4 5 6 7 { counter name = fooCounter print = true } { * prints '1' * } { counter name = fooCounter print = true } { * prints '2' now * } { counter name = fooCounter } { * prints nothing, but counter value is '3' now internally * } { counter name = fooCounter print = true } { * prints '4' * } Counter supports the following attributes: Attribute Description assign optional name of the template variable the current counter value is assigned to direction counting direction, either up or down ; up by default name name of the counter, relevant if multiple counters are used simultaneously print if true , the current counter value is printed; false by default skip positive counting increment; 1 by default start start counter value; 1 by default","title":"counter"},{"location":"view/template-plugins/#54-csrftoken","text":"{csrfToken} prints out the session's CSRF token (\u201cSecurity Token\u201d). 1 2 3 4 5 <form action=\" { link controller = \"Foo\" }{ /link } \" method=\"post\"> { * snip * } { csrfToken } </form> The {csrfToken} template plugin supports a type parameter. Specifying this parameter might be required in rare situations. Please check the implementation for details.","title":"5.4+ csrfToken"},{"location":"view/template-plugins/#currency","text":"currency is a modifier used to format currency values with two decimals using language dependent thousands separators and decimal point: 1 2 3 { assign var = currencyValue value = 12.345 } { $currencyValue | currency } { * prints '12.34' * }","title":"currency"},{"location":"view/template-plugins/#cycle","text":"cycle can be used to cycle between different values: 1 2 3 4 5 6 7 { cycle name = fooCycle values = 'bar,baz' } { * prints 'bar' * } { cycle name = fooCycle } { * prints 'baz' * } { cycle name = fooCycle advance = false } { * prints 'baz' again * } { cycle name = fooCycle } { * prints 'bar' * } The values attribute only has to be present for the first call. If cycle is used in a loop, the presence of the same values in consecutive calls has no effect. Only once the values change, the cycle is reset. Attribute Description advance if true , the current cycle value is advanced to the next value; true by default assign optional name of the template variable the current cycle value is assigned to; if used, print is set to false delimiter delimiter between the different cycle values; , by default name name of the cycle, relevant if multiple cycles are used simultaneously print if true , the current cycle value is printed, false by default reset if true , the current cycle value is set to the first value, false by default values string containing the different cycles values, also see delimiter","title":"cycle"},{"location":"view/template-plugins/#date","text":"date generated a formatted date using wcf\\util\\DateUtil::format() with DateUtil::DATE_FORMAT internally. 1 { $timestamp | date }","title":"date"},{"location":"view/template-plugins/#31-dateinterval","text":"dateInterval calculates the difference between two unix timestamps and generated a textual date interval. 1 { dateInterval start = $startTimestamp end = $endTimestamp full = true format = 'sentence' } Attribute Description end end of the time interval; current timestamp by default (though either start or end has to be set) format output format, either default , sentence , or plain ; defaults to default , see wcf\\util\\DateUtil::FORMAT_* constants full if true , full difference in minutes is shown; if false , only the longest time interval is shown; false by default start start of the time interval; current timestamp by default (though either start or end has to be set)","title":"3.1+ dateInterval"},{"location":"view/template-plugins/#encodejs","text":"encodeJS encodes a string to be used as a single-quoted string in JavaScript by replacing \\\\ with \\\\\\\\ , ' with \\' , linebreaks with \\n , and / with \\/ . 1 2 3 <script> var foo = ' { @ $foo | encodeJS } '; </script>","title":"encodeJS"},{"location":"view/template-plugins/#escapecdata","text":"escapeCDATA encodes a string to be used in a CDATA element by replacing ]]> with ]]]]><![CDATA[> . 1 <![CDATA[ { @ $foo | encodeCDATA } ]]>","title":"escapeCDATA"},{"location":"view/template-plugins/#event","text":"event provides extension points in templates that template listeners can use. 1 { event name = 'foo' }","title":"event"},{"location":"view/template-plugins/#fetch","text":"fetch fetches the contents of a file using file_get_contents . 1 2 3 { fetch file = 'foo.html' } { * prints the contents of `foo.html` * } { fetch file = 'bar.html' assign = bar } { * assigns the contents of `foo.html` to `$bar`; does not print the contents * }","title":"fetch"},{"location":"view/template-plugins/#filesizebinary","text":"filesizeBinary formats the filesize using binary filesize (in bytes). 1 { $filesize | filesizeBinary }","title":"filesizeBinary"},{"location":"view/template-plugins/#filesize","text":"filesize formats the filesize using filesize (in bytes). 1 { $filesize | filesize }","title":"filesize"},{"location":"view/template-plugins/#hascontent","text":"In many cases, conditional statements can be used to determine if a certain section of a template is shown: 1 2 3 { if $foo === 'bar' } only shown if $foo is bar { /if } In some situations, however, such conditional statements are not sufficient. One prominent example is a template event: 1 2 3 4 5 6 7 8 9 { if $foo === 'bar' } <ul> { if $foo === 'bar' } <li>Bar</li> { /if } { event name = 'listItems' } </li> { /if } In this example, if $foo !== 'bar' , the list will not be shown, regardless of the additional template code provided by template listeners. In such a situation, hascontent has to be used: 1 2 3 4 5 6 7 8 9 10 11 { hascontent } <ul> { content } { if $foo === 'bar' } <li>Bar</li> { /if } { event name = 'listItems' } { /content } </ul> { /hascontent } If the part of the template wrapped in the content tags has any (trimmed) content, the part of the template wrapped by hascontent tags is shown (including the part wrapped by the content tags), otherwise nothing is shown. Thus, this construct avoids an empty list compared to the if solution above. Like foreach , hascontent also supports an else part: 1 2 3 4 5 6 7 8 9 { hascontent } <ul> { content } { * \u2026 * } { /content } </ul> { hascontentelse } no list { /hascontent }","title":"hascontent"},{"location":"view/template-plugins/#htmlcheckboxes","text":"htmlCheckboxes generates a list of HTML checkboxes. 1 2 3 { htmlCheckboxes name = foo options = $fooOptions selected = $currentFoo } { htmlCheckboxes name = bar output = $barLabels values = $barValues selected = $currentBar } Attribute Description 5.2+ disabled if true , all checkboxes are disabled disableEncoding if true , the values are not passed through wcf\\util\\StringUtil::encodeHTML() ; false by default name name attribute of the input checkbox element output array used as keys and values for options if present; not present by default options array selectable options with the key used as value attribute and the value as the checkbox label selected current selected value(s) separator separator between the different checkboxes in the generated output; empty string by default values array with values used in combination with output , where output is only used as keys for options","title":"htmlCheckboxes"},{"location":"view/template-plugins/#htmloptions","text":"htmlOptions generates an select HTML element. 1 2 3 4 5 6 { htmlOptions name = 'foo' options = $options selected = $selected } <select name=\"bar\"> <option value=\"\" { if ! $selected } selected { /if } > { lang } foo.bar.default { /lang } </option> { htmlOptions options = $options selected = $selected } { * no `name` attribute * } </select> Attribute Description disableEncoding if true , the values are not passed through wcf\\util\\StringUtil::encodeHTML() ; false by default object optional instance of wcf\\data\\DatabaseObjectList that provides the selectable options (overwrites options attribute internally) name name attribute of the select element; if not present, only the contents of the select element are printed output array used as keys and values for options if present; not present by default values array with values used in combination with output , where output is only used as keys for options options array selectable options with the key used as value attribute and the value as the option label; if a value is an array, an optgroup is generated with the array key as the optgroup label selected current selected value(s) All additional attributes are added as attributes of the select HTML element.","title":"htmlOptions"},{"location":"view/template-plugins/#implode","text":"implodes transforms an array into a string and prints it. 1 { implode from = $array key = key item = item glue = \";\" }{ $key } : { $value }{ /implode } Attribute Description from array with the imploded values glue separator between the different array values; ', ' by default item template variable name where the current array value is stored during the iteration key optional template variable name where the current array key is stored during the iteration","title":"implode"},{"location":"view/template-plugins/#52-ipsearch","text":"ipSearch generates a link to search for an IP address. 1 { \"127.0.0.1\" | ipSearch }","title":"5.2+ ipSearch"},{"location":"view/template-plugins/#js","text":"js generates script tags based on whether ENABLE_DEBUG_MODE and VISITOR_USE_TINY_BUILD are enabled. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 { js application = 'wbb' file = 'WBB' } { * generates 'http://example.com/js/WBB.js' * } { js application = 'wcf' file = 'WCF.User' bundle = 'WCF.Combined' } { * generates 'http://example.com/wcf/js/WCF.User.js' if ENABLE_DEBUG_MODE=1 * } { * generates 'http://example.com/wcf/js/WCF.Combined.min.js' if ENABLE_DEBUG_MODE=0 * } { js application = 'wcf' lib = 'jquery' } { * generates 'http://example.com/wcf/js/3rdParty/jquery.js' * } { js application = 'wcf' lib = 'jquery-ui' file = 'awesomeWidget' } { * generates 'http://example.com/wcf/js/3rdParty/jquery-ui/awesomeWidget.js' * } { js application = 'wcf' file = 'WCF.User' bundle = 'WCF.Combined' hasTiny = true } { * generates 'http://example.com/wcf/js/WCF.User.js' if ENABLE_DEBUG_MODE=1 * } { * generates 'http://example.com/wcf/js/WCF.Combined.min.js' (ENABLE_DEBUG_MODE=0 * } { * generates 'http://example.com/wcf/js/WCF.Combined.tiny.min.js' if ENABLE_DEBUG_MODE=0 and VISITOR_USE_TINY_BUILD=1 * }","title":"js"},{"location":"view/template-plugins/#53-jslang","text":"jslang works like lang with the difference that the resulting string is automatically passed through encodeJS . 1 2 3 4 5 6 7 require(['Language', /* \u2026 */], function(Language, /* \u2026 */) { Language . addObject ( { 'app.foo.bar' : '{jslang}app.foo.bar{/jslang}' , } ); // \u2026 } );","title":"5.3+ jslang"},{"location":"view/template-plugins/#55-json","text":"json JSON-encodes the given value. 1 2 3 <script> let data = { \"title\" : { @ $foo -> getTitle ()| json } } ; </script>","title":"5.5+ json"},{"location":"view/template-plugins/#lang","text":"lang replaces a language items with its value. 1 2 3 4 5 6 7 { lang } foo.bar.baz { /lang } { lang __literal = true } foo.bar.baz { /lang } { lang foo = 'baz' } foo.bar.baz { /lang } { lang } foo.bar.baz. { $action }{ /lang } Attribute Description __encode if true , the output will be passed through StringUtil::encodeHTML() __literal if true , template variables will not resolved but printed as they are in the language item; false by default __optional if true and the language item does not exist, an empty string is printed; false by default All additional attributes are available when parsing the language item.","title":"lang"},{"location":"view/template-plugins/#language","text":"language replaces a language items with its value. If the template variable __language exists, this language object will be used instead of WCF::getLanguage() . This modifier is useful when assigning the value directly to a variable. Note that template scripting is applied to the output of the variable, which can lead to unwanted side effects. Use phrase instead if you don't want to use template scripting. 1 2 3 { $languageItem | language } { assign var = foo value = $languageItem | language }","title":"language"},{"location":"view/template-plugins/#link","text":"link generates internal links using LinkHandler . 1 <a href=\" { link controller = 'FooList' application = 'bar' } param1=2¶m2=A { /link } \">Foo</a> Attribute Description application abbreviation of the application the controller belongs to; wcf by default controller name of the controller; if not present, the landing page is linked in the frontend and the index page in the ACP encode if true , the generated link is passed through wcf\\util\\StringUtil::encodeHTML() ; true by default isEmail sets encode=false and forces links to link to the frontend Additional attributes are passed to LinkHandler::getLink() .","title":"link"},{"location":"view/template-plugins/#newlinetobreak","text":"newlineToBreak transforms newlines into HTML <br> elements after encoding the content via wcf\\util\\StringUtil::encodeHTML() . 1 { $foo | newlineToBreak }","title":"newlineToBreak"},{"location":"view/template-plugins/#54-objectaction","text":"objectAction generates action buttons to be used in combination with the WoltLabSuite/Core/Ui/Object/Action API . For detailed information on its usage, we refer to the extensive documentation in the ObjectActionFunctionTemplatePlugin class itself.","title":"5.4+ objectAction"},{"location":"view/template-plugins/#page","text":"page generates an internal link to a CMS page. 1 2 3 4 5 6 7 { page } com.woltlab.wcf.CookiePolicy { /page } { page pageID = 1 }{ /page } { page language = 'de' } com.woltlab.wcf.CookiePolicy { /page } { page languageID = 2 } com.woltlab.wcf.CookiePolicy { /page } Attribute Description pageID unique id of the page (cannot be used together with a page identifier as value) languageID id of the page language (cannot be used together with language ) language language code of the page language (cannot be used together with languageID )","title":"page"},{"location":"view/template-plugins/#pages","text":"pages generates a pagination. 1 2 3 { pages controller = 'FooList' link = \"pageNo=%d\" print = true assign = pagesLinks } { * prints pagination * } { @ $pagesLinks } { * prints same pagination again * } Attribute Description assign optional name of the template variable the pagination is assigned to controller controller name of the generated links link additional link parameter where %d will be replaced with the relevant page number pages maximum number of of pages; by default, the template variable $pages is used print if false and assign=true , the pagination is not printed application , id , object , title additional parameters passed to LinkHandler::getLink() to generate page links","title":"pages"},{"location":"view/template-plugins/#55-phrase","text":"phrase replaces a language items with its value. If the template variable __language exists, this language object will be used instead of WCF::getLanguage() . This modifier is useful when assigning the value directly to a variable. phrase should be used instead of language unless you want to explicitly allow template scripting on a variable's output. 1 2 3 { $languageItem | phrase } { assign var = foo value = $languageItem | phrase }","title":"5.5+ phrase"},{"location":"view/template-plugins/#plaintime","text":"plainTime formats a timestamp to include year, month, day, hour, and minutes. The exact formatting depends on the current language (via the language items wcf.date.dateTimeFormat , wcf.date.dateFormat , and wcf.date.timeFormat ). 1 { $timestamp | plainTime }","title":"plainTime"},{"location":"view/template-plugins/#53-plural","text":"plural allows to easily select the correct plural form of a phrase based on a given value . The pluralization logic follows the Unicode Language Plural Rules for cardinal numbers. The # placeholder within the resulting phrase is replaced by the value . It is automatically formatted using StringUtil::formatNumeric . English: Note the use of 1 if the number ( # ) is not used within the phrase and the use of one otherwise. They are equivalent for English, but following this rule generalizes better to other languages, helping the translator. 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Hello { plural value = $numberOfWorlds 1 = 'World' other = 'Worlds' } !</h1> <p>There { plural value = $numberOfWorlds 1 = 'is one world' other = 'are # worlds' } !</p> <p>There { plural value = $numberOfWorlds one = 'is # world' other = 'are # worlds' } !</p> German: 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Hallo { plural value = $numberOfWorlds 1 = 'Welt' other = 'Welten' } !</h1> <p>Es gibt { plural value = $numberOfWorlds 1 = 'eine Welt' other = '# Welten' } !</p> <p>Es gibt { plural value = $numberOfWorlds one = '# Welt' other = '# Welten' } !</p> Romanian: Note the additional use of few which is not required in English or German. 1 2 3 4 { assign var = numberOfWorlds value = 2 } <h1>Salut { plural value = $numberOfWorlds 1 = 'lume' other = 'lumi' } !</h1> <p>Exist\u0103 { plural value = $numberOfWorlds 1 = 'o lume' few = '# lumi' other = '# de lumi' } !</p> <p>Exist\u0103 { plural value = $numberOfWorlds one = '# lume' few = '# lumi' other = '# de lumi' } !</p> Russian: Note the difference between 1 (exactly 1 ) and one (ending in 1 , except ending in 11 ). 1 2 3 { assign var = numberOfWorlds value = 2 } <h1>\u041f\u0440\u0438\u0432\u0435\u0442 { plural value = $numberOfWorld 1 = '\u043c\u0438\u0440' other = '\u043c\u0438\u0440\u044b' } !</h1> <p>\u0415\u0441\u0442\u044c { plural value = $numberOfWorlds 1 = '\u043c\u0438\u0440' one = '# \u043c\u0438\u0440' few = '# \u043c\u0438\u0440\u0430' many = '# \u043c\u0438\u0440\u043e\u0432' other = '# \u043c\u0438\u0440\u043e\u0432' } !</p> Attribute Description value The value that is used to select the proper phrase. other The phrase that is used when no other selector matches. Any Category Name The phrase that is used when value belongs to the named category. Available categories depend on the language. Any Integer The phrase that is used when value is that exact integer.","title":"5.3+ plural"},{"location":"view/template-plugins/#prepend","text":"If a string should be prepended to the value of a variable, prepend can be used: 1 2 3 4 5 6 7 { assign var = templateVariable value = 'newValue' } { $templateVariable } { * prints 'newValue * } { prepend var = templateVariable value = '2' } { $templateVariable } { * now prints '2newValue' * } If the variables does not exist yet, prepend creates a new one with the given value. If prepend is used on an array as the variable, the value is prepended to all elements of the array.","title":"prepend"},{"location":"view/template-plugins/#shortunit","text":"shortUnit shortens numbers larger than 1000 by using unit suffixes: 1 2 { 10000 | shortUnit } { * prints 10k * } { 5400000 | shortUnit } { * prints 5.4M * }","title":"shortUnit"},{"location":"view/template-plugins/#smallpages","text":"smallpages generates a smaller version of pages by using adding the small CSS class to the generated <nav> element and only showing 7 instead of 9 links.","title":"smallpages"},{"location":"view/template-plugins/#tablewordwrap","text":"tableWordwrap inserts zero width spaces every 30 characters in words longer than 30 characters. 1 { $foo | tableWordwrap }","title":"tableWordwrap"},{"location":"view/template-plugins/#time","text":"time generates an HTML time elements based on a timestamp that shows a relative time or the absolute time if the timestamp more than six days ago. 1 { $timestamp | time } { * prints a '<time>' element * }","title":"time"},{"location":"view/template-plugins/#truncate","text":"truncate truncates a long string into a shorter one: 1 2 3 { $foo | truncate : 35 } { $foo | truncate : 35 : '_' : true } Parameter Number Description 0 truncated string 1 truncated length; 80 by default 2 ellipsis symbol; wcf\\util\\StringUtil::HELLIP by default 3 if true , words can be broken up in the middle; false by default","title":"truncate"},{"location":"view/template-plugins/#53-user","text":"user generates links to user profiles. The mandatory object parameter requires an instances of UserProfile . The optional type parameter is responsible for what the generated link contains: type='default' (also applies if no type is given) outputs the formatted username relying on the \u201cUser Marking\u201d setting of the relevant user group. Additionally, the user popover card will be shown when hovering over the generated link. type='plain' outputs the username without additional formatting. type='avatar(\\d+)' outputs the user\u2019s avatar in the specified size, i.e., avatar48 outputs the avatar with a width and height of 48 pixels. The last special attribute is append whose contents are appended to the href attribute of the generated anchor element. All of the other attributes matching ~^[a-z]+([A-z]+)+$~ , except for href which may not be added, are added as attributes to the anchor element. Examples: 1 { user object = $user } generates 1 <a href=\" { $user -> getLink () } \" data-object-id=\" { $user -> userID } \" class=\"userLink\"> { @ $user -> getFormattedUsername () } </a> and 1 { user object = $user type = 'avatar48' foo = 'bar' } generates 1 <a href=\" { $user -> getLink () } \" foo=\"bar\"> { @ $object -> getAvatar ()-> getImageTag ( 48 ) } </a>","title":"5.3+ user"},{"location":"view/templates/","text":"Templates # Templates are responsible for the output a user sees when requesting a page (while the PHP code is responsible for providing the data that will be shown). Templates are text files with .tpl as the file extension. WoltLab Suite Core compiles the template files once into a PHP file that is executed when a user requests the page. In subsequent request, as the PHP file containing the compiled template already exists, compiling the template is not necessary anymore. Template Types and Conventions # WoltLab Suite Core supports two types of templates: frontend templates (or simply templates ) and backend templates ( ACP templates ). Each type of template is only available in its respective domain, thus frontend templates cannot be included or used in the ACP and vice versa. For pages and forms, the name of the template matches the unqualified name of the PHP class except for the Page or Form suffix: RegisterForm.class.php \u2192 register.tpl UserPage.class.php \u2192 user.tpl If you follow this convention, WoltLab Suite Core will automatically determine the template name so that you do not have to explicitly set it. For forms that handle creating and editing objects, in general, there are two form classes: FooAddForm and FooEditForm . WoltLab Suite Core, however, generally only uses one template fooAdd.tpl and the template variable $action to distinguish between creating a new object ( $action = 'add' ) and editing an existing object ( $action = 'edit' ) as the differences between templates for adding and editing an object are minimal. Installing Templates # Templates and ACP templates are installed by two different package installation plugins: the template PIP and the ACP template PIP . More information about installing templates can be found on those pages. Base Templates # Frontend # 1 2 3 4 5 { include file = 'header' } { * content * } { include file = 'footer' } Backend # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'foo.bar.baz' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\">Title</h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> { * your default content header navigation buttons * } { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { * content * } { include file = 'footer' } foo.bar.baz is the language item that contains the title of the page. Common Template Components # Forms # For new forms, use the new form builder API introduced with WoltLab Suite 5.2. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <form method=\"post\" action=\" { link controller = 'FooBar' }{ /link } \"> <div class=\"section\"> <dl { if $errorField == 'baz' } class=\"formError\" { /if } > <dt><label for=\"baz\"> { lang } foo.bar.baz { /lang } </label></dt> <dd> <input type=\"text\" id=\"baz\" name=\"baz\" value=\" { $baz } \" class=\"long\" required autofocus> { if $errorField == 'baz' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } foo.bar.baz.error. { @ $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> <dl> <dt><label for=\"bar\"> { lang } foo.bar.bar { /lang } </label></dt> <dd> <textarea name=\"bar\" id=\"bar\" cols=\"40\" rows=\"10\"> { $bar } </textarea> { if $errorField == 'bar' } <small class=\"innerError\"> { lang } foo.bar.bar.error. { @ $errorType }{ /lang } </small> { /if } </dd> </dl> { * other fields * } { event name = 'dataFields' } </div> { * other sections * } { event name = 'sections' } <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> { csrfToken } </div> </form> Tab Menus # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <div class=\"section tabMenuContainer\"> <nav class=\"tabMenu\"> <ul> <li><a href=\"#tab1\">Tab 1</a></li> <li><a href=\"#tab2\">Tab 2</a></li> { event name = 'tabMenuTabs' } </ul> </nav> <div id=\"tab1\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of first tab * } </div> </div> <div id=\"tab2\" class=\"tabMenuContainer tabMenuContent\"> <nav class=\"menu\"> <ul> <li><a href=\"#tab2A\">Tab 2A</a></li> <li><a href=\"#tab2B\">Tab 2B</a></li> { event name = 'tabMenuTab2Subtabs' } </ul> </nav> <div id=\"tab2A\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of first subtab for second tab * } </div> </div> <div id=\"tab2B\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of second subtab for second tab * } </div> </div> { event name = 'tabMenuTab2Contents' } </div> { event name = 'tabMenuContents' } </div> Template Scripting # Template Variables # Template variables can be assigned via WCF::getTPL()->assign('foo', 'bar') and accessed in templates via $foo : {$foo} will result in the contents of $foo to be passed to StringUtil::encodeHTML() before being printed. {#$foo} will result in the contents of $foo to be passed to StringUtil::formatNumeric() before being printed. Thus, this method is relevant when printing numbers and having them formatted correctly according the the user\u2019s language. {@$foo} will result in the contents of $foo to be printed directly. In general, this method should not be used for user-generated input. Multiple template variables can be assigned by passing an array: 1 2 3 4 WCF :: getTPL () -> assign ([ 'foo' => 'bar' , 'baz' => false ]); Modifiers # If you want to call a function on a variable, you can use the modifier syntax: {@$foo|trim} , for example, results in the trimmed contents of $foo to be printed. System Template Variable # The template variable $tpl is automatically assigned and is an array containing different data: $tpl[get] contains $_GET . $tpl[post] contains $_POST . $tpl[cookie] contains $_COOKIE . $tpl[server] contains $_SERVER . $tpl[env] contains $_ENV . $tpl[now] contains TIME_NOW (current timestamp). Furthermore, the following template variables are also automatically assigned: $__wcf contains the WCF object (or WCFACP object in the backend). Comments # Comments are wrapped in {* and *} and can span multiple lines: 1 2 { * some comment * } The template compiler discards the comments, so that they not included in the compiled template. Conditions # Conditions follow a similar syntax to PHP code: 1 2 3 4 5 6 7 { if $foo === 'bar' } foo is bar { elseif $foo === 'baz' } foo is baz { else } foo is neither bar nor baz { /if } The supported operators in conditions are === , !== , == , != , <= , < , >= , > , || , && , ! , and = . More examples: 1 2 3 { if $bar | isset } \u2026 { /if } { if $bar | count > 3 && $bar | count < 100 } \u2026 { /if } Foreach Loops # Foreach loops allow to iterate over arrays or iterable objects: 1 2 3 4 5 <ul> { foreach from = $array key = key item = value } <li> { $key } : { $value } </li> { /foreach } </ul> While the from attribute containing the iterated structure and the item attribute containg the current value are mandatory, the key attribute is optional. If the foreach loop has a name assigned to it via the name attribute, the $tpl template variable provides additional data about the loop: 1 2 3 4 5 6 7 8 9 10 11 <ul> { foreach from = $array key = key item = value name = foo } { if $tpl [ foreach ][ foo ][ first ] } something special for the first iteration { elseif $tpl [ foreach ][ foo ][ last ] } something special for the last iteration { /if } <li>iteration { # $tpl [ foreach ][ foo ][ iteration ]+ 1 } out of { # $tpl [ foreach ][ foo ][ total ] } { $key } : { $value } </li> { /foreach } </ul> In contrast to PHP\u2019s foreach loop, templates also support foreachelse : 1 2 3 4 5 { foreach from = $array item = value } \u2026 { foreachelse } there is nothing to iterate over { /foreach } Including Other Templates # To include template named foo from the same domain (frontend/backend), you can use 1 { include file = 'foo' } If the template belongs to an application, you have to specify that application using the application attribute: 1 { include file = 'foo' application = 'app' } Additional template variables can be passed to the included template as additional attributes: 1 { include file = 'foo' application = 'app' var1 = 'foo1' var2 = 'foo2' } Template Plugins # An overview of all available template plugins can be found here .","title":"Templates"},{"location":"view/templates/#templates","text":"Templates are responsible for the output a user sees when requesting a page (while the PHP code is responsible for providing the data that will be shown). Templates are text files with .tpl as the file extension. WoltLab Suite Core compiles the template files once into a PHP file that is executed when a user requests the page. In subsequent request, as the PHP file containing the compiled template already exists, compiling the template is not necessary anymore.","title":"Templates"},{"location":"view/templates/#template-types-and-conventions","text":"WoltLab Suite Core supports two types of templates: frontend templates (or simply templates ) and backend templates ( ACP templates ). Each type of template is only available in its respective domain, thus frontend templates cannot be included or used in the ACP and vice versa. For pages and forms, the name of the template matches the unqualified name of the PHP class except for the Page or Form suffix: RegisterForm.class.php \u2192 register.tpl UserPage.class.php \u2192 user.tpl If you follow this convention, WoltLab Suite Core will automatically determine the template name so that you do not have to explicitly set it. For forms that handle creating and editing objects, in general, there are two form classes: FooAddForm and FooEditForm . WoltLab Suite Core, however, generally only uses one template fooAdd.tpl and the template variable $action to distinguish between creating a new object ( $action = 'add' ) and editing an existing object ( $action = 'edit' ) as the differences between templates for adding and editing an object are minimal.","title":"Template Types and Conventions"},{"location":"view/templates/#installing-templates","text":"Templates and ACP templates are installed by two different package installation plugins: the template PIP and the ACP template PIP . More information about installing templates can be found on those pages.","title":"Installing Templates"},{"location":"view/templates/#base-templates","text":"","title":"Base Templates"},{"location":"view/templates/#frontend","text":"1 2 3 4 5 { include file = 'header' } { * content * } { include file = 'footer' }","title":"Frontend"},{"location":"view/templates/#backend","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { include file = 'header' pageTitle = 'foo.bar.baz' } <header class=\"contentHeader\"> <div class=\"contentHeaderTitle\"> <h1 class=\"contentTitle\">Title</h1> </div> <nav class=\"contentHeaderNavigation\"> <ul> { * your default content header navigation buttons * } { event name = 'contentHeaderNavigation' } </ul> </nav> </header> { * content * } { include file = 'footer' } foo.bar.baz is the language item that contains the title of the page.","title":"Backend"},{"location":"view/templates/#common-template-components","text":"","title":"Common Template Components"},{"location":"view/templates/#forms","text":"For new forms, use the new form builder API introduced with WoltLab Suite 5.2. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <form method=\"post\" action=\" { link controller = 'FooBar' }{ /link } \"> <div class=\"section\"> <dl { if $errorField == 'baz' } class=\"formError\" { /if } > <dt><label for=\"baz\"> { lang } foo.bar.baz { /lang } </label></dt> <dd> <input type=\"text\" id=\"baz\" name=\"baz\" value=\" { $baz } \" class=\"long\" required autofocus> { if $errorField == 'baz' } <small class=\"innerError\"> { if $errorType == 'empty' } { lang } wcf.global.form.error.empty { /lang } { else } { lang } foo.bar.baz.error. { @ $errorType }{ /lang } { /if } </small> { /if } </dd> </dl> <dl> <dt><label for=\"bar\"> { lang } foo.bar.bar { /lang } </label></dt> <dd> <textarea name=\"bar\" id=\"bar\" cols=\"40\" rows=\"10\"> { $bar } </textarea> { if $errorField == 'bar' } <small class=\"innerError\"> { lang } foo.bar.bar.error. { @ $errorType }{ /lang } </small> { /if } </dd> </dl> { * other fields * } { event name = 'dataFields' } </div> { * other sections * } { event name = 'sections' } <div class=\"formSubmit\"> <input type=\"submit\" value=\" { lang } wcf.global.button.submit { /lang } \" accesskey=\"s\"> { csrfToken } </div> </form>","title":"Forms"},{"location":"view/templates/#tab-menus","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <div class=\"section tabMenuContainer\"> <nav class=\"tabMenu\"> <ul> <li><a href=\"#tab1\">Tab 1</a></li> <li><a href=\"#tab2\">Tab 2</a></li> { event name = 'tabMenuTabs' } </ul> </nav> <div id=\"tab1\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of first tab * } </div> </div> <div id=\"tab2\" class=\"tabMenuContainer tabMenuContent\"> <nav class=\"menu\"> <ul> <li><a href=\"#tab2A\">Tab 2A</a></li> <li><a href=\"#tab2B\">Tab 2B</a></li> { event name = 'tabMenuTab2Subtabs' } </ul> </nav> <div id=\"tab2A\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of first subtab for second tab * } </div> </div> <div id=\"tab2B\" class=\"tabMenuContent\"> <div class=\"section\"> { * contents of second subtab for second tab * } </div> </div> { event name = 'tabMenuTab2Contents' } </div> { event name = 'tabMenuContents' } </div>","title":"Tab Menus"},{"location":"view/templates/#template-scripting","text":"","title":"Template Scripting"},{"location":"view/templates/#template-variables","text":"Template variables can be assigned via WCF::getTPL()->assign('foo', 'bar') and accessed in templates via $foo : {$foo} will result in the contents of $foo to be passed to StringUtil::encodeHTML() before being printed. {#$foo} will result in the contents of $foo to be passed to StringUtil::formatNumeric() before being printed. Thus, this method is relevant when printing numbers and having them formatted correctly according the the user\u2019s language. {@$foo} will result in the contents of $foo to be printed directly. In general, this method should not be used for user-generated input. Multiple template variables can be assigned by passing an array: 1 2 3 4 WCF :: getTPL () -> assign ([ 'foo' => 'bar' , 'baz' => false ]);","title":"Template Variables"},{"location":"view/templates/#modifiers","text":"If you want to call a function on a variable, you can use the modifier syntax: {@$foo|trim} , for example, results in the trimmed contents of $foo to be printed.","title":"Modifiers"},{"location":"view/templates/#system-template-variable","text":"The template variable $tpl is automatically assigned and is an array containing different data: $tpl[get] contains $_GET . $tpl[post] contains $_POST . $tpl[cookie] contains $_COOKIE . $tpl[server] contains $_SERVER . $tpl[env] contains $_ENV . $tpl[now] contains TIME_NOW (current timestamp). Furthermore, the following template variables are also automatically assigned: $__wcf contains the WCF object (or WCFACP object in the backend).","title":"System Template Variable"},{"location":"view/templates/#comments","text":"Comments are wrapped in {* and *} and can span multiple lines: 1 2 { * some comment * } The template compiler discards the comments, so that they not included in the compiled template.","title":"Comments"},{"location":"view/templates/#conditions","text":"Conditions follow a similar syntax to PHP code: 1 2 3 4 5 6 7 { if $foo === 'bar' } foo is bar { elseif $foo === 'baz' } foo is baz { else } foo is neither bar nor baz { /if } The supported operators in conditions are === , !== , == , != , <= , < , >= , > , || , && , ! , and = . More examples: 1 2 3 { if $bar | isset } \u2026 { /if } { if $bar | count > 3 && $bar | count < 100 } \u2026 { /if }","title":"Conditions"},{"location":"view/templates/#foreach-loops","text":"Foreach loops allow to iterate over arrays or iterable objects: 1 2 3 4 5 <ul> { foreach from = $array key = key item = value } <li> { $key } : { $value } </li> { /foreach } </ul> While the from attribute containing the iterated structure and the item attribute containg the current value are mandatory, the key attribute is optional. If the foreach loop has a name assigned to it via the name attribute, the $tpl template variable provides additional data about the loop: 1 2 3 4 5 6 7 8 9 10 11 <ul> { foreach from = $array key = key item = value name = foo } { if $tpl [ foreach ][ foo ][ first ] } something special for the first iteration { elseif $tpl [ foreach ][ foo ][ last ] } something special for the last iteration { /if } <li>iteration { # $tpl [ foreach ][ foo ][ iteration ]+ 1 } out of { # $tpl [ foreach ][ foo ][ total ] } { $key } : { $value } </li> { /foreach } </ul> In contrast to PHP\u2019s foreach loop, templates also support foreachelse : 1 2 3 4 5 { foreach from = $array item = value } \u2026 { foreachelse } there is nothing to iterate over { /foreach }","title":"Foreach Loops"},{"location":"view/templates/#including-other-templates","text":"To include template named foo from the same domain (frontend/backend), you can use 1 { include file = 'foo' } If the template belongs to an application, you have to specify that application using the application attribute: 1 { include file = 'foo' application = 'app' } Additional template variables can be passed to the included template as additional attributes: 1 { include file = 'foo' application = 'app' var1 = 'foo1' var2 = 'foo2' }","title":"Including Other Templates"},{"location":"view/templates/#template-plugins","text":"An overview of all available template plugins can be found here .","title":"Template Plugins"}]}
\ No newline at end of file