api php

From twext

(Redirected from API)
Jump to: navigation, search

Ready to program your own TwEXT plugin? Great! You will find that it's rather simple once you understand the basics of the PHP programming language and the concepts behind the TwEXT API.

Contents

[edit] What is a TwEXT plugin?

A TwEXT Plugin is the unit of the TwEXT system. All TwEXT websites are composed of many plugins that do simple jobs (very well!) and that are chosen to do the job by the user. This is done thru the user preferences editor (which in turn is actually another plugin!).

image:PluginPages.png

From the outside, the user sees the plugin as either a file/page or a module being executed by the server. The whole concept of the plugin is transparent to the user (hey! it's just another page!).

image:PluginCore.png

From the inside, each plugin is a separate and independent module that may be executed at any time by the TwEXT core engine (the thing that keeps the system alive and orchestrated). A plugin receives data, operates on it and then returns a display/output of the data or calls another plugin with the procesed data. The TwEXT core engine also contains the functionality needed to store and retrieve data from a database.

[edit] What is the TwEXT API?

All major platforms have some way of being expanded. In order to do that, a standard way of accessing the internal functionality must be established, this is done through a series of library functions called API or Application Programming Interface.

The TwEXT API is the glue that binds all the plugins together and allows them to communicate with another by using a standardized way for programming plugins and accessing resources. It also includes support for several common functions (like database access and session management) through the use of TwEXT objects.

The best way to see how the API works is to actually see the source code (usually a file called twext.php3, there you will get a glimpse of all the defined support functions, TwEXT classes and definitions/constants. It is (in my opinion) very easy to understand and has many of the major/interesting parts commented.

[edit] How is the data stored?

The data is stored using an DBMS (DataBase Management System). This means that any database software that is supported by PHP may be used by TwEXT to store data (provided that you have the appropriate TwextDatabase class to access it). By default, TwEXT supports MySQL because it's easy to acquire and to maintain (also because it's also PHP's default DBMS).

image:PluginData.png

This data is logically separated by groups called tables (all these are contained within the DBMS). Each table has a section that stores a different data type. Please take a look at the SQL dump of TwEXT to see what fields are available. By the way, this same dump may be inserted into another DBMS (Oracle, Sybase, PostgreSQL, etc.) for access by TwEXT.

At this moment, the following tables exist in TwEXT:

  • preferences List of preferences available for user selection
  • user Contains all of the users and some personal data
  • languages List of all available languages
  • user_prefs Actual user preferences
  • remote_plugins List of all available plugins
  • atoms Bulk storage of all translated chunks/phrases
  • versions Available TwEXT versions on this TwEXT Server
  • session_type List of available session types
  • prefs_defaults Default preferences for all users (used if none selected)
  • documents Keeps all the user documents (this is the good stuff!)

[edit] What are the TwEXT Classes?

In Object Oriented Programming, a class defines how and object will be like (in characteristics and behaviour). Since TwEXT is built upon an OOP foundation, it relies on objects to deliver tasks and allows abstraction of the inner workings of TwEXT to the Plugin programmer (the programmer doesn't need to know how TwEXT works in order to program for it). Also, OOP (and because of that, TwEXT's classes) allow inheritance, that means that anyone can take an existing class and work from it's current functionality to build something better by only modifying what needs to be changes (i.e. if you want to build a better TwextSession management, you just work from the current one and add more to it!).

At this moment, the available TwEXT classes are:

  • TwextDatabase
  • TwextPreferences
  • TwextLinguas
  • TwextSession
  • TwextPlugIn

The following listing is an usage example of source code using the TwEXT class TwextDatabase:

$database = new TwextDatabase();
$sql_result = $database->query("SELECT value FROM atoms WHERE lang_id=0");
// Store the resulting data in $row
$row = $database->fetchNextRow($sql_result);
$database->close();

What we just did right there is connect to the TwEXT database, query some information from it and disconnect (easy!), that just leaves the cool stuff to the Plugin programmer. Here is the actual source code of the TwEXT class (TwextDatabase), please notice how we also separated everything into logical parts for easy expansion:

/*
	TwextDatabase

	Database access should be done thru this class, this will
	bring a nice layer of abstraction to TwEXT and will make
	it portable accross several DBMS

	If you want to implement connectivity with another DBMS,
	extend this class and override the apropriate methods so
	as to change the call to whatever your DBMS will need
*/

class TwextDatabase {

	var $sqlid;

	function TwextDatabase() {
		$this->sqlid = mysql_connect(TWEXT_DBMS_SERVER, TWEXT_DBMS_USER,
					TWEXT_DBMS_PASSWORD) or
					die (TWEXT_DBMS_ERROR_CONNECT);
		$res = mysql_query("use twext_db", $this->sqlid) or
					die (TWEXT_DBMS_ERROR_QUERY);
	}

	function close() {
		return mysql_close($this->sqlid);
	}

	function query($query_str) {
		$sql_result = mysql_query($query_str, $this->sqlid) or
					die ($MESSAGE_DBQUERY_ERROR);
		return $sql_result;
	}

	function rowCount($sql_result) {
		return mysql_num_rows($sql_result);
	}

	function affectedRowsCount($sql_result) {
		return mysql_affected_rows($sql_result);
	}

	function fetchNextRow($sql_result) {
		return mysql_fetch_row($sql_result);
	}

	function cryptPassword($plain) {
		// Most DBMS's support this function, if yours doesn't
		// just go ahead and call PHP's own crypt ;)
		$res = $this->query("SELECT password('$plain')", $this->sqlid);
		$row = $this->fetchNextRow($res);
		return $row[0];
	}

	function getNextIdForTable($table) {
		// NOTE: race conditions may exist here, hehehe... carefull!
		$res = $this->query("
				SELECT id
				FROM $table
				ORDER BY id DESC",
				$this->sqlid);
		if ($this->rowCount($res) > 0) {
			$row = $this->fetchNextRow($res);
			return ($row[0] + 1);
		}
		return 0;
	}

}

[edit] What is the TwEXT execution cycle like?

Everytime a user logs in to the system, a new session is created and is kept through out the user's stay at TwEXT. Every action the user takes is part of a series of stages where the user moves around the TwEXT system, this is known as a TwEXT execution cycle, beginning from the logon until the user logs out.

image:PluginData.png

[edit] Login

The user is greeted by the system while asking for a nick and password, when the user enters this data, the form will call the first plugin in the TwEXT system: the Startup plugin.

[edit] Startup

The startup plugin initializes the TwEXT session after it validates the user. It may also check for preferences integrity, it does not necessarily display any information to the user, that is done so by the Welcome Plugin.

[edit] Welcome Plugin

This is a normal plugin (can be any of the plugins in the system), the difference is that it is the first plugin that the user will have any interaction with and has a special section in the user preferences.

[edit] Plugin

This is the unit of the TwEXT system. All TwEXT servers will have at least some basic plugins to provide interaction with the documents and allow translation from the user.

The idea is that a plugin does a single task and does it well.

[edit] Logout

Final stage of a TwEXT session (and the user's stay in the system). Internally this means that the session will close (together with DBMS and other connections). Optionally each TwEXT system will have some type of cleanup routines to be done here.

[edit] Rules for TwEXT Plugins

To be considered as guidelines as to happy Plugin hacking, these rules are something to remember when programming for TwEXT Plugins.

  1. A plugin is a single file that can be named anything as long as it has the .phpN extension (where N is the curren PHP version for the TwEXT system).
  2. The plugin file will be stored in the plugins directory.
  3. If the plugin needs/uses extra files (more PHPs or images), it will store them within the plugins directory under the same name as the plugin but with the _data extension.
  4. All generic/common system images will be taken/used from the plugins/pix subdirectory.
  5. All plugins must subclass the TwextPlugIn class and override with the apropriate values as to provide information about itself to the system.
  6. A plugin use or not a TwEXT session, some plugins (like the ones that create users) don't need to validate a user or carry a session, it's all right not to follow session management as long as the next to be called plugin isn't affected.
  7. If a plugin creates a user, it will need to add an entry into the user database table and provide the user with default values for preferences (from the preferences table) and store them in the user_prefs table. For user deletion, the entries for user_prefs and the entry for user will have to be deleted.
  8. When adding a new language, an entry with the language data should be included in the languages database table and all the current atoms for the base language should be translated and stored in the atoms database table.
  9. HTML utility/helper functions should be used as much as possible (such as printPageHeader and printPageTail) as to provide a standard look & feel to all the plugins.
  10. Regular text inside Plugins should be kept at a minimal (if any), atoms should be used instead (see TwextLinguas class).
  11. more to come... ;)

[edit] A basic TwEXT Plugin

Here we present two plugin examples, these include the basic funcionality that all plugins must have. The first one does not use session management (this should be uncommon, but possible), the second uses session managemente and should resemble any ordinary plugin.

[edit] Create User Plugin Source

<?php
/*
	Create User Plugin
	Roberto Machorro <rmach@ciberlinux.net>

	Adds a user to the system with the default preference values.
	Since we are not managing a user (or her data) we don't need to
	setup a session, just work directly with the TwextDatabase object
	($database).
*/

include "../twext.php3";

class create_user extends TwextPlugIn {

	var $name = "Simple Create User Plugin";
	var $description = "Adds a new user to the TwEXT system with default prefs.";

	var $version = 0.1;
	var $twext_version = TWEXT_API_VERSION;

	var $author = "Roberto Machorro";
	var $author_email = "rmach@ciberlinux.net";

	var $maintainer = "Roberto Machorro";
	var $maintainer_email = "rmach@ciberlinux.net";

}

$database = new TwextDatabase();

printPageHeader("TwEXT - New User Creation");

if ($have_data == "yes") {
	$sql_result = $database->query("SELECT id FROM user WHERE nick='$nick'");
	$row_count = $database->rowCount($sql_result);
	if (($row_count == 0) && ($passwd1 == $passwd2)) {
		// First we add the user to the user table
		$id = $database->getNextIdForTable("user");
		$crypted_pass = $database->cryptPassword($passwd1);
		$sql_result = $database->query("
			INSERT INTO user
			VALUES ($id, '$nick', '$crypted_pass', '$full_name', '$email')");
		// Now we assign the user the default preferences
		$prefs = new TwextPreferences($nick);
		$count = $prefs->getPreferencesCount();
		for ($i=0; $i<$count; $i++) {
			$value = $prefs->getDefaultPreferenceValue($i);
			$prefs->insertPreferenceValue($i, $value);
		}
		?>
		<H1>You are ready to login!</H1>
		You have been assigned default values to your preferences, which you
		may change when you <A HREF="../">login</A> to TwEXT.
	<?php } else { ?>
		<H1>Darn!</H1>
		Either your user already exists, your password was dumb or you didn't
		type in the same password. Your user was not created, you need to try
		<A HREF="create_user.php3">again</A>.
	<?php }
} else { ?>
	<H1>Creating new user!</H1>
	Please fill in with your data:<P>
	<FORM ACTION="create_user.php3" METHOD="post">
	<INPUT TYPE=hidden NAME="have_data" VALUE="yes">
	Name: <INPUT TYPE=text NAME="full_name" SIZE=25 MAXLENGTH=40><BR>
	E-mail: <INPUT TYPE=text NAME="email" SIZE=25 MAXLENGTH=50><P>
	User (nick): <INPUT TYPE=text NAME="nick" SIZE=10 MAXLENGTH=8><BR>
	Password: <INPUT TYPE=password NAME="passwd1" SIZE=10 MAXLENGTH=8><P>
	Password (again): <INPUT TYPE=password NAME="passwd2" SIZE=10 MAXLENGTH=8><P>
	<INPUT TYPE="submit" VALUE="Create User"> 
	<INPUT TYPE="reset" VALUE="Erase Form">
	</FORM>
<?php }

printPageTail();
?>

[edit] Simple Demo Test Plugin

<?php
/*
	Simple Demo/Test Plugin
	Roberto Machorro <rob@machorro.net>

	This is plugin demonstrates the basic parts of a TwEXT plugin by
	adhereing to the current standards. Please notice that we derive
	from the TwextPlugIn class (this will provide to the TwEXT system
	information about the plugin), we have session management (validating
	the user and providing personal data), access to the user's preferences
	(via TwextPreferences) and i18n (internationalization) via the
	TwextLinguas class.
*/

include "../twext.php3";

class demo_test extends TwextPlugIn {

	var $name = "Simple Plugin for Programmers Entertaintment";
	var $description = "This is plugin demonstrates the basic parts of a TwEXT plugin";

	var $version = 0.1;
	var $twext_version = TWEXT_API_VERSION;

	var $author = "Roberto Machorro";
	var $author_email = "rmach@ciberlinux.net";

	var $maintainer = "Roberto Machorro";
	var $maintainer_email = "rmach@ciberlinux.net";

}

$session = new TwextSession($user, $passwd);
$prefs = new TwextPreferences($user);
$user_id = $session->getUserID();
$atoms = new TwextLinguas($user_id);

printPageHeader("TwEXT Plugin Demo/Test");

if ($session->validity() == false) {
	die("Whoops! Bad user or invalid session!");
}

// Notice that we are getting our message from the atoms table
$greeting = $atoms->getDefaultAtomString(1);

$user_name = $session->getUserName();
$user_mail = $session->getUserEmail();

print "$greeting <A HREF=\"mailto:$user_mail\">$user_name</A><P>";

?>

<?php printPageTail(); ?>

080615: PHP IS BACK


Retrieved from "http://twext.com/api_php"
Personal tools