Index: branches/2.2/workflow/inc/local/functions/function.wf_create_object.php
===================================================================
--- branches/2.2/workflow/inc/local/functions/function.wf_create_object.php	(revision 795)
+++ branches/2.2/workflow/inc/local/functions/function.wf_create_object.php	(revision 3167)
@@ -5,5 +5,5 @@
  * @return mixed
  * @license http://www.gnu.org/copyleft/gpl.html GPL
- * @deprecated 1.4.00.000 - 08/03/2007
+ * @deprecated 2.2.00.000
  * @package Workflow 
  * @subpackage local 
@@ -12,4 +12,5 @@
 function wf_create_object($class_name)
 {
+	wf_warn_deprecated_method('Factory', 'getInstance');
 	$obj = null;
 	$file_name = PHPGW_SERVER_ROOT.SEP.'workflow'.SEP.'inc'.SEP.'local'.SEP.'classes'.SEP.'class.'.$class_name.'.php';
Index: branches/2.2/workflow/inc/local/classes/class.wf_workitem.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_workitem.php	(revision 795)
+++ branches/2.2/workflow/inc/local/classes/class.wf_workitem.php	(revision 3167)
@@ -29,5 +29,5 @@
 	public function wf_workitem()
 	{
-		$this->db = &$GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID;
+		$this->db = &Factory::getInstance('WorkflowObjects')->getDBGalaxia()->Link_ID;
 		$this->processID = (int) $GLOBALS['workflow']['wf_runtime']->activity->getProcessId();
 	}
Index: branches/2.2/workflow/inc/local/classes/class.wf_role.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_role.php	(revision 1048)
+++ branches/2.2/workflow/inc/local/classes/class.wf_role.php	(revision 3167)
@@ -57,7 +57,7 @@
 			$this->processID = (int) $GLOBALS['workflow']['job']['processID'];
 
-		$this->db = &$GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID;
-		$this->roleManager = CreateObject('workflow.workflow_rolemanager');
-		$this->activityManager = CreateObject('workflow.workflow_activitymanager');
+		$this->db = &Factory::getInstance('WorkflowObjects')->getDBGalaxia()->Link_ID;
+		$this->roleManager = Factory::getInstance('workflow_rolemanager');
+		$this->activityManager = Factory::getInstance('workflow_activitymanager');
 	}
 
@@ -186,5 +186,5 @@
 			$users = array((int) $users);
 		$roleID = $this->roleManager->get_role_id($this->processID, $roleName);
-		$ldap = &$GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP');
+		$ldap = Factory::getInstance('WorkflowLDAP');
 		foreach ($users as $user)
 		{
@@ -212,5 +212,5 @@
 		$users = $this->roleManager->list_mapped_users($this->processID, false, array('wf_role_name' => $roleName));
 
-		$ldap = &$GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP');
+		$ldap = Factory::getInstance('WorkflowLDAP');
 		$output = array();
 		foreach ($users as $id => $login)
@@ -367,5 +367,5 @@
 
 		/* get the roles */
-		$userGroups = $GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP')->getUserGroups($userID);
+		$userGroups = Factory::getInstance('WorkflowLDAP')->getUserGroups($userID);
 		$query = 'SELECT DISTINCT role.wf_role_id, role.wf_name, role.wf_description FROM egw_wf_roles role, egw_wf_user_roles user_role WHERE (user_role.wf_role_id = role.wf_role_id) AND (role.wf_p_id = ?) AND (role.wf_role_id = ANY (?))';
 		$query .= ' AND (((user_role.wf_user = ?) AND (user_role.wf_account_type = ?))';
Index: branches/2.2/workflow/inc/local/classes/class.wf_instance.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_instance.php	(revision 1385)
+++ branches/2.2/workflow/inc/local/classes/class.wf_instance.php	(revision 3167)
@@ -77,5 +77,5 @@
 	{
 		$instanceID = (int) $instanceID;
-		$instance = CreateObject('workflow.workflow_instance');
+		$instance = Factory::getInstance('workflow_instance');
 		if (!$instance->getInstance($instanceID))
 			return false;
@@ -92,5 +92,5 @@
 	{
 		/* load the DB */
-		$this->db = &$GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID;
+		$this->db = &Factory::getInstance('WorkflowObjects')->getDBGalaxia()->Link_ID;
 
 		/* load the process ID from the runtime */
@@ -118,5 +118,5 @@
 		$instance = $this->getInstanceObject($instanceID);
 
-		$runActivity = CreateObject('workflow.run_activity');
+		$runActivity = Factory::getInstance('run_activity');
 
 		ob_start();
@@ -250,29 +250,44 @@
 
 	/**
-	* Busca as instâncias filhas de uma instância
-	* Se os parâmetros não forem informados, retorna instâncias filhas das instância atual.
-	* @param int $instanceID O ID da instância pai (não obrigatório).
-	* @param int $activityID O ID da atividade corrente da instância pai
-	* @return array As instâncias filhas do par instância/atividade atual
-	* @access public
-	*/
-	public function getChildren($instanceID = null, $activityID = null)
+	* This method gets all children instances of the given instance.
+	* If there is no parameter, it gets the children instances of the current instance
+	* @param int $instanceID Dad instance's identification.
+	* @return array Array with the children instances, or false
+	* @access public
+	*/
+	public function getChildren($instanceID = null)
 	{
 		$output = array();
 		if (is_null($instanceID))
 			$instanceID = $GLOBALS['workflow']['wf_runtime']->instance_id;
-		if (is_null($activityID))
-			$activityID = $GLOBALS['workflow']['wf_runtime']->activity_id;
-
-		/* check instanceID */
-		if (!$this->checkInstanceAccess($instanceID, $activityID))
+
+		/* check instanceID */
+		if (!$this->checkInstanceAccess($instanceID))
 			return $output;
 
 		/* build the SQL query */
-		$query = 'SELECT i.wf_instance_id AS wf_instance_id, ia.wf_activity_id AS wf_activity_id, ia.wf_started AS wf_started, i.wf_name AS wf_name, i.wf_status AS wf_status, ia.wf_user AS wf_user, ir.wf_parent_lock AS wf_parent_lock ';
-		$query .= 'FROM egw_wf_interinstance_relations ir, egw_wf_instances i LEFT JOIN egw_wf_instance_activities ia ON (ia.wf_instance_id = i.wf_instance_id)';
-		$query .= 'WHERE (ir.wf_child_instance_id = i.wf_instance_id) AND (ir.wf_parent_instance_id = ?) AND (ir.wf_parent_activity_id = ?)';
-
-		$result = $this->db->query($query, array($instanceID, $activityID));
+		$query = "
+			SELECT
+				i.wf_instance_id AS wf_instance_id,
+				ia.wf_activity_id AS wf_activity_id,
+				i.wf_started AS wf_started,
+				i.wf_name AS wf_name,
+				i.wf_status AS wf_status,
+				ia.wf_user AS wf_user,
+				ir.wf_parent_lock AS wf_parent_lock
+			FROM
+			    egw_wf_interinstance_relations as ir
+			LEFT JOIN
+			    egw_wf_instances as i
+			ON
+			    i.wf_instance_id = ir.wf_child_instance_id
+			LEFT JOIN
+			    egw_wf_instance_activities as ia
+			ON
+			    i.wf_instance_id = ia.wf_instance_id
+			WHERE
+			    ir.wf_parent_instance_id = ?";
+
+		$result = $this->db->query($query, array($instanceID));
 		$output = $result->GetArray(-1);
 
@@ -423,6 +438,5 @@
 
 		/* load the required instance (for the required user) */
-		require_once GALAXIA_LIBRARY . SEP . 'src' . SEP . 'GUI' . SEP . 'GUI.php';
-		$GUI = new GUI($GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID);
+		$GUI = &Factory::newInstance('GUI');
 		$userInstance = $GUI->gui_list_user_instances($userID, 0, -1, '', '', "(ga.wf_is_interactive = 'y') AND (gia.wf_activity_id = {$activityID}) AND (gia.wf_instance_id = {$instanceID})", false, $this->processID, true, false, true, false, false, false);
 		$userInstance = $userInstance['data'];
@@ -456,9 +470,6 @@
 		if ($userID !== '*')
 		{
-			require_once dirname(__FILE__) . '/class.wf_role.php';
-			require_once dirname(__FILE__) . '/class.wf_engine.php';
-
-			$wfRole = new wf_role();
-			$engine = new wf_engine();
+			$wfRole = Factory::getInstance('wf_role');
+			$engine = Factory::getInstance('wf_engine');
 			/* get information about the activity */
 			if (($activityInfo = $engine->getActivityInformationByID($activityID)) === false)
@@ -529,6 +540,5 @@
 
 		/* try to get the role id */
-		require_once dirname(__FILE__) . '/class.wf_role.php';
-		$wfRole = new wf_role();
+		$wfRole = Factory::getInstance('wf_role');
 		if (($roleID = $wfRole->getRoleIdByName($roleName)) === false)
 			return false;
Index: branches/2.2/workflow/inc/local/classes/class.wf_engine.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_engine.php	(revision 795)
+++ branches/2.2/workflow/inc/local/classes/class.wf_engine.php	(revision 3167)
@@ -68,5 +68,5 @@
 		$flagObject[0] = is_null($this->processManager);
 		if ($flagObject[0])
-			$this->processManager = CreateObject('workflow.workflow_processmanager');
+			$this->processManager = Factory::getInstance('workflow_processmanager');
 
 		$output = array();
@@ -86,10 +86,10 @@
 	* @return bool true caso a instância tenha sido continuada e false caso contrário.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function continueInstance($activityID, $instanceID)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'continueInstance');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->continueInstance($activityID, $instanceID);
 	}
@@ -100,10 +100,10 @@
 	* @return boolean true se foi possível abortar a instância e false caso contrário.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function abortInstance($instanceID)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'abort');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->abort($instanceID);
 	}
@@ -115,10 +115,10 @@
 	* @return boolean true se foi possível mudar o nome da instância e false caso contrário.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function setInstanceName($instanceID, $name)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'setName');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->setName($instanceID, $name);
 	}
@@ -130,10 +130,10 @@
 	* @return boolean true se foi possível mudar a prioridade da instância e false caso contrário.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function setInstancePriority($instanceID, $priority)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'setPriority');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->setPriority($instanceID, $priority);
 	}
@@ -145,10 +145,10 @@
 	* @return array As instâncias que satisfazem o critério de seleção.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function getIdleInstances($numberOfDays, $activities = null)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'getIdle');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->getIdle($numberOfDays, $activities);
 	}
@@ -159,8 +159,9 @@
 	* @return array As instâncias que satisfazem o critério de seleção.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function getInstances($activities = null)
 	{
+		wf_warn_deprecated_method('wf_instance', 'getIdle');
 		return $this->getIdleInstances(0, $activities);
 	}
@@ -171,10 +172,10 @@
 	* @return array As instâncias que satisfazem o critério de seleção.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function getInstancesByName($name)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'getByName');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		$preOutput = $WFInstance->getByName($name);
 		$output = array();
@@ -193,11 +194,11 @@
 	* @return array As instâncias filhas do par instância/atividade atual
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function getChildInstances($instanceID = null, $activityID = null)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
-		$preOutput = $WFInstance->getChildren($instanceID, $activityID);
+		wf_warn_deprecated_method('wf_instance', 'getChildren');
+		$WFInstance = &Factory::getInstance('wf_instance');
+		$preOutput = $WFInstance->getChildren($instanceID);
 		$output = array();
 		foreach ($preOutput as $childInstance)
@@ -213,10 +214,10 @@
 	* @return mixed Uma array contento as propriedades da instância (no formato "nome_da_propriedade" => "valor"). Ou false em caso de erro.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function getInstanceProperties($instanceID)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'getProperties');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->getProperties($instanceID);
 	}
@@ -227,10 +228,10 @@
 	* @return array Propriedades da instância filha. Array no formato "nome_da_propriedade" => "valor".
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function getChildInstanceProperties($instanceID)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'getProperties');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->getProperties($instanceID);
 	}
@@ -247,5 +248,5 @@
 		$flagObject[0] = is_null($this->acl);
 		if ($flagObject[0])
-			$this->acl = CreateObject('workflow.workflow_acl');
+			$this->acl = Factory::getInstance('workflow_acl');
 
 		$output = $this->acl->getUserPermissions($type, $uid);
@@ -268,5 +269,5 @@
 		$flagObject[0] = is_null($this->acl);
 		if ($flagObject[0])
-			$this->acl = CreateObject('workflow.workflow_acl');
+			$this->acl = Factory::getInstance('workflow_acl');
 
 		$output = $this->acl->getUserGroupPermissions($type, $uid);
@@ -291,5 +292,5 @@
 		/* build the SQL query */
 		$query = "SELECT wf_activity_id, wf_name, wf_normalized_name, wf_type, wf_description FROM egw_wf_activities WHERE (wf_activity_id = ?) AND (wf_p_id = ?)";
-		$db = &$GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID;
+		$db = &Factory::getInstance('WorkflowObjects')->getDBGalaxia()->Link_ID;
 		$resultSet = $db->query($query, array($activityID, $processID));
 
@@ -319,5 +320,5 @@
 		/* build the SQL query */
 		$query = "SELECT wf_activity_id, wf_name, wf_normalized_name, wf_type, wf_description FROM egw_wf_activities WHERE (wf_name = ?) AND (wf_p_id = ?)";
-		$db = &$GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID;
+		$db = &Factory::getInstance('WorkflowObjects')->getDBGalaxia()->Link_ID;
 		$resultSet = $db->query($query, array($activityName, $processID));
 
@@ -342,10 +343,10 @@
 	* @return array As instâncias que satisfazem o critério de seleção.
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function getUserInstances($users, $activities = null, $status = null)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'getByUser');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->getByUser($users, $activities, $status);
 	}
@@ -356,10 +357,10 @@
 	* @return bool true caso a propriedade tenha sido alterada com sucesso
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function setInstanceProperty($instanceID, $nameProperty, $value)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'setProperty');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->setProperty($instanceID, $nameProperty, $value);
 	}
@@ -373,10 +374,10 @@
 	* @return bool true se o usuário tiver acesso à instância (levando em consideração $writeAccess) ou false caso contrário
 	* @access public
-	* @deprecated 1.7.00.000
+	* @deprecated 2.2.00.000
 	*/
 	function checkUserAccessToInstance($userID, $instanceID, $activityID, $writeAccess = true)
 	{
-		require_once 'class.wf_instance.php';
-		$WFInstance = new wf_instance();
+		wf_warn_deprecated_method('wf_instance', 'checkUserAccess');
+		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->checkUserAccess($userID, $instanceID, $activityID, $writeAccess);
 	}
Index: branches/2.2/workflow/inc/local/classes/class.wf_natural.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_natural.php	(revision 795)
+++ branches/2.2/workflow/inc/local/classes/class.wf_natural.php	(revision 3167)
@@ -1,130 +1,114 @@
 <?php
-	require_once(PHPGW_SERVER_ROOT.SEP.'workflow'.SEP.'inc'.SEP.'natural'.SEP.'class.natural.php');
+/**************************************************************************\
+* eGroupWare                                                               *
+* http://www.egroupware.org                                                *
+* --------------------------------------------                             *
+*  This program is free software; you can redistribute it and/or modify it *
+*  under the terms of the GNU General Public License as published by the   *
+*  Free Software Foundation; either version 2 of the License, or (at your  *
+*  option) any later version.                                              *
+\**************************************************************************/
+
+require_once(PHPGW_SERVER_ROOT.SEP.'workflow'.SEP.'inc'.SEP.'natural'.SEP.'class.natural.php');
+
+/**
+ * Mainframe connection to workflow
+ *
+ * TODO - This class should be removed from here. Its based on a not
+ * public protocol, thus cannot be used for everybody.
+ *
+ * @package Workflow
+ * @subpackage local
+ * @license http://www.gnu.org/copyleft/gpl.html GPL
+ * @author Everton Flávio Rufino Seára
+ */
+class wf_natural extends Natural
+{
 
 	/**
-	* Mainframe connection to workflow
-	* @author Everton Flávio Rufino Seára
-	* @package Workflow
-	* @subpackage local
-	* @license http://www.gnu.org/copyleft/gpl.html GPL
-	**/
+	 * @var object Log Object
+	 * @access private
+	 */
+	private $logger = null;
 
-	class wf_natural extends Natural
+	function __construct()
 	{
+		parent::Natural();
 
-		function __construct()
-		{
-			parent::Natural();
+		$natconf = array(
+					'mainframe_ip'			=> '',
+					'mainframe_port'		=> '',
+					'mainframe_key'			=> '',
+					'mainframe_password'	=> '',
+					'mainframe_environment'	=> ''
+		);
 
-			$natconf = array(
-						'mainframe_ip'			=> '',
-						'mainframe_port'		=> '',
-						'mainframe_key'			=> '',
-						'mainframe_password'	=> '',
-						'mainframe_environment'	=> ''
-			);
+		$nat_conf_values = &Factory::getInstance('workflow_wfruntime')->getConfigValues($natconf);
 
-			$nat_conf_values = $GLOBALS['workflow']['wf_runtime']->getConfigValues($natconf);
+		$this->setIPAddress($nat_conf_values['mainframe_ip']);
+		$this->setServerPort($nat_conf_values['mainframe_port']);
+		$this->setKey($nat_conf_values['mainframe_key']);
+		$this->setPassword($nat_conf_values['mainframe_password']);
+		$this->setApplication($nat_conf_values['mainframe_environment']);
 
-			$this->setIPAddress($nat_conf_values['mainframe_ip']);
-			$this->setServerPort($nat_conf_values['mainframe_port']);
-			$this->setKey($nat_conf_values['mainframe_key']);
-			$this->setPassword($nat_conf_values['mainframe_password']);
-			$this->setApplication($nat_conf_values['mainframe_environment']);
+		$this->logger = &Factory::getInstance('Logger', array('file'));
+	}
+
+	/**
+	 * This method MUST be called before using execute method
+	 * It specifies the natural sub-program to be accessed.
+	 *
+	 * @param Object $obj Object that specifies natural sub-program properties
+	 * @return void
+	 */
+	public function configure($obj)
+	{
+		$this->obj = $obj;
+
+		$this->initialize($obj->name);
+
+		if ($obj->server != NULL){
+			$this->setIPAddress($obj->server);
 		}
-
-		/**
-		 * Method to configure the access to mainframe
-		 * This method MUST be called before using execute method, else 'false' will be returned
-		 *
-		 * Only the first and second param are mandatory.
-		 *
-		 * @param String $subProgram - Name of sub-program
-		 * @param String $inputParameter - Input parameters to sub-program
-		 *
-		 * @param String $ip - IP Address of Mainfram
-		 * @param int $port - ServerPort to access the mainframe
-		 * @param String $key - Access key (user)
-		 * @param String $password - Key (user) password
-		 * @param char $environment - Application environment access 'D' (development) or 'P' (production)
-
-		 */
-
-		public function configure($obj)
-		{
-			$this->obj = $obj;
-
-			$this->initialize($obj->name);
-
-			if ($obj->server != NULL){
-				$this->setIPAddress($obj->server);
-			}
-			if ($obj->port != NULL){
-				$this->setServerPort($obj->port);
-			}
-			if ($obj->key != NULL){
-				$this->setKey($obj->key);
-			}
-			if ($obj->password != NULL){
-				$this->setPassword($obj->password);
-			}
-			if ($obj->environment != NULL){
-				$this->setApplication($obj->environment);
-			}
-			if ($obj->logon != NULL){
-				$this->setLogon($obj->logon);
-			}
-			if ($obj->system != NULL){
-				$this->setSystem($obj->system);
-			}
-			if ($obj->rc != NULL){
-				$this->setRC($obj->rc);
-			}
+		if ($obj->port != NULL){
+			$this->setServerPort($obj->port);
 		}
-
-		/*
-
-		public function configure($subProgram, $inputParameter, $ip = NULL, $port = NULL,
-										$key = NULL, $password = NULL, $environment = NULL, $logon = NULL, $system = NULL, $rc = NULL)
-		{
-			$this->initialize($subProgram, $inputParameter);
-
-			if ($ip != NULL){
-				$this->setIPAddress($ip);
-			}
-			if ($port != NULL){
-				$this->setServerPort($port);
-			}
-			if ($key != NULL){
-				$this->setKey($key);
-			}
-			if ($password != NULL){
-				$this->setPassword($password);
-			}
-			if ($environment != NULL){
-				$this->setApplication($environment);
-			}
-			if ($logon != NULL){
-				$this->setLogon($logon);
-			}
-			if ($system != NULL){
-				$this->setSystem($system);
-			}
-			if ($rc != NULL){
-				$this->setRC($rc);
-			}
-
+		if ($obj->key != NULL){
+			$this->setKey($obj->key);
 		}
-
-		 */
-
-		/**
-		 * Access and retrieve data from mainframe
-		 * @return bool
-		 */
-		public function execute($inputParams = "")
-		{
-			return parent::execute($inputParams);
+		if ($obj->password != NULL){
+			$this->setPassword($obj->password);
+		}
+		if ($obj->environment != NULL){
+			$this->setApplication($obj->environment);
+		}
+		if ($obj->logon != NULL){
+			$this->setLogon($obj->logon);
+		}
+		if ($obj->system != NULL){
+			$this->setSystem($obj->system);
+		}
+		if ($obj->rc != NULL){
+			$this->setRC($obj->rc);
 		}
 	}
+
+	/**
+	 * Method for accessing and retrieving data from mainframe
+	 * @return bool
+	 */
+	public function execute($inputParams = "")
+	{
+		// execute action and log wasted time
+		$totalTime = microtime(true);
+		$result = parent::execute($inputParams);
+		$totalTime = microtime(time) - $totalTime;
+		$log = sprintf("WF_NATURAL [subprogram=%s] [time=%ss]",
+					$this->obj->name,
+					number_format($totalTime,3)
+					);
+		$this->logger->debug($log);
+		return $result;
+	}
+}
 ?>
Index: branches/2.2/workflow/inc/local/classes/class.wf_location.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_location.php	(revision 795)
+++ branches/2.2/workflow/inc/local/classes/class.wf_location.php	(revision 3167)
@@ -36,5 +36,5 @@
 	function initialize()
 	{
-		$this->db = &$GLOBALS['workflow']['workflowObjects']->getDBExpresso()->Link_ID;
+		$this->db = &Factory::getInstance('WorkflowObjects')->getDBExpresso()->Link_ID;
 		$this->db->setFetchMode(ADODB_FETCH_ASSOC);
 		$this->cityInfo = array();
@@ -67,4 +67,125 @@
 		if (isset($this->cityInfo[$city_id]))
 			return $this->cityInfo[$city_id];
+
+		$sql =
+		"SELECT
+			c.id_city AS id_city,
+			c.city_name AS city_name,
+			c.is_district,
+			s.id_state AS id_state,
+			s.state_name AS state_name,
+			s.state_symbol AS state_symbol
+		FROM
+			phpgw_cc_state s,
+			phpgw_cc_city c
+		WHERE
+			c.id_state = s.id_state AND
+			s.id_country = 'BR' AND
+			c.id_city = ?";
+
+		$result = $this->db->query($sql, array($city_id));
+		$output = $result->fetchRow();
+
+		$this->cityInfo[$city_id] = $output;
+		return $output;
+	}
+
+   /**
+	* Busca as informações do estado pelo id passado
+	* @param int $state_id Numero ID do estado
+	* @return mixed (array ou boolean)
+	* @access public
+	*/
+	function getStateById($state_id)
+	{
+		if (!is_numeric($state_id))
+			return false;
+
+		$state_id = (int) $state_id;
+		if (isset($this->stateInfo[$state_id]))
+			return $this->stateInfo[$state_id];
+
+		$sql =
+		"SELECT
+			id_state,
+			state_name,
+			state_symbol
+		FROM
+			phpgw_cc_state
+		WHERE
+			id_country = 'BR' AND
+			id_state = ?";
+
+		$result = $this->db->query($sql, array($state_id));
+		$output = $result->fetchRow();
+
+		$this->stateInfo[$city_id] = $output;
+		return $output;
+	}
+    /**
+	 * Busca as cidades de um estado
+	 * @param int $state_id Numero ID do estado
+	 * @param bool $include_districts True, busca cidades e distritos. False, busca apenas cidades.
+	 * @return mixed (array ou boolean)
+	 * @access public
+	 */
+	function getCitiesFromState($state_id, $include_districts = true)
+	{
+		if (!is_numeric($state_id) || !is_bool($include_districts))
+			return false;
+
+		$state_id = (int) $state_id;
+		if (isset($this->citiesFromState[$state_id]))
+			return $this->citiesFromState[$state_id];
+
+		$where = "";
+		if(!$include_districts){
+			$where = " AND c.is_district = 'F' ";
+		}
+
+		$sql =
+		"SELECT
+			c.id_city AS id_city,
+			c.city_name AS city_name,
+			c.is_district
+		FROM
+			phpgw_cc_state s,
+			phpgw_cc_city c
+		WHERE
+			c.id_state = s.id_state AND
+			s.id_country = 'BR' AND
+			c.id_state = ? " . $where . "
+		ORDER BY
+			city_name";
+
+		$result = $this->db->query($sql, array($state_id));
+		$output = array();
+		while ($row = $result->fetchRow())
+			$output[] = $row;
+
+		$this->citiesFromState[$state_id] = $output;
+		return $output;
+	}
+    /**
+	 * Busca as cidades por parte do nome, sem considerar maiúsculas e/ou minúsculas e nem acentuação (retorna 10 resultados)
+	 * @param string Parte do nome da cidade
+	 * @param int $state_id Numero ID do estado
+	 * @param bool $include_districts True, busca cidades e distritos. False, busca apenas cidades.
+	 * @return mixed (array ou boolean)
+	 * @access public
+	 */
+	function getCitiesByKey($key, $state_id = 0, $include_districts = true)
+	{
+		if (!is_string($key) || !is_numeric($state_id) || !is_bool($include_districts))
+			return false;
+
+		$where = "";
+		if($state_id > 0){
+			$where = " AND c.id_state = " . $state_id;
+		}
+
+		if(!$include_districts){
+			$where = " AND c.is_district = 'F' ";
+		}
 
 		$sql =
@@ -81,99 +202,9 @@
 			c.id_state = s.id_state AND
 			s.id_country = 'BR' AND
-			c.id_city = ?";
-
-		$result = $this->db->query($sql, array($city_id));
-		$output = $result->fetchRow();
-
-		$this->cityInfo[$city_id] = $output;
-		return $output;
-	}
-
-   /**
-	* Busca as informações do estado pelo id passado
-	* @param int $state_id Numero ID do estado
-	* @return mixed (array ou boolean)
-	* @access public
-	*/
-	function getStateById($state_id)
-	{
-		if (!is_numeric($state_id))
-			return false;
-
-		$state_id = (int) $state_id;
-		if (isset($this->stateInfo[$state_id]))
-			return $this->stateInfo[$state_id];
-
-		$sql =
-		"SELECT
-			id_state,
-			state_name,
-			state_symbol
-		FROM
-			phpgw_cc_state
-		WHERE
-			id_country = 'BR' AND
-			id_state = ?";
-
-		$result = $this->db->query($sql, array($state_id));
-		$output = $result->fetchRow();
-
-		$this->stateInfo[$city_id] = $output;
-		return $output;
-	}
-    /**
-	 * Busca as cidades de um estado
-	 * @param int $state_id Numero ID do estado
-	 * @return mixed (array ou boolean)
-	 * @access public
-	 */
-	function getCitiesFromState($state_id)
-	{
-		if (!is_numeric($state_id))
-			return false;
-
-		$state_id = (int) $state_id;
-		if (isset($this->citiesFromState[$state_id]))
-			return $this->citiesFromState[$state_id];
-
-		$sql =
-		"SELECT
-			c.id_city AS id_city,
-			c.city_name AS city_name
-		FROM
-			phpgw_cc_state s,
-			phpgw_cc_city c
-		WHERE
-			c.id_state = s.id_state AND
-			s.id_country = 'BR' AND
-			c.id_state = ?
+			TO_ASCII(c.city_name) ILIKE TO_ASCII('" . $key . "%')
+			" . $where . "
 		ORDER BY
-			city_name";
-
-		$result = $this->db->query($sql, array($state_id));
-		$output = array();
-		while ($row = $result->fetchRow())
-			$output[] = $row;
-
-		$this->citiesFromState[$state_id] = $output;
-		return $output;
-	}
-    /**
-	 * Busca os estados brasileiros
-	 * @return mixed (array ou boolean)
-	 * @access public
-	 */
-	function getStates()
-	{
-		$sql =
-		"SELECT
-			id_state,
-			state_name
-		FROM
-			phpgw_cc_state
-		WHERE
-			id_country = 'BR'
-		ORDER BY
-			state_name";
+			city_name
+		LIMIT 10";
 
 		$result = $this->db->query($sql);
@@ -184,4 +215,29 @@
 		return $output;
 	}
+	/**
+	 * Busca os estados brasileiros
+	 * @return mixed (array ou boolean)
+	 * @access public
+	 */
+	function getStates()
+	{
+		$sql =
+		"SELECT
+			id_state,
+			state_name
+		FROM
+			phpgw_cc_state
+		WHERE
+			id_country = 'BR'
+		ORDER BY
+			state_name";
+
+		$result = $this->db->query($sql);
+		$output = array();
+		while ($row = $result->fetchRow())
+			$output[] = $row;
+
+		return $output;
+	}
 }
 ?>
Index: branches/2.2/workflow/inc/local/classes/class.JobBase.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.JobBase.php	(revision 1437)
+++ branches/2.2/workflow/inc/local/classes/class.JobBase.php	(revision 3167)
@@ -89,9 +89,9 @@
 	{
 		require_once 'common.inc.php';
-		$GLOBALS['workflow']['factory']->getInstance('WorkflowMacro')->prepareEnvironment();
+		Factory::getInstance('WorkflowMacro')->prepareEnvironment();
 		$this->jobID = $jobID;
 		$this->processID = $processID;
 		$this->currentDate = $currentDate;
-		$this->jobManager = &$GLOBALS['workflow']['factory']->getInstance('WorkflowJobManager');
+		$this->jobManager = Factory::getInstance('WorkflowJobManager');
 		$this->testMode = $testMode;
 		$this->maximumExecutionTime = $maximumExecutionTime;
@@ -148,10 +148,8 @@
 	final private function prepareEnvironment()
 	{
-		$GLOBALS['workflow']['factory']->getInstance('WorkflowMacro')->prepareProcessEnvironment($this->processID);
-
-		require_once PHPGW_SERVER_ROOT . '/workflow/inc/class.process_factory.inc.php';
+		Factory::getInstance('WorkflowMacro')->prepareProcessEnvironment($this->processID);
 
 		$this->environment = array();
-		$this->environment['factory']  = &new ProcessFactory();
+		$this->environment['factory']  = &Factory::newInstance('ProcessWrapperFactory');
 	}
 
@@ -202,5 +200,5 @@
 	final public function createNewInstance($startActivityId, $instanceName=false, $properties=false, $user=false)
 	{
-		$activityManager = CreateObject('workflow.workflow_activitymanager');
+		$activityManager = Factory::getInstance('workflow_activitymanager');
 		$activity = $activityManager->get_activity($startActivityId);
 
Index: branches/2.2/workflow/inc/local/classes/class.wf_orgchart.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_orgchart.php	(revision 1320)
+++ branches/2.2/workflow/inc/local/classes/class.wf_orgchart.php	(revision 3167)
@@ -24,5 +24,5 @@
 	function wf_orgchart()
 	{
-		$this->db = &$GLOBALS['workflow']['workflowObjects']->getDBWorkflow()->Link_ID;
+		$this->db = &Factory::getInstance('WorkflowObjects')->getDBWorkflow()->Link_ID;
 		$this->db->setFetchMode(ADODB_FETCH_ASSOC);
 	}
@@ -117,4 +117,5 @@
 	 * Este método irá buscar na tabela de áreas, todas as áreas que pertencem à organização solicitada.
 	 * @param int $organizationID O ID da organização.
+	 * @param int $onlyActiveAreas false= recupera todas as áreas; true= recupera somente as áreas ativas.
 	 * @return array Uma array seqüencial contendo as áreas de uma organização. Cada linha do array conterá:
 	 * - organizacao_id
@@ -131,12 +132,20 @@
 	 * @access public
 	 */
-	function getOrganizationAreas($organizationID)
-	{
-		$query = "SELECT organizacao_id, area_id, area_status_id, " .
-				 "       superior_area_id, centro_custo_id, titular_funcionario_id," .
-				 "       substituto_funcionario_id, sigla, descricao, ativa, auxiliar_funcionario_id" .
-				 "  FROM area" .
-				 " WHERE (organizacao_id = ?)" .
-				 " ORDER BY sigla, descricao";
+	function getOrganizationAreas($organizationID, $onlyActiveAreas = false)
+	{
+		$query = "SELECT a.organizacao_id, a.area_id, a.area_status_id, " .
+				 "       a.superior_area_id, a.centro_custo_id, a.titular_funcionario_id, " .
+				 "       a.sigla, a.descricao, a.ativa, a.auxiliar_funcionario_id, " .
+				 "		 s.funcionario_id as substituto_funcionario_id " .
+				 " FROM area a " .
+				 "  LEFT OUTER JOIN substituicao s " .
+				 "  ON ((a.area_id = s.area_id) AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) " .
+				 " WHERE " .
+				 "	(a.organizacao_id = ?) ";
+		// Se desejar somente retornar as áreas que estão ativas
+		if($onlyActiveAreas)
+			$query .=" AND a.ativa = 'S' ";
+
+		$query .= " ORDER BY a.sigla, a.descricao";
 
 		$result = $this->db->query($query, array($organizationID));
@@ -320,9 +329,15 @@
 	function getArea($areaID)
 	{
-		$query = "SELECT organizacao_id, area_id, area_status_id, " .
-				 "       superior_area_id, centro_custo_id, titular_funcionario_id," .
-				 "       substituto_funcionario_id, sigla, descricao, ativa, auxiliar_funcionario_id" .
-				 "  FROM area" .
-				 " WHERE (area_id = ?)";
+		$query = "SELECT a.organizacao_id, a.area_id, a.area_status_id, " .
+				 "       a.superior_area_id, a.centro_custo_id, a.titular_funcionario_id, " .
+				 "       a.sigla, a.descricao, a.ativa, a.auxiliar_funcionario_id, " .
+				 "		 s.funcionario_id as substituto_funcionario_id " .
+				 " FROM area a " .
+				 "  LEFT OUTER JOIN substituicao s " .
+				 "  ON ((a.area_id = s.area_id) AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) " .
+				 " WHERE " .
+				 "	(a.area_id = ?) " .
+				 " ORDER BY a.sigla, a.descricao";
+
 
 		$result = $this->db->query($query, array($areaID));
@@ -357,9 +372,17 @@
 	function getAreaByName($acronym, $organizationID = 1)
 	{
-		$query = "SELECT organizacao_id, area_id, area_status_id, " .
-				 "       superior_area_id, centro_custo_id, titular_funcionario_id," .
-				 "       substituto_funcionario_id, sigla, descricao, ativa, auxiliar_funcionario_id" .
-				 "  FROM area" .
-				 " WHERE (UPPER(sigla) = UPPER(?) and (organizacao_id = ?))";
+		$query = "SELECT a.organizacao_id, a.area_id, a.area_status_id, " .
+				 "       a.superior_area_id, a.centro_custo_id, a.titular_funcionario_id, " .
+				 "       a.sigla, a.descricao, a.ativa, a.auxiliar_funcionario_id, " .
+				 "		 s.funcionario_id as substituto_funcionario_id " .
+				 " FROM area a " .
+				 "  LEFT OUTER JOIN substituicao s " .
+				 "  ON ((a.area_id = s.area_id) AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) " .
+				 " WHERE " .
+				 "	(UPPER(a.sigla) = UPPER(?)) " .
+				 " AND " .
+				 "	(a.organizacao_id = ?) " .
+				 " ORDER BY a.sigla, a.descricao";
+
 
 		$result = $this->db->query($query, array($acronym, (int) $organizationID));
@@ -395,9 +418,16 @@
 		$result = array();
 
-		$query = "SELECT organizacao_id, area_id, area_status_id, " .
-				 "       superior_area_id, centro_custo_id, titular_funcionario_id," .
-				 "       substituto_funcionario_id, sigla, descricao, ativa, auxiliar_funcionario_id" .
-				 "  FROM area" .
-				 " WHERE (area_status_id = ?)";
+		$query = "SELECT a.organizacao_id, a.area_id, a.area_status_id, " .
+				 "       a.superior_area_id, a.centro_custo_id, a.titular_funcionario_id, " .
+				 "       a.sigla, a.descricao, a.ativa, a.auxiliar_funcionario_id, " .
+				 "		 s.funcionario_id as substituto_funcionario_id " .
+				 " FROM area a " .
+				 "  LEFT OUTER JOIN substituicao s " .
+				 "  ON ((a.area_id = s.area_id) AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) " .
+				 " WHERE " .
+				 "	(a.area_status_id = ?) " .
+				 " ORDER BY a.sigla, a.descricao";
+
+
 
 		$result = $this->db->query($query, array($areaStatusID));
@@ -436,10 +466,14 @@
 		$areas = implode(', ', $areaIDs);
 
-		$query = "SELECT organizacao_id, area_id, area_status_id, " .
-				 "       superior_area_id, centro_custo_id, titular_funcionario_id," .
-				 "       substituto_funcionario_id, sigla, descricao, ativa, auxiliar_funcionario_id" .
-				 "  FROM area" .
-				 " WHERE area_id IN ($areas)" .
-				 " ORDER BY sigla, descricao";
+		$query = "SELECT a.organizacao_id, a.area_id, a.area_status_id, " .
+				 "       a.superior_area_id, a.centro_custo_id, a.titular_funcionario_id, " .
+				 "       a.sigla, a.descricao, a.ativa, a.auxiliar_funcionario_id, " .
+				 "		 s.funcionario_id as substituto_funcionario_id " .
+				 " FROM area a " .
+				 "  LEFT OUTER JOIN substituicao s " .
+				 "  ON ((a.area_id = s.area_id) AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) " .
+				 " WHERE " .
+				 "	(a.area_id IN ($areas)) " .
+				 " ORDER BY a.sigla, a.descricao";
 
 		// A execução é realizada sem o segundo parâmetro pois este não pode estar entre aspas
@@ -448,4 +482,38 @@
 			return false;
 
+		$output = $result->GetArray(-1);
+		return $output;
+	}
+	
+	/**
+	 * Return all areas that the employee is a supervisor.
+	 * 
+	 * Search in the organization for all areas that the employee is a supervisor.
+	 * @param int $employeeID The ID of employee
+	 * @return array Array containing all the areas that the employeee is a supervisor.
+	 * @access public
+	 */
+	function getSupervisorAreas($employeeID) {
+
+		if (!$employeeID) {
+			return false;
+		}
+
+		$query = "SELECT 
+						a.area_id
+					FROM 
+						area a 
+						LEFT OUTER JOIN substituicao s ON ((a.area_id = s.area_id) 
+						AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) 
+					WHERE 
+						a.titular_funcionario_id = ? OR 
+						s.funcionario_id = ?
+					GROUP BY
+						a.area_id";
+		
+		$result = $this->db->query($query, array($employeeID,$employeeID));
+		if (!$result)
+			return false;
+		
 		$output = $result->GetArray(-1);
 		return $output;
@@ -506,14 +574,19 @@
 	function getSubAreasByParentAreaID($parentAreaID, $onlyActiveAreas = false)
 	{
-		$query = "SELECT organizacao_id, area_id, area_status_id, " .
-				 "       superior_area_id, centro_custo_id, titular_funcionario_id," .
-				 "       substituto_funcionario_id, sigla, descricao, ativa, auxiliar_funcionario_id" .
-				 "  FROM area" .
-				 " WHERE superior_area_id = ?";
+		$query = "SELECT a.organizacao_id, a.area_id, a.area_status_id, " .
+				 "       a.superior_area_id, a.centro_custo_id, a.titular_funcionario_id, " .
+				 "       a.sigla, a.descricao, a.ativa, a.auxiliar_funcionario_id, " .
+				 "		 s.funcionario_id as substituto_funcionario_id " .
+				 " FROM area a " .
+				 "  LEFT OUTER JOIN substituicao s " .
+				 "  ON ((a.area_id = s.area_id) AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) " .
+				 " WHERE " .
+				 "	(a.superior_area_id = ?) ";
+
 
 		if ($onlyActiveAreas){
 			$query .= " AND ativa = 'S'";
 		}
-		$query .= " ORDER BY sigla, descricao";
+		$query .= " ORDER BY a.sigla, a.descricao";
 
 		$result = $this->db->query($query, array($parentAreaID));
@@ -1168,5 +1241,11 @@
 			return false;
 
-		return $employee['centro_custo_id'];
+		$costCenterID = $employee['centro_custo_id'];
+		if(!empty($costCenterID)){
+			return $costCenterID;
+		} else {
+			$employeeArea = $this->getArea($employee['area_id']);
+			return $employeeArea['centro_custo_id'];
+		}
 	}
 
Index: branches/2.2/workflow/inc/local/classes/class.wf_ldap.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_ldap.php	(revision 1067)
+++ branches/2.2/workflow/inc/local/classes/class.wf_ldap.php	(revision 3167)
@@ -1,4 +1,3 @@
 <?php
-require_once PHPGW_SERVER_ROOT . SEP . 'workflow' . SEP . 'inc' . SEP . 'local' . SEP . 'classes' . SEP . 'class.wf_cached_ldap.php';
 
 /**
@@ -41,11 +40,11 @@
 	function wf_ldap()
 	{
-		$tmpLDAP = &$GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP');
+		$tmpLDAP = Factory::getInstance('WorkflowLDAP');
 		$this->user_context  = $tmpLDAP->getUserContext();
 		$this->group_context = $tmpLDAP->getGroupContext();
 
-		$this->ds = &$GLOBALS['workflow']['workflowObjects']->getLDAP();
+		$this->ds = &Factory::getInstance('WorkflowObjects')->getLDAP();
 
-		$this->cachedLDAP = new wf_cached_ldap();
+		$this->cachedLDAP = &Factory::getInstance('wf_cached_ldap');
 		$this->cachedLDAP->setOperationMode($this->cachedLDAP->OPERATION_MODE_LDAP);
 	}
Index: branches/2.2/workflow/inc/local/classes/class.wf_mail.php
===================================================================
--- branches/2.2/workflow/inc/local/classes/class.wf_mail.php	(revision 795)
+++ branches/2.2/workflow/inc/local/classes/class.wf_mail.php	(revision 3167)
@@ -39,5 +39,5 @@
 		$requiredConfiguration = array('mail_smtp_profile' => false);
 		$configuration = $GLOBALS['workflow']['wf_runtime']->process->getConfigValues($requiredConfiguration);
-		$bo_emailadmin = CreateObject('emailadmin.bo');
+		$bo_emailadmin = Factory::getInstance('bo');
 		$profileData = $bo_emailadmin->getProfile($configuration['mail_smtp_profile']);
 
