e107 v2.x Plugin and Theme developer manual.

Getting Started

Developing Plugins, Themes and Custom Scripts with e107.

Hello World

To create a simple test script, create a new file called test.php in your root folder with the following php:

		require_once("class2.php");
require_once(HEADERF);
echo "Hello World";
require_once(FOOTERF);

Then point your browser to www.yoursite.com/test.php

Files and Folders

Below is the basic folder-structure of the e107 installation.

Folder Can be modified Description
e107_admin No Contains main files used for the admin area.
e107_core No Contains core assets. You should not make changes within this folder.
e107_handlers No Contains core functions and classes. You should not make changes within this folder.
e107_images Not Usually Contains core images. You should not normally need to make changes within this folder.
e107_languages Not the English folder. Contains core language files.
e107_media Not usually Contains Media such as downloadable images or files which are specific to your installation.
e107_plugins Yes Contains all plugins, installed and uninstalled. You may manually add plugins to this folder if need be.
e107_system Not usually Contains private files such as logs, plugin and theme downloads which are specific to your installation.
e107_theme Yes Contains all themes, installed and uninstalled. You may manually add themes to this folder if need be.
e107_web No Contains core js and css packages.

Debugging

Your code should not produce any PHP warnings or notices during normal use. This primarily implies that all variables must be defined before being used. It also implies that a corrupted installation may produce errors, although as far as practicable the code should accommodate this. Many PHP notices can be avoided by using the functions vartrue() and varset().

We recommend this collection of Firefox Addons. The most important being the e107 Debugger. If you don't wish to use the debugger, you can still activate various debugging modes manually, by changing the query string of the url. ie. directly after .php? add [debug=xxxx]

Query Description
[debug=basic+] Display basic error information
[debug=notice+] Display PHP Notices.
[debug=warning+] Display PHP Warnings.
[debug=time+] Display load/processing times
[debug=sql+] Display SQL info.
[debug=-] Disable debugging. 

Classes and Methods

Using e107's built-in classes and methods.

Database

Retrieving the database class object

		$sql = e107::getDb();

select()

Selecting data from a database table:

		$sql = e107::getDb();
$sql->select('tablename', 'field1, field2', 'field_id = 1');

fetch()

Selecting, looping through and displaying selected data with the fetch() method:

		$sql = e107::getDb();
$sql->select('tablename', 'field1, field2', 'field_id = 1');
while($row = $sql->fetch())
{
    echo $row['field1'];
}

insert()

Inserting data into a database table:

		$insert = array(
    'user_id' => 1,
    'user_email' => '@'
);

$sql->insert('user', $insert); // where 'user' is the table name

update()

Updating information in a database:

		$update = array(
    'user_email' => '@',
    // ... Long list of fields/values
    'WHERE' => 'user_id = 1'
);

$sql->update('user', $update); // where 'user' is the table name.

retrieve()

Combined select() and fetch() method.

Example: Get single value

		$string = $sql->retrieve('user', 'user_email', 'user_id=1');


Example: Get multiple table-row values

		if($allRows = $sql->retrieve('user', 'user_name, user_email', '', true))
{
	foreach($allRows as $row)
	{
		echo $row["user_name"]." - ".$row["user_email"]."<br/>";  
	}
}

delete()

Delete a record from a database table.

		$sql->delete("user", "user_id=2");

gen()

Generic query function

Example: perform a JOIN with gen():

		$sql->gen("SELECT f.*,u.user_name FROM #faqs AS f LEFT JOIN #users as u ON f.faq_author = u.user_id ");

Forms

Retrieving the form class object

		$frm = e107::getForm();

Basics

open()

Returns a form opening tag.

		$frm->open('myform'); // returns
		$frm->open('myform', 'get', 'myscript.php', array('autocomplete' => 'on', 'class' => 'formclass'));

Name Description
$name string - form name
$mode string - post | get - 'post' by default
$target string - request URL - e_REQUEST_URI by default
$options array - specify options such as class or autocomplete

close()

Returns a form closing tag

		$frm->close(); // returns 

text()

Returns a text field form element

		$frm->text('my-field', 'current_value', 100, array('size' => 'large')); // returns <input class="tbox input-large" id="my-field" maxlength="100" name="my-field" type="text" value="current_value"></input>

Name Description
$name string - name of the text field
$value string - value of the text fieldt
$maxlength integer - specifies maxlength element of the text field
$options array - specify options such as class, size or selectize
size: mini, small, medium, large, xlarge, xxlarge
selectize: array with selectize.js options

textarea()

		$frm->textarea($name,$value,$rows,$cols,$options,$counter);

bbarea()

		$frm->bbarea($name,$value,$template,$mediaCat,$size,$options);
Name Description
$name string - Name of the field
$value string - Contents of the field
$template (optional) string - A string defining the button template to use with bbarea. Included in the core are the following: news, submitnews, extended, admin, mailout, page, comment, signature
But you can also use the name of the plugin (e.g. forum) if the plugin provides a bbcode_template.php
$mediaCat (optional) string - Name of the nedia catalog to use (default: _common)
Is only used by tinymce (if installed and used)
$size (optional) string - Size of the bbarea/editor.
Use one of the following values: tiny, small, medium, large (default: large)
$options

(optional) array - Array with options to use with the editor:
id: string - In case the bbarea/editor id should be different to the name
class: string - the css classes to use
counter: boolean - Show a character counter
wysiwyg: boolean/string -

  • False in case you want disable the wysiwyg editor for this field and use the default bbcode editor.
  • True to enable the current installed (and enabled) wysiwyg editor
  • Name of the editor (e.g. tinymce4 or simplemde) to use, in case wysiwyg is generally enabled and the supplied editor is installed.

select()

		$frm->select($name,$option_array,$selected,$options,$defaultBlank);

checkbox()

		$frm->checkbox($name,$value,$checked,$options);

hidden()

		$frm->hidden($name,$value,$options);

button()

		$frm->button($name,$value,$action,$label,$options);

Advanced

carousel() Render a Bootstrap carousel

		$frm->carousel($name, $array, $options);
		$array = array(
      'slide1' => array('caption' => 'Slide 1', 'text' => 'first slide content' ),
      'slide2' => array('caption' => 'Slide 2', 'text' => 'second slide content' ),
      'slide3' => array('caption' => 'Slide 3', 'text' => 'third slide content' )
  );

echo $frm->carousel('my-carousel', $array);

tabs() Render Bootstrap tabs

		$frm->tabs($array,$options);
		$array = array(
   'home' => array('caption' => 'Home', 'text' => 'some tab content' ),
   'other' => array('caption' => 'Other', 'text' => 'second tab content' )
);

echo $frm->tabs($array);

echo $frm->tabs($array, array('active'=>'other')); // make 'other' the initial active tab. 

Parser

toHtml()

Parse HTML in various ways. eg. replace constants, convert bbcode etc.

		$tp->toHtml(string, bbcodes, type);
$tp->toHtml("<strong class="bbcode bold bbcode-b bbcode-b-page">Bold print</strong>", true, 'BODY'); // Example
Name Description
string text or HTML to be parsed
bbcodes boolean - set to true to parse bbcodes into html
type string - TITLE, SUMMARY, DESCRIPTION, BODY, LINKTEXT, RAWTEXT

toDate()

Convert a unix timestamp into a readable format.

		$tp->toDate(unixDatestamp, format);
Format Description
short Short date format as defined in admin preferences
long Long date format as defined in admin preferences
relative Relative time format. eg. "2 days ago"

toText()

Convert html to plain text.

		$tp->toText(string);

createConstants()

Convert e_xxxxx paths to their equivalent shortcodes. eg. e_PLUGIN becomes {e_PLUGIN}

		$tp->createConstants(string);

replaceConstants()

Convert {e_XXXX} shortcode paths to their equivalent constants. eg. {e_PLUGIN} becomes e_PLUGIN

		$tp->replaceConstants(string);

parseTemplate()

Parse an e107 template using core and/or custom shortcodes. ie. replaces all instances of {XXXXX_XXXX} etc.

		$tp->parseTemplate(template, use core shortcodes, custom shortcodes);
Name Description
template string
user core shortcodes boolean
custom shortcodes object

thumbUrl()

Use to convert {e_MEDIA_IMAGE} and other image paths to an auto-sized image path for use inside an img tag.

		$url = "{e_MEDIA_IMAGE}2012-04/someimage.jpg";
$image = $tp->thumbUrl($url);
echo "<img src='".$image."' />

setThumbSize()

Set the width, height and crop of the thumbUrl function.

		$tp->setThumbSize($width, $height, $crop);

toGlyph()

Convert a glyph name into Html. Just choose an icon from font-awesome and remove the first 'fa'
Templates may also use the following shortcode: which calls the same function.

		$tp->toGlyph("fa-anchor");


Advanced settings:

		$tp->toGlyph("fa-anchor", array('size'=>'2x'));

toIcon()

Render an icon. If a .glyph extension is found, it will automatically use the toGlyph() function above.

		$iconPath = "{e_MEDIA}myicon.png";
$tp->toIcon($iconPath);

toAvatar()

Render a user avatar. If empty, the current user's avatar will be displayed if found or a generic avatar image.

		echo $tp->toAvatar(); // render avatar of the current user. 
		$userData = e107::user(5);  // Get User data for user-id #5. 
echo $tp->toAvatar($userData); // requires as a minimum $userData['user_image'].

toImage()

Render an image.

		$url = "{e_MEDIA_IMAGE}2012-04/someimage.jpg";
$parms = array('w'=>500, 'h'=>200,'crop'=>1, 'alt'=>'my image'); // if not width/height set, the default as set by {SETIMAGE} will be used.
echo $tp->toImage($url,$parms); 

Render

Send HTML to the browser.

		$ns = e107::getRender();
$ns->tablerender($caption, $text, $mode, $return);
Name Description
$caption string - header/caption
$text string - main content
$mode unique name for what is being rendered. eg contact-menu
$return boolean - when set to true the content is returned instead of being echoed.

Preferences

Developers may retrieve admin preferences for their theme or plugin, or a core preference using the following method:

		e107::pref(type, value);

Example: Load a stored value that was saved in the preferences admin area of the 'faqs' plugin

		$myprefs = e107::pref('faqs'); // returns an array.

Or load a single preference value.

		$perPage = e107::pref('faqs', 'faqs_per_page');
Type Value (optional)
core all core preference values.
theme preferences of the currently selected front-end theme.
(any plugin folder name) preferences of a particular plugin

Javascript

Basics

Including javascript in your plugin or theme may be achieved by using the following function:

		e107::js(type, value, dependency, zone);

Example: Load a script in the 'faqs' plugin directory and auto-load jquery if not already loaded.

		e107::js('faqs','js/faqs.js', 'jquery')

Example: Load a theme script in the footer

		e107::js("theme", "js/scripts.js", 'jquery');  // no 'zone' value, loaded in the footer by default. 

Example: Load a theme script in the header

		e107::js("theme", "js/scripts.js", 'jquery', 2); // including a 'zone' value loads it in the header 
Type Value Description
core path relative to the core folder Include a core js file in the header of the page
url* full url to javascript filel Include a remote js file in the header of the page
inline javascript code Include raw javascript code in the header of the page
theme path to js file, relative to the current theme's folder Include a theme js file
(any plugin folder name) path to js file, relative to the plugin's folder Include a plugin js file
settings ‡ array (PHP) Adds settings to e107's global storage of JavaScript settings.

‡ settings: An associative array with configuration options. The array is merged directly into e107.settings. All plugins should wrap their actual configuration settings in another variable to prevent conflicts in the e107.settings namespace. Items added with a string key will replace existing settings with that key; items with numeric array keys will be added to the existing settings array.

Remember that loading from url may take more time than local resources, remember to use dependency if needed

JavaScript Behaviors

Behaviors are event-triggered actions that attach to page elements, enhancing default non-JavaScript UIs. Behaviors are registered in the e107.behaviors object using the method 'attach' and optionally also 'detach' as follows:

		var e107 = e107 || {'settings': {}, 'behaviors': {}};

(function ($)
{
  e107.behaviors.myBehavior = {
    attach: function (context, settings)
    {

    },
    detach: function (context, settings, trigger)
    {

    }
  };
})(jQuery);

e107.attachBehaviors is added to the jQuery ready event and so runs on initial page load. Developers implementing Ajax in their solutions should also call this function after new page content has been loaded, feeding in an element to be processed, in order to attach all behaviors to the new content.

See the e107_web/js/core/all.jquery.js file for more information.

Using jQuery

jQuery is now namespaced to avoid conflicts with other Javascript libraries such as Prototype. All your code that expects to use jQuery as $ should be wrapped in an outer context like so.

		(function ($) {
  // All your code here.
})(jQuery);

If you don't, you may see the error Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function or similar.

jQuery Once

e107.behaviors will often be called multiple times on a page. For example, core/custom plugin performs some Ajax operation, all e107 behaviors will be executed again after page load, in order to attach any relevant JavaScript to the newly loaded elements. This can have the undesired affect of applying JavaScript to elements each time e107 behaviors are executed, resulting in the same code being applied multiple times. To ensure that the JavaScript is applied only once, we can use the jQuery $.once() function. This function will ensure that the code inside the function is not executed if it has already been executed for the given element.

Using jQuery $.once() (integrated into e107 core), the developer experience of applying these effects is improved. Note that there is also the $.removeOnce() method that will only take effect on elements that have already applied the behaviors.

		var e107 = e107 || {'settings': {}, 'behaviors': {}};

(function ($)
{

  e107.behaviors.myBehavior = {
    attach: function (context, settings)
    {
      $(context).find(".some-element").once('my-behavior').each(function ()
      {
        // All your code here.
      });
    }
  };

})(jQuery);

Settings passed locally to JavaScript Behaviors

		e107.behaviors.myBehavior = {
  attach: function(context, settings) {
    $('#example', context).html(settings.myvar);
  }
};

How to override a JavaScript Behavior

If you want to override a bit of core (or third party) e107 JavaScript Behavior, just copy the behavior to your javascript file (e.g in your plugin or theme), then load it after the original code using "zones".

CSS

Including css in your plugin or theme may be achieved by using the following function:

		e107::css(type, value);
Type Value Description
theme path relative to the theme's folder Include a theme css file in the header of the site
url full url to css file Include a remote css file in the header of the site
inline css code Include raw css code in the header of every page of the site

User Data

Returns an array of user data for a specific user. Input can be either a specific ID ($user_id) or use USERID for the currently logged in user.

		e107::user($user_id);
$userData = e107::user(USERID); // Example - currently logged in user. 
$userData = e107::user(5); // Example  User ID #5.

Meta

Include meta tags in the html header.

e107::meta($name, $content, $extended);
e107::meta('keywords','some words'); // example
e107::meta('apple-mobile-web-app-capable','yes'); // example

Events

Plugin developers can hook into various e107 core events and trigger functions of their own. Typically, an e_module.php file is used to store this information since it is loaded with every page.

From e107 v2.1.2 you can use e_event.php to catch the events in order of using e_module.php

Variable Description
name The event you wish to hook into. (see table below)
function Your function or class/method to trigger when this event occurs. string for function, or for classes use an array(class,method) .
include include[/code] (optional) path a file to include if required.

		e107::getEvent()->register(name, function, include);


Example 1: trigger myFunction() on user login.

		//
e107::getEvent()->register('login', 'myFunction'); 

function myFunction($data)
{
   // do something    
}


Example 2: trigger myFunction() on user login. Function in external file.

		e107::getEvent()->register('login', 'myFunction',  e_PLUGIN."myplugin/myFunctions.php");


Example 3: trigger a class and method on user login.

		e107::getEvent()->register('login', array('myClass', 'myMethod'),  e_PLUGIN."myplugin/myClass.php");

User Event Triggers

Trigger Name Description Data
login User login/signin Array of user data
logout User logout/signout Notice event
user_file_upload User uploads a file Array of file information
user_signup_submitted User submits signup form Array of user data
user_signup_activated User activates newly created account. (email link) Array of user data
user_xup_login User signs in via a social media account. eg. Facebook, Twitter etc. Array of user data
user_xup_signup User creates an account using their social media login. Facebook, Twitter etc. Array of user data
user_profile_display User has viewed a profile Array of data
user_profile_edit User has edited their profile Array of data of user who changed the settings
user_comment_posted User has posted a new comment Array of data
preuserset Before usersettings are updated Array of new user settings ($_POST)
postuserset After usersettings are updated Array of new user settings ($_POST)
userdatachanged After usersettings are updated (same time and data as user_profile_edit) Array of data of user who changed the settings

Custom page

Trigger function Description Data
user_page_item_viewed User has viewed a custom page Array of data

News

Trigger Name Description Data
user_news_item_viewed User viewed a news item Array of data
user_news_submit User submitted a news item Array of data

Private Messenger

Trigger name Description Data
user_pm_sent User has sent a private message Array of data
user_pm_read User has read a private message Array of data

Forum

Trigger Name Description Data
user_forum_topic_created User creates a forum topic Array of data
user_forum_topic_created_probationary New user creates a forum topic Array of data
user_forum_topic_updated User updates a forum topic Array of data
user_forum_topic_deleted User deletes a forum topic Array of data
user_forum_topic_moved User has moved forum topic to a different forum Array of data
user_forum_topic_split User has split the forum topic Array of data
user_forum_post_created User creates a forum post/reply Array of data
user_forum_post_updated User updates a forum post/reply Array of data
user_forum_post_deleted User deletes a forum post/reply Array of data
user_forum_post_report User has reported a forum post/reply Array of data

Chatbox

Trigger function Description Data
user_chatbox_post_created User has posted a chatbox message Array of data (ip and message)

Admin Event Triggers

Admin changes their password

Trigger Name Description Data
admin_password_update Admin updates their password Array containing user_id and time of change.

Comments Manager

Trigger Name Description Data
admin_comment_update Admin updates a comment Array of comment data
admin_comment_delete Admin deletes a comment Array of comment data

Downloads

Trigger Name Description Data
admin_download_create Admin creates a download item Array of download data
admin_download_update Admin updates a download item Array of download data
admin_download_delete Admin deletes a download item Array of download data

News

Trigger Name Description Data
admin_news_create Admin creates a news item Array of news data
admin_news_update Admin updates a news item Array of news data
admin_news_delete Admin deletes a news item Array of news data
admin_news_category_create Admin creates a news category Array of news data
admin_news__category_update Admin updates a news category Array of news data
admin_news_category_delete Admin deletes a news category Array of news data

Pages

Trigger Name Description Data
admin_page_create Admin creates a page/menu item Array of page data
admin_page_update Admin updates a page/menu item Array of page data (new and old)
admin_page_delete Admin deletes a page/menu item Array of page data

Users

Trigger Name Description Data
admin_user_create Admin creates a new user Array of user data
admin_user_update Admin modifies user data Array of user data (new and old)
admin_user_delete Admin deletes a user Array of user data
admin_user_activate Admin activates an unverified user Array of user data
admin_user_loginas Admin logs in as another user Array of user data
admin_user_logoutas Admin logs out as another user Array of user data

Alerts

You can assign and render 'alert' messages using the following.

		$mes = e107::getMessage();

addSuccess()

		$mes = e107::getMessage();
$mes->addSuccess('You did it!');

addError()

		$mes = e107::getMessage();
$mes->addError('There was a problem!');

addWarning()

		$mes = e107::getMessage();
$mes->addWarning('You do not have access to this area!');

addInfo()

		$mes = e107::getMessage();
$mes->addInfo('Please take note!');

addDebug()

Messages assigned here will only be displayed when debug mode is active.

		$mes = e107::getMessage();
$mes->addInfo('Please take note!');

render()

None of the above methods will output anything, until you use this method to render them.

		$mes = e107::getMessage();
$mes->addInfo('Please take note!');
echo $mes->render();

Logging

You can log events to the admin system logs by using the built in log class.

$log = e107::getLog();

add()

name a title or name for the log event.
details details for the log event - can be either a string of text or an array.
type the type of event. (see table below)
code is a custom reference code for your type of event. It should be short, ALL CAPITALS and not contain spaces.

$log = e107::getLog();
$log->add(name, details, type, code);

//Example: 
$log->add('My Event Name', $myDetailedData, E_LOG_INFORMATIVE, 'MYCODE');


Type Description
E_LOG_INFORMATIVE Informational event
E_LOG_NOTICE Notice event
E_LOG_WARNING Warning event
E_LOG_FATAL Fatal event

Redirection

You can redirect to a url using the following static method:

		e107::redirect(url);

To redirect to the home page, simply leave the url blank.

		e107::redirect();

To redirect to the admin area, use the value 'admin'.

		e107::redirect('admin');

For any other location, include the full url.

		e107:redirect("http://my-domain.com/myfile.php");
exit;

Urls

You can generate a search-engine-friendly URL (where supported) using the following method:

		e107::url(plugin, key, row, options);
Value Type Description
plugin string Folder name of the plugin. (will use data from e_url.php)
key string Unique key
row array array of variable data such as id, title etc. eg. user_id, user_name
options array An associative array of additional options, with the following elements:
'mode': abs | full
'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.
'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.

Example

In this example we will generate a search-engine-friendly URL for a forum topic with the following code: .

		$data = array(
'forum_sef'='my-sef-forum-name',
'thread_id'=>2,
'thread_sef'=>'my-forum-topic'
); // these values are usually loaded from the database.

$url = e107::url('forum','topic',$data);

The code above loads the following file: e107_plugins/forum/e_url.php and generates a URL from the following array data with the unique key topic:

		$config['topic'] = array(
'regex' => '^forum/(.*)/(d*)-([w-]*)/???(.*)',
'sef' => 'forum/{forum_sef}/{thread_id}-{thread_sef}/',
'redirect' => '/e107_plugins/forum/forum_viewtopic.php?id=$2&$4'
);

Only the value of 'sef' is used in this array. it substitutes the values {forum_sef}, {thread_id} and {thread_sef} with the variables in the $data array.

The end result would look something like this: http://sitename.com/forum/my-sef-forum-name/2-my-forum-topic

Plugin Basics

Creating an e107 plugin

Plugin Overview

Plugins extended the functionality of e107 and allow for endless possibilities. We've aimed to make our plugin architecture as simple as possible. Often you can copy a file from an existing plugin and simply modify a few parameters in order to get similar functionality in your own plugin.

Plugin Builder

By far the quickest and easiest way to develop a plugin for e107 is to use the plugin builder ( Manage -> Plugin Manager -> Plugin Builder).
It will create the plugin.xml (meta-data) file, as well as code most of the admin area of your plugin for you. Additional features may be added in future.

Steps to Use:

  • Create an empty plugin folder in e107_plugins/ (eg. 'myplugin')
  • Create a new text file with the _sql.php extension. (eg. 'myplugin_sql.php')
  • Using PHPMyAdmin, create your database table structure, and then export it in SQL format.
  • Copy/Paste the "CREATE TABLE" data to your your _sql.php file. (see other plugins for examples)
  • Go to Manage -> Plugin Manager -> Plugin Builder and choose 'myplugin' from the dropdown menu and then follow the prompts.
  • Thoroughly check the details of each Table Tab (and Preferences Tab if you need them) before proceeding with the creation process.

Admin-UI

This will summarize the various options which may be used while utilizing the admin-ui class. Please note that the documentation for this is a work-in-progress. Thank you for your patience.

$fields

Database fields are defined by the $fields value in the admin-ui class. Example:

		protected $fields = array(

   'myfield_id'  => array("title"=>"My Title", "type"=>"text", "data"=>"str", "width"=>"auto", "inline"=>true)

   // .....

);
Key Format Description
title string Field Title
type string Type of Field
data string Data Type
width string width of the column (List View)
inline boolean | string  Enable or disable inline editing.
help string  Popup helper text (tooltip)
readParms array  Parameters specific to the 'list' mode.
writeParms array  Parameters specific to the 'edit' and 'create' modes.
validate boolean | string Marks the field as required (*).

type

Type Description
text text box
number text box (number)
checkbox checkbox (0 or 1 is returned)
icon icon (from media manager)
textarea text area (text only)
boolean radio buttons with enable/disable
bbarea right text area (html)
dropdown dropdown list (ie. <select></select> )
userclass drop-down list of userclasses
userclasses checkboxes for multiple userclasses
datestamp date / time text box
user user selection text box. (type 3 letters to find/search)
hidden hidden field
ip text field with ip decoding
email text field for email addresses
url text field for urls (becomes clickable in list mode)
password password field (with optional generator)
image Media-manager image selection tool for a single image
images Media-manager image selection tool for multiple images
file Media-manager file selection tool for a single file
files Media-manager file selection tool for multiple files
media Media-Manager selection tool for images, mp4, youtube and gylphs. (requires type=json)
method custom method
lanlist drop-down list of installed languages
language drop-down list of all languages
templates Dropdown list of templates (from a template file)
null (without quotes) Ignore this field and do not save it's data
false (without quotes) Hide this field but save it's data if a posted key value is found.

data

Value Description
str Posted data is converted to string before saving to the database
safestr Posted data is run through a filter (using filter_var(FILTER_SANITIZE_STRING)) and thus strips HTML.
int Posted data is converted to integer before saving to the database
array Posted data is converted to an e107 array format. (use e107::unserialize() to decode)
json Posted data is converted to json format before saving to the database
false (no quotes) Posted data from this field is not saved to the database

 

readParms (list mode)

Key Value Field-type Comments
thumb (integer)  image  Set the thumbnail width
 url  (string)  e_url.php key value or a field key.  number, text, tags, null  Wrap value in a link
 target  (string) blank | dialog  number, text, tags, null  Target for 'url' above.

 

writeParms (create/edit mode)

Key Value Field-type Comments
pre (html) (all) Render html just before the field
post (html) (all) Render html just after the field
media (string) bbarea Sets the media-owner category to be used by the media-manager
video 0 or 1 image Show video selector tab in media-manager
path 'plugin' or null image When set to 'plugin', images will be stored in the 'plugin' folder within e107_media
glyphs 0 or 1 icon Show glyph selector tab in media-manager
size large, xlarge, xxlarge, block-level  text, url, email, textarea, dropdown Set the size (width) of input field
optArray (array of key=>value pairs) dropdown, checkboxes Set the keys/values to be used in the dropdown or checkboxes.
placeholder (string) text, url, email, textarea Placeholder text
pattern (regexp) text, url, email Regular expression validation
type date or datetime datestamp Choose between date or date and time
readonly 0 or 1 datestamp Make element read-only
auto 0 or 1 datestamp Insert current date/time automatically
label yesno boolean Change "Enabled" and "Disabled" to "Yes" and "No".
inverse 0 or 1 boolean Invert the values of 0 and 1. ie. "Disabled" = 1 and "Enabled" = 0.
enabled (string) boolean Alternate text to replace "Enabled"
disabled (string) boolean Alternate text to replace "Disabled"
classlist public, guest, nobody, member, admin, main, classes
(comma separated)
userclass Set which userclasses should be displayed.
tdClassLeft (string) (all) Set the css class for the left-side table cell.
tdClassRight (string) (all) Set the css class for the right-side table cell.
trClass (string) (all) Set the css class for the table row.
nolabel 0 or 1 (all) Hide the left table cell

Creating a tree structure

The admin UI allows to automatically create a tree structure based on parent/child relationship tables. Examples can be found in the forum and download plugin. In order to add a tree structure, add the following code:

		protected $sortField  = 'field1';
protected $sortParent = 'field2';
protected $treePrefix = 'field3';

In this case, field1 represents the fields which determines the order (for example an ID field). The 'field2' represents the field which is the parent and 'field3' the child. For example:

		protected $sortField  = 'download_category_order';
protected $sortParent = 'download_category_parent';
protected $treePrefix = 'download_category_name';

Setup and Installation

plugin.xml


Here's a simple example of a plugin.xml file.

		<?xml version="1.0" encoding="utf-8"?>
<e107Plugin name="Newsfeeds" version="2.0" date="2012-08-01" compatibility="2.0" installRequired="true">
	<author name="e107 Inc." url="http://e107.org" email="@" />
	<description>This plugin's description.</description>
	<category>content</category>
	<adminLinks>
		<link url='admin_config.php' description='Configure Newsfeeds' icon='images/icon_32.png' iconSmall='images/icon_16.png' >LAN_CONFIGURE</link>	
	</adminLinks>
	<siteLinks>
		<link url="/e107_plugins/newsfeed/newsfeed.php" >Newsfeeds</link>
	</siteLinks>	
</e107Plugin>


Here's an advanced example of a plugin.xml file.

		<?xml version="1.0" encoding="utf-8"?>
<e107Plugin name="FAQs" version="1.1"  lan="LAN_PLUGIN_XXX_NAME" date="2012-08-01" compatibility="2.0" installRequired="true">
	 <author name="e107 Inc" url="http://www.e107.org" email="@" />
	<summary>Add frequently asked questions to your e107 website.</summary>
	<description  lan="LAN_PLUGIN_XXX_DESCRIPTION">A simple plugin to add Frequently Asked Questions to your website.</description>
	 <copyright>Copyright e107 Inc e107.org, Licensed under GPL</copyright>
	<category>content</category>
	<keywords>
		<word>faq</word>
		<word>question</word>
		<word>answer</word>
	</keywords>
	<adminLinks>
		<link url='admin_config.php' description='Configure FAQs' icon='images/icon_32.png' iconSmall='images/icon_16.png' primary='true'>LAN_CONFIGURE</link>		
	</adminLinks>
	<siteLinks>
		<link url='/e107_plugins/faqs/faqs.php' description='FAQs' icon='images/icon_32.png' iconSmall='images/icon_16.png' function="faqCategories">LAN_PLUGIN_FAQS_NAME</link>		
	</siteLinks>
	<pluginPrefs>
		<pref name="add_faq">255</pref>
		<pref name="submit_question">255</pref>
		<pref name="classic_look">0</pref>
	</pluginPrefs>
	<dependencies>
		<plugin name='chatbox_menu' />
		<plugin name='calendar_menu' min_version='3.70' />
		<PHP name='core' min_version='5.2.5' />
		<MySQL name='server' min_version='4.9' />
		<extension name='curl' min_version='1.3' />
		<extension name='mb_string' />
	</dependencies>
	<userClasses>
		<class name="faq_moderator" description="FAQ moderator" />		
	</userClasses>
	<extendedFields>
		<field name="viewed" type='EUF_TEXTAREA' default='0' active="true" />
		<field name="posts" type='EUF_INTEGER' default='0' active="true" />
	</extendedFields>	
</e107Plugin>

 

Tip: If you are developing a commercial plugin, you'll want to add a few extra attributes so that it displays correct in the admin area under "Find Plugins". .
<e107Plugin name="FAQs" .... price="25.00" currency="EUR" url="http://direct-path-to-my-theme-purchase-page.com" >

Just package your plugin.zip file with only the plugin.xml and any images (including plugin icons) , excluding .php files etc. before sharing it. When the user clicks to download your plugin, the url you have provided will be displayed.

plugin_setup.php


More details coming soon. See e107_plugins/gallery/gallery_setup.php for an example.

plugin_sql.php


This contains a "CREATE TABLE" mysql dump of the database tables that your plugin will use.
You can find examples in most of the plugins in e107_plugins/

Languages

File Types

Language File Type Usage
English_front.php The front-end of your plugin.
English_admin.php The admin-area of your plugin
English_global.php Used site-wide - for example, in plugin.xml, a xxxxx_menu.php or e_xxxxxx.php file.

 

Defining Language Terms aka 'LANS'

Avoid duplicating terms, particularly in the admin area. If defining terms for admin, always search lan_admin.php for existing LANs which may match what you require. Never use HTML or URLs inside LAN definitions. Use double quotes within the defines and use str_replace() for variables where needed. See the examples below:

Good:

		define("LAN_XXX", "Thank you Firstname");
define("LAN_XXX", "Go to [x] to see the results."); // Good - replace [ and ] with <a href='...'> and </a> using str_replace()
define("LAN_XXX", "I want to [quote] here"); // Good - replace [ and ] with " " using str_replace()


Bad:

		define("LAN_XXX", "Thank you <b>Firstname</b>"); //Bad contains HTML
define("LAN_XXX", "Thank you <a href='http://somewhere.com'>Firstname</a>"); //Bad contains HTML
define("LAN_XXX", "Thank you Firstname"); //Bad - allows translator to modify link.


Avoid short language strings for words such as 'and', 'to' and so on. There aren't always equivalents in other languages. If embedding values into a phrase, use substitution. Avoid using substitution terms which are real words or known bbcodes.

		define("LAN_EXAMPLE_01", "Update results: [x] records changed, [y] errors, [z] not changed");
$repl = array($changed,$errors,$unchanged);
$text = $tp->lanVars(LAN_EXAMPLE_01,$repl);



Loading Language Files


To load a language file from a plugin folder:

		e107::lan('faqs');
e107::lan('faqs',true);
e107::lan('faqs',false, true);
e107::lan('faqs',true, true);


Will include the following paths:

		e107_plugins/faqs/languages/English_front.php
e107_plugins/faqs/languages/English_admin.php
e107_plugins/faqs/languages/English/English_front.php
e107_plugins/faqs/languages/English/English_admin.php

Extending core functionality

e107 plugin "addons" are files which reside in each plugin's folder and allow a plugin to embed itself inside e107's core pages and functions.
You can recognize these files by their e_xxxxx.php naming format.
By simply placing any or all of the file types below inside your plugin's folder, they will be auto-detected during installation and integrated into the system.
If added after installation you may need to run the Scan Plugin Folders option in admin -> Databases.

e_cron.php

Allows a plugin to add additional scheduled task options to e107. (see admin -> Scheduled Tasks)
Be sure to replace plugindir with your plugin's directory name. eg. class faqs_cron

		class plugindir_cron       // plugin-folder name + '_cron'.
{
    function config() // Setup  
    {
        $cron = array();
	
        $cron[] = array(
            'name'            => "Name of my function",  // Displayed in admin area. . 
            'function'        => "myFunction",    // Name of the function which is defined below. 
            'category'        => 'mail',           // Choose between: mail, user, content, notify, or backup
            'description'     => "Description of what my function does"  // Displayed in admin area. 
        );		
		
        return $cron;
    }
	
    public function myFunction()
    {
        // Do Something. 
    }

}

e_dashboard.php

Adds custom plugin information to the dashboard of e107's admin area. The 'latest', 'status' and 'website stats' areas may all contain information from your plugin.
See e107_plugins/forum/e_dashboard.php for an example of usage.

e_event.php (as of e107 v2.1.2)

Allows a plugin to easily hook into system events and trigger their own methods/functions using data provided by those events. (more coming soon)

e_header.php

Allows a plugin developer to add data to the of every page. This file is loaded in the header of each page of your site. ie. Wherever you see require_once(HEADERF) in a script.
It is used to place elements inside the html tags.
Typically you would use one or all of the following functions within this file: e107::js(), e107::css() or e107::meta().
Output should never be echoed or printed from this file.

e_help.php

Allows plugin developers to add information to the plugin configuration page sidebar.

e_latest.php

Deprecated. Use e_dashboard.php instead.

e_mailout.php

Allows your plugin to use e107's mailout feature for bulk mailing.
See e107_plugins/newsletter/e_mailout.php for an example.

e_menu.php

Provide configuration options for each instance of your plugin's menus. Examples can be found in e107_plugins/banner/e_menu.php and e107_plugins/news/e_menu.php

(This is a replacement for the old config.php file used in v1.x)

e_module.php

This file is loaded every time the core of e107 is included. ie. Wherever you see require_once("class2.php") in a script. It allows a developer to modify or define constants, parameters etc. which should be loaded prior to the header or anything that is sent to the browser as output. It may also be included in Ajax calls.

e_search.php

Adds your plugin to the 'search page' of e107.
See e107_plugins/chatbox_menu/e_search.php for an example.

e_meta.php

Deprecated. Use e_header.php instead.

e_notify.php

Adds your plugin to the email notifications admin area. Replace mytrigger with a unique name of your own, and myplugin with your plugin folder.

		class myplugin_notify extends notify // plugin-folder + '_notify' 
{		
	function config()
	{
		
		$config = array();
	
		$config[] = array(
			'name'			=> "New Trigger Name", // Displayed in admin area. 
			'function'		=> "myplugin_mytrigger",
			'category'		=> ''
		);	
		
		return $config;
	}
	
	function myplugin_mytrigger($data) 
	{
	
		$message = print_a($data,true);
		
		$this->send('myplugin_mytrigger', "My Subject", $message);
	}
	
}

Then add the following to your script when you want to trigger it.

		e107::getEvent()->trigger("myplugin_mytrigger", $data);



e_status.php

Deprecated. Use e_dashboard.php instead.

e_rss.php

Adds your plugin to the RSS plugin, and generates RSS feeds for your plugin.

		class chatbox_menu_rss // plugin-folder + '_rss' 
{
    /**
     * Admin RSS Configuration 
     */        
    function config() 
    {
        $config = array();
    
        $config[] = array(
            'name'            => 'Chatbox Posts',
            'url'            => 'chatbox',
            'topic_id'        => '',
            'description'    => 'this is the rss feed for the chatbox entries', // that's 'description' not 'text' 
            'class'            => '0',
            'limit'            => '9'
        );    
        
        return $config;
    }
    
    /**
     * Compile RSS Data
     * @param $parms array    url, limit, id 
     * @return array
     */
    function data($parms='')
    {
        $sql = e107::getDb();
        
        $rss = array();
        $i=0;
                    
        if($items = $sql->select('chatbox', "*", "cb_blocked=0 ORDER BY cb_datestamp DESC LIMIT 0,".$parms['limit']))
        {

        while($row = $sql->fetch())
            {
                $tmp                        = explode(".", $row['cb_nick']);
                $rss[$i]['author']            = $tmp[1];
                $rss[$i]['author_email']    = ''; 
                $rss[$i]['link']            = "chatbox_menu/chat.php?".$row['cb_id'];
                $rss[$i]['linkid']            = $row['cb_id'];
                $rss[$i]['title']            = '';
                $rss[$i]['description']        = $row['cb_message'];
                $rss[$i]['category_name']    = '';
                $rss[$i]['category_link']    = '';
                $rss[$i]['datestamp']        = $row['cb_datestamp'];
                $rss[$i]['enc_url']            = "";
                $rss[$i]['enc_leng']        = "";
                $rss[$i]['enc_type']        = "";
                $i++;
            }

        }                
                    
        return $rss;
    }
            
        
    
}

e_related.php

Adds your plugin to the search which generates 'related' links in news items and pages of e107. See e107_plugins/news/e_related.php for an example.

e_shortcode.php

Sometimes a plugin developers wishes that his shortcode be available not only to his plugin's templates but to core templates and templates of other plugins. This is the purpose of this file. It's content is identical to that of a regular shortcode class except that all the methods must follow the following naming convention:
sc_plugindir_name() eg. sc_faqs_question()

e_sitelink.php

Adds a sitelink sublink-generating function for your plugin. eg. auto-generated navigation drop-down menus for 'latest articles' etc.
See e107_plugins/news/e_sitelink.php for an example.

e_url.php

Provides a simple way to add mod-rewrite redirects to your plugin's page, without having to edit the .htaccess file. To create search-engine-friendly URLs which utilize this addon, please see the e107::url() method.

		class myplugin_url // plugin-folder + '_url' 
{
	function config() 
	{
		$config = array();
	
		$config[] = array(
			'regex'			=> '^myplugref-(.*)/?$',
			'redirect'		=> '{e_PLUGIN}myplugin/ref.php?ref=$1',
		);
				
		return $config;
	}	
}



e_user.php

Adds information about a specific user to the user's profile page. See e107_plugins/forum/e_user.php for a working example.

Upgrading v1.x Plugins

Your Plugin's Admin Area

We recommend plugin developers to upgrade their admin areas using the 'Plugin Builder' in the 'Plugin Manager" area. It allows you to select your e107 _sql file from your plugin folder, or directly from the database table list and will generate most of the new code for the admin-area of your plugin. It will also generate the new plugin.xml meta-file, which is used during installation of your plugin and also when sharing plugins via this site. The advantages of using the new admin system are numerous - including, but not limited to:

  • No need to code in the HTML or the process of reading or writing to your database.
  • Consistent interface with the rest of admin
  • Users can select which fields from your db table they wish to view - based on your predefined list.
  • Media-Manager is integrated into the system.
  • Easily add drag and drop sorting/re-ordering to your plugin.
  • Easily add batch delete, copy, featurebox creation, sitelink creation, userclass modification, etc. etc.
  • Easily add inline editing to your data.
  • Easily add tabs to keep your plugin's admin-area well organized.

Your Plugin's Front End

Minimum Changes:

  • Include a plugin.xml file

Recommended Changes:

  • Include a plugin.xml file
  • Use e107's form_handler class for all form elements.
  • Use Bootstrap 3 html/css standards in your templates and/or HTML markup
  • Upgrade e_xxxx.php files to v2 standards
  • Upgrade language-file names to new standards

Migrating Plugin Preferences to their own table row.

In e107 v.2x we recommend plugins to save their preferences to their own table row, however old plugins may still be storing them in the core preference table.

To easily migrate from one to the other, we created a simple method called migrateData().

		$oldPluginPrefs = array(
    'myplugin_caption' => 'caption', // old-pref-name => new-pref-name 
    'myplugin_display' => 'display',
    'myplugin_maxage' => 'maxage',
);

if($newPrefs = e107::getConfig()->migrateData($oldPluginPrefs,true)) // returns new array with values and deletes core pref. 
{
    $result = e107::getPlugConfig('myplugin')->setPref($newPrefs)->save(false,true,false); // save new prefs to 'myplugin'. 
}

Theme Basics

Creating an e107 theme

Theme Overview

  • e107 v2.x is designed for Bootstrap styling. It is therefore encouraged for developers to use bootstrap as their guide for their HTML markup.
  • A default Bootstrap 3 is provided with e107. For html markup and examples, please refer to the Bootstrap documentation and for snippets: bootsnipp.com.
  • If you find markup in the core templates of e107 which does not work well with bootstrap, please let us know in the Github issue tracker, so that we may correct it.

theme.xml

This file contains information about the theme. It is used during installation and also during configuration of the theme.
To create a new theme.xml file or derive one from an existing v1.x theme.php file use the conversion tool here: yoursite.com/e107_admin/theme.php?mode=convert
Example from the bootstrap theme:

		<?xml version="1.0" encoding="utf-8"?>
<e107Theme name="bootstrap" version="1.0" date="2012-12-01" compatibility="2.0">
    <author name ="e107 Inc" email="@" url="http://e107.org" />
    <summary>Bootstrap e107 admin theme</summary>
    <description>Bootstrap e107 admin theme</description>
    <category>generic</category>
    <keywords>
        <word>bootstrap</word>
        <word>clean</word>
    </keywords>
    <screenshots>
        <image>preview.jpg</image>
        <image>fullpreview.jpg</image>
    </screenshots>
    <stylesheets>
        <css file="style.css" name="Default"  />
        <css file="css/superhero.css" name="Superhero" />
    </stylesheets>
    <layouts>
        <layout name='default' title='Default' default='true' />
        <layout name='default-home' title='Default Home'>
            <custompages>FRONTPAGE</custompages>	
        </layout>
        <layout name='hero' title='Hero' />
        <layout name='marketing-narrow' title='Marketing Narrow' />
        <layout name='docs' title='Documentation' />
    </layouts>
</e107Theme>
Tip: If you are developing a commercial theme, you'll want to add a few extra attributes so that it displays correctly in the admin area under "Find Themes". .

<e107Theme name="bootstrap" ... <strong>price="25.00" currency="EUR" url="http://direct-path-to-my-theme-purchase-page.com"</strong> >

Just package your theme's zip file with only the theme.xml and any images (including screenshots) , excluding .php, .css files etc. before sharing it.
When the user clicks to download the theme, it will display the url you have provided.

theme.php

Contains the main HTML template for your theme. A very basic theme.php file might look like this example below. the {---} is replaced automatically with the main page's content.
<?php

$LAYOUT['default'] = "
        <header>MY HEADER<header>
        <article>
            {---}
        </article>
    <footer> My Footer </footer>
";

function tablestyle($caption, $text, $mode='') 
{
    echo "<h3>".$caption."</h3>";
    echo $text;
}

?>
e107 will take this data and render the dynamic content of the page into it. The output of the above might look something like this:
<html>
<head>
 // Auto generated title, script, meta and link tags are added here. 
</head>
<body>
    <header>MY HEADER<header><article>
    <h3>Caption of the current page</h3>
    Text of the current page
    </article><footer> My Footer </footer>
</body>
</html>

Including JS, CSS and Meta in the head

See the section on including Javscripts, Stylesheets and Meta information.

Including a language file

You should use core language terms and avoid using a theme language file if possible. Refer to e107_languages/English/English.php for available terms.
e107::lan('theme'); // loads e107_themes/CURRENT_THEME/languages/English.php (when English is selected)

Core Shortcodes

Commonly used core theme shortcodes are listed below.

Name Description
{---} Renders the main content of the current page.
{CMENU=xxxxxx} Renders a specific custom menu item as defined in admin -> Pages/Menus. xxxxxx = menu name.
{LOGO} The site's logo as defined in the admin preferences.
{MENU=1} Menu Area as allocated using the media-manager in admin. Add multiple areas by incrementing the numeric value.
{MENU: type=xxxxxx} When xxxxxx is NOT a number, it will attempt to render a specific menu with the name xxxxxx. eg. {MENU=contact} will render e107_plugins/contact/contact_menu.php
{NAVIGATION=xxxxx} Bootstrap-style navigation. Where xxxxx is one of: main, side, footer, alt, alt5, alt6 eg. {NAVIGATION=footer}
{SETSTYLE=xxxxxx} A special shortcode which is used to dynamically change the value of $style as used inside tablerender() to the value of xxxxxx.
{SETIMAGE: w=x} A special shortcode which is used to dynamically change the size of avatars and other images. x= numerical value. eg. {SETIMAGE: w=100&h=200&crop=1}
{SITEDESCRIPTION} The description of the website as defined in the admin preferences.
{SITEDISCLAIMER} The site disclaimer as defined in the admin preferences. Typically used in the footer of the site.
{SITENAME} The name of the website as defined in the admin preferences.
{WMESSAGE} Renders the welcome message as defined in admin-> Welcome Message.



Usage example:

		$LAYOUT['default'] = "
    <header>{SITENAME}<header>
    <div>{NAVIGATION=main}</div>
    {SETSTYLE=menu}
    <div class='span2'>
    {MENU=1}
    {MENU=contact}
    </div>
    <div class='span10'>
    {SETSTYLE=default}

 {---}

    </div>
    <footer>{SITEDISCLAIMER}</footer>
";

function tablestyle($caption, $text, $mode='')
{
    global $style; // value defined by {SETSTYLE} shortcode. 
 
    switch($style) 
     {
        case 'menu': 
            echo "<h5>".$caption."</h5>";
            echo $text;
        break;

        default: 
            echo "<h2>".$caption."</h2>";
            echo $text;
        break;
    }
    
}

News


Shortcode Description Optional Parameters
{NEWS_ID} Unique ID for the current news item (news_id)
{NEWS_TITLE} News Title
{NEWS_SUMMARY} News item summary
{NEWS_DATE} News Date
{NEWS_BODY} News Body (main content)
{NEWS_TAGS} New Keywords/Meta-Keywords
{NEWS_URL} News URL (current URL)
{NEWS_AUTHOR} Name of the Author of the news item
{NEWS_AUTHOR_AVATAR} Avatar of the Author of the news item
{NEWS_AUTHOR_SIGNATURE} Signature text of the Author of the news item. eg. a short bio about the user.
{NEWS_AUTHOR_ITEMS_URL} Link to a News page listing all items by the same author.
{NEWS_CATEGORY_NAME} News Category Name
{NEWS_CATEGORY_DESCRIPTION} News Category Description
{NEWS_CATEGORY_ICON} News Category Icon
{NEWS_RELATED} Related news items based on keyword matches types: news | page
limit: (integer) (default is 5)

Page/Menu


Shortcode Description Optional Parameters
{CPAGEANCHOR}
{CPAGETITLE} Title of the page
{CPAGEBODY} Main text body of the page
{CPAGEAUTHOR} Author of the page
{CPAGEDATE} Creation date of the page {CPAGEDATE=x} default: long. 'short' and 'relative'
{CPAGEMETADIZ} Meta description of the page.
{CPAGEBUTTON}
{BOOK_ANCHOR}
{BOOK_DESCRIPTION}
{BOOK_ICON}
{BOOK_ID}
{BOOK_NAME}
{BOOK_URL}
{CHAPTER_ANCHOR}
{CHAPTER_BREADCRUMB}
{CHAPTER_BUTTON}
{CHAPTER_DESCRIPTION}
{CHAPTER_ICON}
{CHAPTER_ID}
{CHAPTER_NAME}
{CHAPTER_URL}

style.css

This file should contain the primary css for your theme.
Keep in mind that e107 v2.x uses bootstrap naming conventions.

theme_shortcodes.php

OPTIONAL e107 v2.x removes the need for separate xxxxxx.sc files inside your theme's folder. You can now include all your theme-specific shortcodes in a single file. These shortcodes may be used in the $LAYOUT of your theme.php file. eg. Using the example below: {MY_SHORTCODE} and {MY_OTHER_SHORTCODE}

		class theme_shortcodes extends e_shortcode
{
	
    function sc_my_shortcode()
    {
        return "Something";
    }

    function sc_my_other_shortcode()
    {
        return "Something else";
    }

}

theme_config.php

OPTIONAL Adds information and user-selectable options to the theme's configuration page.

		class theme_mytheme implements e_theme_config
{
    function process() // Save posted values from config() fields. 
    {
        $pref = e107::getConfig();
		
        $theme_pref 					= array();
        $theme_pref['example']			= $_POST['_blank_example'];
        $theme_pref['example2'] 	= intval($_POST['_blank_example2']);

        $pref->set('sitetheme_pref', $theme_pref);
        return $pref->dataHasChanged();
    }

    function config()
    {
        $tp = e107::getParser();
		
        $var[0]['caption'] = "Sample configuration field";
        $var[0]['html'] = $tp->text('_blank_example', e107::getThemePref('example', 'default'));

        $var[1]['caption'] = "Sample configuration field";
        $var[1]['html'] = $tp->text('_blank_example2', e107::getThemePref('example2', 'default'));
		
        return $var;
    }

    function help()
    {
        return "
                <div class='well'>
                        Some information about my theme. 
                </div>
        ";
    }
}

Overriding Core Templates

  • All templates that are used in e107 can be overridden by copying them into specific folders within your current theme folder. 
  • Core themes (located in e107_core/templates/ ) should be copied into e107_themes/YOURTHEME/templates/ 
  • Plugin templates should be copied into e107_themes/YOURTHEME/templates/PLUGIN-FOLDER
    Note: Older plugins may look for templates in the root folder of your theme. ie. e107_theme/YOURTHEME/  

Some examples to illustrate this:
1) The comment template is a core template, as it is located in e107_core/templates/. To override this template, copy the file to e107_themes/your_theme_folder/templates/.

2) The news template is located in e107_plugins/news/. To override this template, copy the file over to e107_themes/your_theme_folder/templates/news/.

3) The same for, for example, the chatbox menu template. The chatbox_menu template is located in e107_plugins/chatbox_menu. Copy the template over to e107_themes/your_theme_folder/templates/chatbox_menu/

Important: For overriding plugin templates, the folder name within your_theme_folder/templates/ directory must match the exact plugin folder name. 

Upgrading v1.x Themes

Themes developed for v1.x of e107 will continue to work using v2.x. However, to get the most out of v2.x, we suggest the following changes be made to bring your theme up to the new v2.x standards. Replace $HEADER and $FOOTER with $LAYOUT['default'] combining both of them into a single template. Place a {---} between them so e107 knows where to split it into HEADER and FOOTER. Replace any occurrences of $CUSTOMHEADER and $CUSTOMFOOTER with $LAYOUT['custom'] (see above) If you have recurring code in your $LAYOUT. eg. Navigation html which should be included as the header and footer of every layout, then use the special layouts: $LAYOUT['_header_'] and $LAYOUT['__footer_']. If your theme contains links to external social pages such as facebook, twitter, youtube or google+, use the core definitions for them. ie. XURL_FACEBOOK, XURL_TWITTER, XURL_YOUTUBE, XURL_GOOGLE. Remove any reference to $CUSTOMPAGES and place them inside theme.xml in the layouts section.
<layout name='custom' title='Custom Pages'>
    <custompages>FRONTPAGE</custompages>
    <custompages>/forum/</custompages>
</layout>
If you have used index.php in your $CUSTOMPAGES list, use FRONTPAGE instead (see above) The function theme_head() has been deprecated. Instead, use either e107::css() or e107::js() to include what you require in the header. (see bootstrap or other new core theme for examples) Shortcodes need to be set to UPPERCASE in all occurrences in your theme.php file. Remove all references to $register_sc['xxxxx'] from theme.php for shortcodes used in the $LAYOUT. Place the contents of all xxxxxx.sc files used by $LAYOUT ($HEADER and $FOOTER) inside theme_shortcodes.php and then remove these xxxxxx.sc files from your theme's folder.

Templating/Shortcodes

Utilizing e107's Templating and Shortcode engine.

Templating Overview

  • Templates and shortcodes function together to allow a developer to place dynamic content into their code.
  • Templates are portions of HTML which contain markers that are replaced by dynamic content when parsed e107's parseTemplate()function.
  • These markers are called 'shortcodes'.
  • A shortcode is always CAPITALIZED and is surrounded by curly brackets and it may contain letters and underscores. For example: {MY_SHORTCODE}
  • Each shortcode has a corresponding function/method which is run during the parsing of the template. These functions are always lowercase and begin with the prefix sc_ . eg. sc_my_shortcode(). This means that {MY_SHORTCODE} is replaced by what is returned by sc_my_shortcode().
  • Shortcodes may also contain parameters which are sent to the corresponding method. For example: {MY_SHORTCODE: x=foo&y=bar}

Creating Templates

Create a folder called templates inside your plugin directory, and inside create an empty file using the name of your plugin folder, followed by _template.php. eg. myplugin_template.php Inside this file add an array by the same name, but in UPPERCASE: eg. $MYPLUGIN_TEMPLATE['xxxx'] xxxx can be anything you want, but we suggest using start, item, end etc. when applicable. This value should always be lowercase. Here's a simple example of the contents of myplugin_template.php:

		<?php

$MYPLUGIN_TEMPLATE['start'] = "<ul>";
$MYPLUGIN_TEMPLATE['item'] = "<li>{MYPLUGIN_ITEM}</li>";
$MYPLUGIN_TEMPLATE['end'] = "</ul>";

?>

If your plugin will use several different types of templates, eg. a listing page and an input form. You can do something like this:

		<?php

$MYPLUGIN_TEMPLATE['list']['start'] = "<ul>";
$MYPLUGIN_TEMPLATE['list']['item'] = "<li>{MYPLUGIN_ITEM}</li>";
$MYPLUGIN_TEMPLATE['list']['end'] = "</ul>";

$MYPLUGIN_TEMPLATE['form']['start'] = "<form>";
$MYPLUGIN_TEMPLATE['form']['body'] = "<div>{MYPLUGIN_FORMINPUT}</divi>";
$MYPLUGIN_TEMPLATE['form']['end'] = "</form>";

?>

Loading Templates

You may load a template file in the following way:

$template   = e107::getTemplate('myplugin'); // loads e107_plugins/myplugin/templates/myplugin_template.php

You can now use the $template array for parsing.

Example
$text = e107::getParser()->parseTemplate($template['start'], true, $scObj); 

// or

$text = e107::getParser()->parseTemplate($template['form']['start'], true, $scObj);



Creating Shortcodes

Create an empty file in your plugin directory called myplugin_shortcodes.php where myplugin is the name of your plugin's folder.
Add the following code replacing myplugin with the name of your plugin's folder.

class myplugin_shortcodes extends e_shortcode
{
    // Enter Shortcode methods here
}

Add your shortcode methods using the sc_ prefix and what follows in lower case.
In the example below we will create a shortcode for {SAY_HELLO} which will say 'hello' to the logged in user.
class myplugin_shortcodes extends e_shortcode
{
    function sc_say_hello($parm='')
    {
       return "Hello ".USERNAME;
    }
}

Advanced example using shortcode parameters. eg. {SAY_HELLO: name=john}

class myplugin_shortcodes extends e_shortcode
{
    function sc_say_hello($parm)
    {
       return "Hello ".vartrue($parm['name']);
    }
}

Advanced example using database values. See $sc->setVars($row); in example below.

class myplugin_shortcodes extends e_shortcode
{
    function sc_say_hello($parm)
    {
       return "Hello ".vartrue($this->var['name']);
    }
}

Loading Shortcodes

Loading shortcodes may be done in the following way:

$sc = e107::getScBatch('myplugin',TRUE); // loads e107_plugins/myplugin/myplugin_shortcodes.php



Putting it all together

Parsing the Template

Use the parseTemplate() method from the text-parser class to replace shortcodes with their real value.
$tp->parseTemplate('template','use-core-shortcodes','shortcode-class');

Basic Example

$template   = e107::getTemplate('myplugin', 'form'); // load the 'form' template from the plugin folder. 
$tp = e107::getParser(); // get Parser Class.
$sc = e107::getScBatch('myplugin',true); // get myplugin shortcodes from plugin folder. 

echo $tp->parseTemplate($template['start'], true, $sc); // parse the 'start' part of the 'form' template.

Full Example with loop

$sql = e107::getDb(); // get the database Class. 
$tp = e107::getParser(); // get Parser Class.
$sc = e107::getScBatch('myplugin',true); // get myplugin shortcodes from plugin folder. 

$template   = e107::getTemplate('myplugin', 'list'); // get template array of 'list' from plugin folder. 

echo $tp->parseTemplate($template['start'], true, $sc); // parse the 'start' part of the 'list' template.

$rowArray = $sql->retrieve("SELECT field FROM #myplugin", true);	// load the values from the plugin's database table. 

foreach($rowArray as $row)    // loop through the database results. 
{
	$sc->setVars($row);	    // send the value of the $row to the class. 
	echo $tp->parseTemplate($template['item'], false, $sc);    // parse the 'item' 
}

echo $tp->parseTemplate($template['end'], false, $sc); // parse the 'end' part of the 'list' template.









Social Links