Index: sandbox/workflow/branches/1015/setup/setup.inc.php
===================================================================
--- sandbox/workflow/branches/1015/setup/setup.inc.php	(revision 2042)
+++ sandbox/workflow/branches/1015/setup/setup.inc.php	(revision 3061)
@@ -16,6 +16,6 @@
 	$setup_info['workflow']['app_order']	= 10;
 	$setup_info['workflow']['enable']		= 1;
-	$setup_info['workflow']['author']		= 'Ported from tikiwiki, modified by regis_glc alpeb & mbartz<br>Customized to ExpressoLivre by viani, rodrigolira, mariceli, drovetto, carloseduardo, rufino, asaikawa, gbisotto, julianadelgado & rodsouza<br>See changeLog for full names.';
-	$setup_info['workflow']['note']			= 'Workflow engine';
+	$setup_info['workflow']['author']		= 'See changeLog for complete list of developers.';
+	$setup_info['workflow']['note']			= 'Workflow Engine';
 	$setup_info['workflow']['license']		= 'GPL';
 	$setup_info['workflow']['description']		= 'Workflow Management';
@@ -59,9 +59,9 @@
 	$setup_info['workflow']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('1.0.0','1.0.1','1.2', '2.0', '2.1')
+		'versions' => Array('1.0.0','1.0.1','1.2', '2.0', '2.1', '2.2')
 	);
 	$setup_info['workflow']['depends'][] = array(
 		'appname' => 'preferences',
-		'versions' => Array('1.0.0', '0.9.13.002', '2.0', '2.1')
+		'versions' => Array('1.0.0', '0.9.13.002', '2.0', '2.1', '2.2')
 	);
 ?>
Index: sandbox/workflow/branches/1015/setup/default_records.inc.php
===================================================================
--- sandbox/workflow/branches/1015/setup/default_records.inc.php	(revision 2042)
+++ sandbox/workflow/branches/1015/setup/default_records.inc.php	(revision 3061)
@@ -59,5 +59,5 @@
 $GLOBALS['phpgw']->ADOdb->query("INSERT INTO phpgw_config (config_app, config_name, config_value) VALUES(?, ?, ?)", array('workflow', 'log_type_file', 'True'));
 $GLOBALS['phpgw']->ADOdb->query("INSERT INTO phpgw_config (config_app, config_name, config_value) VALUES(?, ?, ?)", array('workflow', 'log_type_firebug', 'True'));
-$GLOBALS['phpgw']->ADOdb->query("INSERT INTO phpgw_config (config_app, config_name, config_value) VALUES(?, ?, ?)", array('workflow', 'log_level', '7'));
+$GLOBALS['phpgw']->ADOdb->query("INSERT INTO phpgw_config (config_app, config_name, config_value) VALUES(?, ?, ?)", array('workflow', 'log_level', '0'));
 
 /* connect to the new database */
Index: sandbox/workflow/branches/1015/setup/tables_current.inc.php
===================================================================
--- sandbox/workflow/branches/1015/setup/tables_current.inc.php	(revision 1229)
+++ sandbox/workflow/branches/1015/setup/tables_current.inc.php	(revision 3061)
@@ -190,9 +190,8 @@
 				'fd' => array(
 					'wf_parent_instance_id'	=> array('type' => 'int', 'precision' => '4', 'nullable' => False),
-					'wf_parent_activity_id'	=> array('type' => 'int', 'precision' => '4', 'nullable' => False),
 					'wf_child_instance_id' 	=> array('type' => 'int', 'precision' => '4', 'nullable' => False),
 					'wf_parent_lock' 		=> array('type' => 'int', 'precision' => '2', 'nullable' => True)
 				),
-				'pk' => array('wf_parent_instance_id', 'wf_parent_activity_id', 'wf_child_instance_id'),
+				'pk' => array('wf_parent_instance_id', 'wf_child_instance_id'),
 				'fk' => array(),
 				'ix' => array(),
Index: sandbox/workflow/branches/1015/setup/tables_update.inc.php
===================================================================
--- sandbox/workflow/branches/1015/setup/tables_update.inc.php	(revision 2042)
+++ sandbox/workflow/branches/1015/setup/tables_update.inc.php	(revision 3061)
@@ -1216,4 +1216,18 @@
 	{
 		#updating the current version
+		$GLOBALS['setup_info']['workflow']['currentver'] = '2.0.003';
+		return $GLOBALS['setup_info']['workflow']['currentver'];
+	}
+	$test[] = '2.0.003';
+	function workflow_upgrade2_0_003()
+	{
+		#updating the current version
+		$GLOBALS['setup_info']['workflow']['currentver'] = '2.0.004';
+		return $GLOBALS['setup_info']['workflow']['currentver'];
+	}
+	$test[] = '2.0.004';
+	function workflow_upgrade2_0_004()
+	{
+		#updating the current version
 		$GLOBALS['setup_info']['workflow']['currentver'] = '2.1.000';
 		return $GLOBALS['setup_info']['workflow']['currentver'];
@@ -1224,4 +1238,8 @@
 		if (!$GLOBALS['phpgw_setup']->oProc->m_bDeltaOnly)
 		{
+			/* updating log level */
+			$values = array('0', 'workflow', 'log_level');
+			$GLOBALS['phpgw']->ADOdb->query('UPDATE phpgw_config SET config_value=? WHERE config_app=? AND config_name=?', $values);
+
 			$workflowHostInfo = extractDatabaseParameters();
 
@@ -1260,4 +1278,13 @@
 			/* reconnect to the previous database */
 			$GLOBALS['phpgw']->ADOdb->connect($workflowHostInfo['host'], $workflowHostInfo['user'], $workflowHostInfo['password'], $workflowHostInfo['dbname']);
+
+			/* removing primary key of egw_wf_interinstance_relations */
+			$GLOBALS['phpgw']->ADOdb->query('ALTER TABLE egw_wf_interinstance_relations DROP CONSTRAINT egw_wf_interinstance_relations_pkey');
+
+			/* removing wf_parent_activity_id column from egw_wf_interinstance_relations table */
+			$GLOBALS['phpgw']->ADOdb->query('ALTER TABLE egw_wf_interinstance_relations DROP COLUMN wf_parent_activity_id');
+
+			/* adding primary key without the column removed */
+			$GLOBALS['phpgw']->ADOdb->query('ALTER TABLE egw_wf_interinstance_relations ADD CONSTRAINT egw_wf_interinstance_relations_pkey PRIMARY KEY (wf_parent_instance_id, wf_child_instance_id)');
 		}
 
Index: sandbox/workflow/branches/1015/doc/change_log.txt
===================================================================
--- sandbox/workflow/branches/1015/doc/change_log.txt	(revision 1712)
+++ sandbox/workflow/branches/1015/doc/change_log.txt	(revision 3061)
@@ -15,9 +15,38 @@
 arifragoso is Ari Fragoso de Medeiros Junior
 hermespinheiro is Hermes Pinheiro Neto
-
-Os registros estão listados em ordem decrescente de data de realização.
+pedroerp is Pedro Eugênio Rocha Pedreira
+fabianok is Fabiano Sardenberg Kuss
+pereira.jair is Jair Gonçalves Pereira Junior
+adeildosantos is Adeildo Fernandes dos Santos
+
+[2.2.000]
+
+	#1143 - Refinição da função apache_request_headers, caso não exista no ambiente apache-php (viani)
+	#1139 - Modificação na função wf_upload_file para possibilitar a remoção de arquivos (fabianok)
+	#1131 - Modificação na exportação de processos para permitir templates com nomes aleatórios (viani)
+	#1120 - Moficado plugin wf_select_ldap_users para retornar atributos adicionais (adeildosantos)
+	#1119 - Implementado método getSupervisorAreas em class.wf_orgchart.php (pereira.jair)
+	#1089 - Melhoria em query sql na inserção de instancias. (fabianok)
+	#1082 - Removida coluna wf_parent_activity_id da tabela egw_wf_interinstance_relations (asaikawa)
+	#1080 - Modificada string (excluído) para (inativo) quando um registro de usuário no cache não existe mais no ldap. (viani)
+	#1069 - Inclusão de log de tempo de execução de atividades. (gbisotto/rufino)
+	#1004 - Melhorado o método getEmployeeCostCenterID para que retorne o id da área caso não exista o id do centro de custo do funcionário. (gbisotto)
+	#946 - Possibilitar que o plugin smarty wf_autocomplete_input atualize a lista de seleção a cada tecla pressionada. (asaikawa)
+	#944 - Alteração na função javascript get_form_fields para retornar em array os elementos identificados com '[]'. (asaikawa)
+	#943 - Criar na classe wf_location, uma consulta de cidades pelo início do nome. (asaikawa)
+	#942 - Ajustar a classe wf_location para considerar a nova coluna que identifica se o registro é distrito. (asaikawa)
+	#935 - Incluída opção para listar funcionários em ordem alfabética geral na impressão do organograma. (pedroerp)
+	#928 - Incluída busca por telefone no organograma. (pedroerp)
+	#916 - Criada nova variável wf_webserver_url no contexto de execução dos processos. (pedroerp)
+	#870 - Correção de bug no parâmetro print_mode da classe run_activity. (pedroerp)
+	#869 - Indentificação do titular e substituro de áreas do organograma. (pedroerp)
+	#868 - Correção da altura das janelas de edição do organograma. (pedroerp)
+	#609 - Reconstrução da classe factory (pedroerp/rufino)
+	#441 - Inclusão do período de substituição de chefia no organograma. (pedroerp)
 
 [2.1.000]
 
+	#989 - Compatibilização do workflow com os novos temas do Expresso. (rodsouza)
+	#951 - Correção de bug na verificação de sessão das chamadas ajax do workflow. (viani)
 	#794 - Correção de bug de sintaxe na classe Workflow_WfSecurity. (hermespinheiro).
 	#792 - Modificado o atribuito de usuário padrão de uma atividade para aceitar também um perfil padrão. (rufino)
@@ -27,14 +56,28 @@
 	#658 - Correção no alinhamento dos ícones de aplicações externas. Ao redimensionar a janela, o ícones são reorganizados. (gbisotto)
 	#657 - Correção no alinhamento do menu de atividades dos processos. Ao redimensionar a janela, os menus são reorganizados. (gbisotto).
+	#643 - Criação do método createNewInstance na classe JobBase, que possibilita iniciar uma instância do processo a partir de um job. (rufino)
 	#639 - Inclusão de cor em destaque ao passar o mouse sobre uma linha nas visualizações do organograma. (rodsouza)
 	#638 - Mudança na query de busca do organograma para pesquisar também por áreas. (rodsouza)
-	#643 - Criação do método createNewInstance na classe JobBase, que possibilita iniciar uma instância do processo a partir de um job. (rufino)
+	#637 - Inclusão de click-to-call no organograma e outras melhorias na interface. (rodsouza)
+	#603 - Remoção do design pattern observer da engine do workflow, por inutilidade. (gbisotto)
 	#442 - Criação do plugin wf_autocomplete_input, para listar com autocomplete o resultado de uma busca ajax. (rufino)
-	#637 - Inclusão de click-to-call no organograma e outras melhorias na interface. (rodsouza)
+
+[2.0.004]
+
+	#1045 - Corrigido bug de sessão nas chamadas ajax de processos. (viani)
+	#951 - Corrigido bug na verificação de sessão ativa nas chamadas ajax de processos. (viani)
+
+[2.0.003]
+	#899 - Inclusão de inserts faltantes no arquivo default_records, além de atualização de estrutura de tabelas do organograma. (pedroerp)
+
+[2.0.001]
+
+	#671 - Inclusão do arquivo header.session.inc.php para a verificação de segurança de sessão. (asaikawa)
 
 [2.0.000]
 
-	* Correção de bug no método getByUser da classe wf_instance. (hermespinheiro)
-	* Melhorias no organograma, com novas visualizações nas interfaces. (rodsouza)
+	#641 - Correção de bug no método getByUser da classe wf_instance. (hermespinheiro)
+	#589 - Melhorias no organograma, com novas visualizações nas interfaces. (rodsouza)
+	#439 - Redução do tempo de carga dos funcionários de uma área no organograma (rodsouza)
 
 [1.8.05.000]
Index: sandbox/workflow/branches/1015/lib/factory/WorkflowFactory.php
===================================================================
--- sandbox/workflow/branches/1015/lib/factory/WorkflowFactory.php	(revision 2588)
+++ sandbox/workflow/branches/1015/lib/factory/WorkflowFactory.php	(revision 3061)
@@ -63,4 +63,5 @@
 		$this->registerFileInfo('Thread', 'class.Thread.inc.php', 'inc');
 		$this->registerFileInfo('Paging', 'class.Paging.inc.php', 'inc');
+		$this->registerFileInfo('Logger', 'class.Logger.inc.php', 'inc');
 		$this->registerFileInfo('FsUtils', 'class.fsutils.inc.php', 'inc');
 		$this->registerFileInfo('UserPictureProvider', 'class.UserPictureProvider.inc.php', 'inc');
@@ -168,4 +169,15 @@
 
 
+		/**
+		 * TODO - This is another ATR - Alternative Technical Resource (common known
+		 * as workaround) to allow instantiation of "wf" classes. Although these classes
+		 * should have not been instanciated by the workflow module, some of them are
+		 * instantiated by run_activity during every execution. =(
+		 * In a new version of MVC these objects must be created by the Processes.
+		 */
+		$this->registerFileInfo('wf_natural', 'class.wf_natural.php', 'inc/local/classes');
+		$this->registerFileInfo('wf_db', 'class.wf_db.php', 'inc/local/classes');
+
+
 		/* ok. no more instances of this class.. */
 		self::$_instantiated = true;
Index: sandbox/workflow/branches/1015/inc/class.bo_utils.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.bo_utils.inc.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/class.bo_utils.inc.php	(revision 3061)
@@ -64,5 +64,5 @@
 	 */
 	function search_ldap_users_by_cn($params)
-	{
+	{ 
 		// parâmetro a ser procurado no ldap
 		$cn = trim(ereg_replace(' +', ' ', $params['cn']));
@@ -86,4 +86,6 @@
 			$ret_name = empty($params['name']) ? 'cn' : $params['name'];
 
+			$ret_complement = empty($params['complement']) ? '' : $params['complement'];
+
 			$ajaxConfig = &Factory::newInstance('ajax_config', 'contactcenter');
 			$config = $ajaxConfig->read_repository();
@@ -103,5 +105,9 @@
 
 				$filter     = '(&(uid=*)(phpgwAccountType=u)(!(phpgwAccountVisible=-1))(cn=*' . $cn . '*))';
-				$attrib_ret = array('cn', $ret_id, $ret_name);
+
+				if($ret_complement != '')
+					$attrib_ret = array('cn', $ret_id, $ret_name, $ret_complement);
+				else
+					$attrib_ret = array('cn', $ret_id, $ret_name);
 
 				$r = ldap_search($ds, $ldapconfig['basedn'], $filter, $attrib_ret, 0, 0, 5);
@@ -112,11 +118,30 @@
 					}
 					elseif(ldap_count_entries($ds, $r) < 200){
+
 						$result = ldap_get_entries($ds, $r);
-						foreach($result as $value){
-							$output['values'][] = array(
-								'id'   => $value[$ret_id],
-								'name' => trim(ucwords(strtolower($value[$ret_name][0]))));
+
+						foreach($result as $value){ 
+							if( ($value[$ret_name][0] != '') && ($value[$ret_complement][0] != '') ){
+									$complement = " >> " . $value[$ret_complement][0];
+									$output['values'][] = array(
+																 'id'   => $value[$ret_id],
+																 'name' => trim(ucwords(strtolower($value[$ret_name][0]))) . $complement
+															   ); 
+
+							}
+						elseif($value[$ret_name][0] != ''){
+								$output['values'][] = array(
+															 'id'   => $value[$ret_id],
+															 'name' => trim(ucwords(strtolower($value[$ret_name][0])))
+														   ); 
+							}
+						else{
+								$output['values'][] = array(
+															 'id'   => '',
+															 'name' => "-- Selecione uma Opção --"
+														   ); 
+							}
+
 						}
-
 
 						foreach ($output['values'] as $key => $value){
@@ -140,5 +165,5 @@
 		else{
 			$output['msg'] = 'Não digite caracteres especiais nem números. Apenas letras e espaços são permitidos.';
-		}
+		} 
 		return $output;
 	}
Index: sandbox/workflow/branches/1015/inc/class.run_activity.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.run_activity.inc.php	(revision 2588)
+++ sandbox/workflow/branches/1015/inc/class.run_activity.inc.php	(revision 3061)
@@ -24,5 +24,5 @@
      */
 	class run_activity extends WorkflowUtils
-	{  	
+	{
 		/**
 		 * @var array  $public_functions func
@@ -50,5 +50,5 @@
 		 * @access public
 		 */
-		var $process;	
+		var $process;
 		/**
 		 * @var object $GUI  GUI engine object. Act carefully with it.
@@ -62,13 +62,13 @@
 		var $message = Array();
 		/**
-		 * @var object $categories categorie object for categories 
+		 * @var object $categories categorie object for categories
 		 * @access public
 		 */
 		var $categories;
 		/**
-		 * @var array $conf 
-		 * @access public
-		 */
-		var $conf = array();	
+		 * @var array $conf
+		 * @access public
+		 */
+		var $conf = array();
 		/**
 		 * @var $wf_template local activity template
@@ -76,10 +76,10 @@
 		 */
 		var $wf_template;
-		/** 
+		/**
 		 * @var object $instance
 		 * @access public
 		 */
 		var $instance;
-		/** 
+		/**
 		 * @var object $activity_type The type of activity
 		 * @access public
@@ -88,61 +88,61 @@
 		// then we retain all usefull vars as members, to make them avaible in user's source code
 		// theses are data which can be set before the user code and which are not likely to change because of the user code
-		/** 
-		 * @var int $process_id The process id 
+		/**
+		 * @var int $process_id The process id
 		 * @access public
 		 */
 		var $process_id;
-		/** 
-		 * @var int $activity_id The activity id 
+		/**
+		 * @var int $activity_id The activity id
 		 * @access public
 		 */
 		var $activity_id;
-		/** 
+		/**
 		 * @var int $process_name The process name
 		 * @access public
 		 */
 		var $process_name;
-		/** 
-		 * @var int $process_version The process_version 
+		/**
+		 * @var int $process_version The process_version
 		 * @access public
 		 */
 		var $process_version;
-		/** 
-		 * @var int $activity_name The process id 
+		/**
+		 * @var int $activity_name The process id
 		 * @access public
 		 */
 		var $activity_name;
-		/** 
-		 * @var int $user_name The user name 
+		/**
+		 * @var int $user_name The user name
 		 * @access public
 		 */
 		var $user_name;
-		/** 
-		 * @var int $view_activity activity id of the view activity avaible for this process 
+		/**
+		 * @var int $view_activity activity id of the view activity avaible for this process
 		 * @access public
 		 */
 		var $view_activity;
-		// theses 4 vars aren't avaible for the user code, they're set only after this user code was executed		
-		/** 
-		 * @var int $instance_id Instance id 
+		// theses 4 vars aren't avaible for the user code, they're set only after this user code was executed
+		/**
+		 * @var int $instance_id Instance id
 		 * @access public
 		 */
 		var $instance_id=0;
-		/** 
-		 * @var string $instance_name Instance name 
+		/**
+		 * @var string $instance_name Instance name
 		 * @access public
 		 */
 		var $instance_name='';
-		/** 
-		 * @var int $instance_owner Instance owner id 
+		/**
+		 * @var int $instance_owner Instance owner id
 		 * @access public
 		 */
 		var $instance_owner=0;
-		/** 
-		 * @var string $owner_name Owner name 
+		/**
+		 * @var string $owner_name Owner name
 		 * @access public
 		 */
 		var $owner_name='';
-		
+
 		/**
 		 * @var bool $print_mode print mode
@@ -155,11 +155,11 @@
 		 */
 		var $enable_print_mode = false;
-		
+
 		/**
 		 * @var array $act_role_names of roles associated with the activity, usefull for lists of users associated with theses roles
-		 * @access public	
+		 * @access public
 		 */
 		var $act_role_names= Array();
-		
+
 		/**
 		 * @var array $agents Array of ui_agent objects
@@ -172,20 +172,20 @@
 		 * @access public
 		 */
-		var $smarty;                
+		var $smarty;
 		/**
 		 * @var array $wf holds a global environment vector
 		 * @access public
 		 */
-		var $wf;                    
+		var $wf;
 		/**
 		 * @var $download_mode activates download mode
 		 * @access public
 		 */
-		var $download_mode;        
+		var $download_mode;
 		/**
 		 * @var string $_template_name holds the template's file name
 		 * @access public
 		 */
-		var $_template_name = null; 
+		var $_template_name = null;
 		/**
 		 * @var bool Indicates wether the current instance is a child instance or not
@@ -193,4 +193,5 @@
          */
 		var $isChildInstance = false;
+
 		/**
 		 * @var object Stores a 'workflow_smarty' object
@@ -200,7 +201,13 @@
 
 		/**
+		 * @var object Log Object
+         * @access private
+         */
+		private $logger = null;
+
+		/**
 		 * Constructor
-		 * 
-		 * @access public 
+		 *
+		 * @access public
 		 */
 		function run_activity()
@@ -218,4 +225,7 @@
 
 			$this->workflowSmarty 	= &Factory::getInstance('workflow_smarty', false);
+
+			// never configure a log of type "firebug" here. This will make goAjax stop running well =(
+			$this->logger 			= &Factory::getInstance('Logger', array('file'));
 
 			// TODO: open a new connection to the database under a different username to allow privilege handling on tables
@@ -236,4 +246,6 @@
 		function go($activity_id=0, $iid=0, $auto=0)
 		{
+			$totalTime = microtime(true);
+
 			$result=Array();
 
@@ -431,8 +443,8 @@
 
 			/* BEGIN WORKFLOW MVC SETTINGS */
-			$env = array( );                                           //create settings vector
+			$env = array();                                            //create settings vector
 			$env['view']          =& $smarty;                          //view layer instance
 			$env['template_file'] =& $_template_name;                  //template file to be shown
-			$env['dao']           =& wf_create_object('wf_db');        //data access object instance
+			$env['dao']			  =& Factory::newInstance('wf_db');    //data access object instance
 			$env['workflow']      =& $GLOBALS['workflow'];             //workflow environment information
 			$env['instance']      =& $instance;                        //process manager instance
@@ -441,5 +453,5 @@
 			$env['request']       =& $security->process($_REQUEST);    //sanitizes input data from client
 			$env['factory']       =& Factory::getInstance('ProcessWrapperFactory');  //instantiation controller class
-			$env['natural']		  =& wf_create_object('wf_natural');   //data access object instance for mainframe
+			$env['natural']		  =& Factory::newInstance('wf_natural');   //data access object instance for mainframe
 			/* END WORKFLOW MVC SETTINGS */
 
@@ -485,6 +497,10 @@
 
 			/* include the files */
+			$processTime = microtime(true);
+
 			foreach ($_engineFiles as $_engineFile)
 				require $_engineFile;
+
+			$processTime = (microtime(true) - $processTime);
 
 			unset($GLOBALS['workflow_env']);
@@ -528,6 +544,17 @@
 			}
 
+			$totalTime = (microtime(true) - $totalTime);
+
+			$logTime = sprintf("GO [pid=%s,iid=%s,uid=%s,aid=%s] [eng=%ss,proc=%ss]",
+								$this->process_id,
+								$this->instance_id,
+								$GLOBALS['user'],
+								$this->activity_id,
+								number_format(($totalTime - $processTime),3),
+								number_format($processTime,3) );
+
+			$this->logger->debug($logTime);
+
 			// TODO: process instance comments
-
 			$instructions = $this->runtime->handle_postUserCode(_DEBUG);
 			switch($instructions['action'])
@@ -593,4 +620,6 @@
 		function goAjax($activity_id=0, $iid=0, $auto=0)
 		{
+			$totalTime = microtime(true);
+
 			$result=Array();
 
@@ -702,6 +731,6 @@
 
 			/* BEGIN WORKFLOW MVC SETTINGS */
-			$env = array( );                                           //create settings vector
-			$env['dao']           =& wf_create_object('wf_db');        //data access object instance
+			$env = array();                                            //create settings vector
+			$env['dao']			  =& Factory::newInstance('wf_db');    //data access object instance
 			$env['workflow']      =& $GLOBALS['workflow'];             //workflow environment information
 			$env['instance']      =& $instance;                        //process manager instance
@@ -710,5 +739,5 @@
 			$env['request']       =& $security->process($_REQUEST); //sanitizes input data from client
 			$env['factory']       =& Factory::newInstance('ProcessWrapperFactory');  //instantiation controller class
-			$env['natural']		  =& wf_create_object('wf_natural');   //data access object instance for mainframe
+			$env['natural']		  =& Factory::newInstance('wf_natural');   //data access object instance for mainframe
 			/* END WORKFLOW MVC SETTINGS */
 
@@ -727,5 +756,5 @@
 			 * the messages for the process factory instead of Workflow
 			 * factory. Note that this is the same comment as the previous
-			 * function... boooring.. =}
+			 * function... boooring..
 			 */
 			Security::enable();
@@ -734,5 +763,9 @@
 			$nc = &Factory::newInstance('NanoController');
 			$nc->setClassPath(GALAXIA_PROCESSES . SEP . $this->process->getNormalizedName(). SEP . 'code');
+
+			$processTime = microtime(true);
 			$nc->iterateOverVirtualRequests();
+			$processTime = microtime(true) - $processTime;
+
 			$nc->outputResultData();
 			unset($GLOBALS['workflow_env']);
@@ -740,4 +773,16 @@
 			if (!is_null($iid))
 				$instance->instance->sync();
+
+			$totalTime = microtime(true) - $totalTime;
+
+			$logTime = sprintf("GOAJAX [pid=%s,iid=%s,uid=%s,aid=%s] [eng=%ss,proc=%ss]",
+								$this->process_id,
+								$this->instance_id,
+								$GLOBALS['user'],
+								$this->activity_id,
+								number_format(($totalTime - $processTime),3),
+								number_format($processTime,3) );
+
+			$this->logger->debug($logTime);
 		}
 
Index: sandbox/workflow/branches/1015/inc/local/functions/function.wf_create_object.php
===================================================================
--- sandbox/workflow/branches/1015/inc/local/functions/function.wf_create_object.php	(revision 795)
+++ sandbox/workflow/branches/1015/inc/local/functions/function.wf_create_object.php	(revision 3061)
@@ -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: sandbox/workflow/branches/1015/inc/local/classes/class.wf_instance.php
===================================================================
--- sandbox/workflow/branches/1015/inc/local/classes/class.wf_instance.php	(revision 2588)
+++ sandbox/workflow/branches/1015/inc/local/classes/class.wf_instance.php	(revision 3061)
@@ -250,29 +250,35 @@
 
 	/**
-	* 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 ir, egw_wf_instances i ' .
+				 '  LEFT JOIN egw_wf_instance_activities ia ' .
+				 '  ON (ia.wf_instance_id = i.wf_instance_id) ' .
+				 ' WHERE ' .
+				 '  (ir.wf_child_instance_id = i.wf_instance_id) AND (ir.wf_parent_instance_id = ?) ';
+
+		$result = $this->db->query($query, array($instanceID));
 		$output = $result->GetArray(-1);
 
Index: sandbox/workflow/branches/1015/inc/local/classes/class.wf_engine.php
===================================================================
--- sandbox/workflow/branches/1015/inc/local/classes/class.wf_engine.php	(revision 2588)
+++ sandbox/workflow/branches/1015/inc/local/classes/class.wf_engine.php	(revision 3061)
@@ -86,8 +86,9 @@
 	* @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)
 	{
+		wf_warn_deprecated_method('wf_instance', 'continueInstance');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->continueInstance($activityID, $instanceID);
@@ -99,8 +100,9 @@
 	* @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)
 	{
+		wf_warn_deprecated_method('wf_instance', 'abort');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->abort($instanceID);
@@ -113,8 +115,9 @@
 	* @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)
 	{
+		wf_warn_deprecated_method('wf_instance', 'setName');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->setName($instanceID, $name);
@@ -127,8 +130,9 @@
 	* @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)
 	{
+		wf_warn_deprecated_method('wf_instance', 'setPriority');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->setPriority($instanceID, $priority);
@@ -141,8 +145,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 getIdleInstances($numberOfDays, $activities = null)
 	{
+		wf_warn_deprecated_method('wf_instance', 'getIdle');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->getIdle($numberOfDays, $activities);
@@ -154,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);
 	}
@@ -166,8 +172,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 getInstancesByName($name)
 	{
+		wf_warn_deprecated_method('wf_instance', 'getByName');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		$preOutput = $WFInstance->getByName($name);
@@ -187,10 +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)
 	{
-		$WFInstance = &Factory::getInstance('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)
@@ -206,8 +214,9 @@
 	* @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)
 	{
+		wf_warn_deprecated_method('wf_instance', 'getProperties');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->getProperties($instanceID);
@@ -219,8 +228,9 @@
 	* @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)
 	{
+		wf_warn_deprecated_method('wf_instance', 'getProperties');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->getProperties($instanceID);
@@ -333,8 +343,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 getUserInstances($users, $activities = null, $status = null)
 	{
+		wf_warn_deprecated_method('wf_instance', 'getByUser');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->getByUser($users, $activities, $status);
@@ -346,8 +357,9 @@
 	* @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)
 	{
+		wf_warn_deprecated_method('wf_instance', 'setProperty');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->setProperty($instanceID, $nameProperty, $value);
@@ -362,8 +374,9 @@
 	* @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)
 	{
+		wf_warn_deprecated_method('wf_instance', 'checkUserAccess');
 		$WFInstance = &Factory::getInstance('wf_instance');
 		return $WFInstance->checkUserAccess($userID, $instanceID, $activityID, $writeAccess);
Index: sandbox/workflow/branches/1015/inc/local/classes/class.wf_natural.php
===================================================================
--- sandbox/workflow/branches/1015/inc/local/classes/class.wf_natural.php	(revision 795)
+++ sandbox/workflow/branches/1015/inc/local/classes/class.wf_natural.php	(revision 3061)
@@ -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: sandbox/workflow/branches/1015/inc/local/classes/class.wf_orgchart.php
===================================================================
--- sandbox/workflow/branches/1015/inc/local/classes/class.wf_orgchart.php	(revision 2588)
+++ sandbox/workflow/branches/1015/inc/local/classes/class.wf_orgchart.php	(revision 3061)
@@ -480,4 +480,38 @@
 		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;
+	}
 
 	/**
Index: sandbox/workflow/branches/1015/inc/class.workflow_processmanager.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.workflow_processmanager.inc.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/class.workflow_processmanager.inc.php	(revision 3061)
@@ -226,14 +226,4 @@
 			  fclose($fp);
 			  $out.='      ]]></code>';
-			  if($res['wf_is_interactive']=='y') {
-				$out.='      <template><![CDATA[';
-				$fp=fopen(GALAXIA_PROCESSES.SEP."$wf_procname".SEP."code".SEP."templates".SEP."$name.tpl","r");
-				//while(!feof($fp)) {
-				//	$line=fread($fp,8192);
-					$out.=''; //all templatess will be exported in another section
-				//}
-				fclose($fp);
-				$out.='      ]]></template>';
-			  }
 			  $out.='    </activity>'."\n";    
 			}
Index: sandbox/workflow/branches/1015/inc/class.so_move_instances.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.so_move_instances.inc.php	(revision 2588)
+++ sandbox/workflow/branches/1015/inc/class.so_move_instances.inc.php	(revision 3061)
@@ -318,23 +318,4 @@
 		}
 
-		/* format the array elements for use in a SELECT SQL statement, e.g. [iid => 12, aid = 27] would produce (12, 27) */
-		$instanceActivityList = array_map(create_function('$e', 'return \'(\' . $e[\'iid\'] . \', \' . $e[\'aid\'] . \')\';'), $instanceActivityList);
-
-		/* update the interinstance relations of the modified rows of the instance_activities table */
-		$resultSet = $this->db->query("SELECT wf_parent_instance_id, wf_parent_activity_id FROM egw_wf_interinstance_relations WHERE ((wf_parent_instance_id, wf_parent_activity_id) IN (" . implode(', ', $instanceActivityList) . "))");
-		$rows = $resultSet->GetArray(-1);
-		if (is_array($rows))
-		{
-			foreach ($rows as $row)
-			{
-				/* update the activity ID */
-				if (!$this->db->query("UPDATE egw_wf_interinstance_relations SET wf_parent_activity_id = ? WHERE (wf_parent_instance_id = ?) AND (wf_parent_activity_id = ?)", array($activitiesConvert[$row['wf_parent_activity_id']], $row['wf_parent_instance_id'], $row['wf_parent_activity_id'])))
-				{
-					$this->db->FailTrans();
-					return array('error' => 'Erro atualizando a tabela de relacionamento inter-instância. Nenhuma modificação foi salva');
-				}
-			}
-		}
-
 		/* in case of success, commit the modifications */
 		$this->db->CompleteTrans();
Index: sandbox/workflow/branches/1015/inc/log/Log/observer.php
===================================================================
--- sandbox/workflow/branches/1015/inc/log/Log/observer.php	(revision 795)
+++ sandbox/workflow/branches/1015/inc/log/Log/observer.php	(revision 3061)
@@ -79,5 +79,5 @@
          */
         if (class_exists($class)) {
-            $object = &new $class($priority, $conf);
+            $object = new $class($priority, $conf);
             return $object;
         }
@@ -103,7 +103,7 @@
             /* Support both new-style and old-style construction. */
             if ($newstyle) {
-                $object = &new $class($priority, $conf);
+                $object = new $class($priority, $conf);
             } else {
-                $object = &new $class($priority);
+                $object = new $class($priority);
             }
             return $object;
Index: sandbox/workflow/branches/1015/inc/log/Log.php
===================================================================
--- sandbox/workflow/branches/1015/inc/log/Log.php	(revision 795)
+++ sandbox/workflow/branches/1015/inc/log/Log.php	(revision 3061)
@@ -167,5 +167,5 @@
         /* If the class exists, return a new instance of it. */
         if (Log::_classExists($class)) {
-            $obj = &new $class($name, $ident, $conf, $level);
+            $obj = new $class($name, $ident, $conf, $level);
             return $obj;
         }
Index: sandbox/workflow/branches/1015/inc/class.basemodel.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.basemodel.inc.php	(revision 795)
+++ sandbox/workflow/branches/1015/inc/class.basemodel.inc.php	(revision 3061)
@@ -167,9 +167,10 @@
     * @param string $obj Class name
     * @return mixed
-    * @deprecated
+    * @deprecated 2.2.00.000
     * @access public
     */
 	function &getInstance($obj)
-    {
+	{
+		wf_warn_deprecated_method('Factory', 'getInstance');
 		return(wf_create_object(strtolower($obj)));
 	}
Index: sandbox/workflow/branches/1015/inc/engine/src/ProcessMonitor/ProcessMonitor.php
===================================================================
--- sandbox/workflow/branches/1015/inc/engine/src/ProcessMonitor/ProcessMonitor.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/engine/src/ProcessMonitor/ProcessMonitor.php	(revision 3061)
@@ -59,7 +59,8 @@
 
   /**
-   * @deprecated
+   * @deprecated 2.2.00.000
    */
   function update_instance_status($iid,$status) {
+	wf_warn_deprecated_method();
     return;
     $query = "update `".GALAXIA_TABLE_PREFIX."instances` set `wf_status`=? where `wf_instance_id`=?";
@@ -69,7 +70,8 @@
   
   /**
-   * @deprecated
+   * @deprecated 2.2.00.000
    */
   function update_instance_activity_status($iid,$activityId,$status) {
+	wf_warn_deprecated_method();
     return;
     $query = "update `".GALAXIA_TABLE_PREFIX."instance_activities` set `wf_status`=? where `wf_instance_id`=? and `wf_activity_id`=?";
Index: sandbox/workflow/branches/1015/inc/engine/src/common/WfRuntime.php
===================================================================
--- sandbox/workflow/branches/1015/inc/engine/src/common/WfRuntime.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/engine/src/common/WfRuntime.php	(revision 3061)
@@ -6,69 +6,69 @@
  * as it handle concurrency and part of the core execution of the instance while avoiding
  * bad manipulation of the instance
- * 
+ *
  * @package Galaxia
- * @license http://www.gnu.org/copyleft/gpl.html GPL 
+ * @license http://www.gnu.org/copyleft/gpl.html GPL
  */
-class WfRuntime extends Base 
-{  
+class WfRuntime extends Base
+{
   /**
    * @var array processes config values cached for this object life duration, init is done at first use for the only process associated with this runtime object
    * @access public
    */
-  var $conf= Array();  
+  var $conf= Array();
   /**
    * @var object $activity
-   * @access public 
+   * @access public
    */
   var $activity = null;
   /**
    * @var object $instance
-   * @access public 
+   * @access public
    */
   var $instance = null;
   /**
    * @var int $instance_id
-   * @access public 
-   */
-  var $instance_id = 0;  
+   * @access public
+   */
+  var $instance_id = 0;
   /**
    * @var int $activity_id
-   * @access public 
+   * @access public
    */
   var $activity_id = 0;
   /**
    * @var object $process Retrieve process information
-   * @access public 
+   * @access public
    */
   var $process = null;
   /**
    * @var object $workitems  Reference to $instance->workitems
-   * @access public 
+   * @access public
    */
   var $workitems = null;
   /**
    * @var object $activities Reference to $instance->activities
-   * @access public 
-   */  
+   * @access public
+   */
   var $activities = null;
   /**
    * @var object $security Security object
-   * @access public 
-   */  
+   * @access public
+   */
   var $security = null;
   /**
    * @var bool $transaction_in_progress Transaction state
-   * @access public 
-   */  
-  var $transaction_in_progress = false; 
+   * @access public
+   */
+  var $transaction_in_progress = false;
   /**
    * @var bool $debug Debug state
-   * @access public 
-   */   
+   * @access public
+   */
   var $debug=false;
   /**
    * @var bool $auto_mode Automatic mode state, non-interactive for instance, big impact on error handling
-   * @access public 
-   */  
+   * @access public
+   */
   var $auto_mode=false;
 
@@ -81,10 +81,10 @@
   /**
    * Constructor
-   * 
+   *
    * @param object &$db ADOdb
    * @return object WfRuntime instance
    * @access public
    */
-  function WfRuntime() 
+  function WfRuntime()
   {
     $this->child_name = 'WfRuntime';
@@ -101,8 +101,8 @@
    * Collect errors from all linked objects which could have been used by this object
    * Each child class should instantiate this function with her linked objetcs, calling get_error(true)
-   * 
+   *
    * @param bool $debug false by default, if true debug messages can be added to 'normal' messages
    * @param string $prefix appended to the debug message
-   * @return void 
+   * @return void
    * @access private
    */
@@ -118,5 +118,5 @@
   /**
    * Ends-up dying and giving a last message
-   * 
+   *
    * @param string $last_message last sentence
    * @param bool $include_errors false by default, if true we'll include error messages
@@ -134,5 +134,5 @@
     if ($this->debug) $debug = true;
     if ($this->auto_mode) $dying = false;
-    
+
     if ($include_errors)
     {
@@ -161,7 +161,7 @@
    * Loads the config values for the process associated with the runtime
    * config values are cached while this WfRuntime object stays alive
-   * 
+   *
    * @param array $arrayconf Config array with default value, where key is config option name and value is default value
-   * @access private 
+   * @access private
    * @return array Values associated with the current process for the asked config options and as well for som WfRuntime internal config options
    */
@@ -172,5 +172,5 @@
       $this->loadProcess();
     }
-    $arrayconf['auto-release_on_leaving_activity'] = 1;  
+    $arrayconf['auto-release_on_leaving_activity'] = 1;
     $this->conf =  $this->process->getConfigValues($arrayconf);
     return $this->conf;
@@ -179,8 +179,8 @@
   /**
    * Loads instance, the activity and the process, needed by the runtime engine to 'execute' the activity
-   * 
+   *
    * @param int $activityId activity id, the activity we will run
    * @param int $instanceId instance Id, can be empty for a start or standalone activity
-   * @return bool 
+   * @return bool
    * @access public
    */
@@ -204,9 +204,9 @@
       return false;
     }
-    
+
     //ensure the activity is not completed
     $this->instance->setActivityCompleted(false);
 	$this->instance->activityID = $activityId;
-    
+
     //set the workitems and activities links
     $this->workitems =& $this->instance->workitems;
@@ -214,8 +214,8 @@
     return true;
   }
-  
+
   /**
    * Retrieves the process object associated with the activity
-   * 
+   *
    * @param int $pId Process id of the process you want, if you do not give it we will try to take it from the activity
    * @return mixed Process object of the right type or false
@@ -242,8 +242,8 @@
     return true;
   }
-  
+
   /**
    * Gets current process instance
-   * 
+   *
    * @return object Process instance
    * @access public
@@ -256,5 +256,5 @@
   /**
    * Retrieves the activity of the right type from a baseActivity Object
-   * 
+   *
    * @param int $activity_id activity_id you want
    * @param bool $with_roles will load the roles links on the object
@@ -285,19 +285,19 @@
     return true;
   }
-  
+
   /**
    * Gets current activity instance
-   * 
+   *
    * @return object Activity instance
    * @access public
-   */  
+   */
   function &getActivity()
   {
     return $this->activity;
   }
-  
+
   /**
    * Gets the instance which could be an empty object
-   * 
+   *
    * @param int $instanceId is the instance id
    * @return mixed Instance object which can be empty or string if something was turning bad
@@ -308,5 +308,5 @@
     $this->instance_id = $instanceId;
     $this->instance->getInstance($instanceId);
-    if ( ($this->instance->getInstanceId()==0) 
+    if ( ($this->instance->getInstanceId()==0)
       && (! (($this->activity->getType()=='standalone') || ($this->activity->getType()=='start') )) )
     {
@@ -319,10 +319,10 @@
     return true;
   }
-  
+
   /**
    * Perform necessary security checks at runtime before running an activity
    * This will as well lock the tables via the security object
    * It should be launched in a transaction
-   * 
+   *
    * @return bool true if ok, false if the user has no runtime access
    * @access public
@@ -356,5 +356,5 @@
    * This will as well lock the tables via the security object
    * It should be launched in a transaction
-   * 
+   *
    * @return bool true if ok, false if the user has no runtime access instance and activity are unsetted in case of false check
    * @access public
@@ -372,9 +372,9 @@
         //we are granted an access to release but there is a special bad case where
         //we are a user authorized at releasing instances owned by others and where
-        //this instance is owned by another (for some quite complex reasons). 
+        //this instance is owned by another (for some quite complex reasons).
         //we should not release this new user!!
-        //Then this is auto-release, not a conscious act and so we will release only 
+        //Then this is auto-release, not a conscious act and so we will release only
         //if we can still grab this instance (avoiding the bad case)
-        
+
         //test grab before release
         if ($this->checkUserRun())
@@ -386,11 +386,11 @@
     return false;
   }
-  
+
   /**
    * Sets/unsets the WfRuntime in debug mode
-   * 
+   *
    * @param bool $debug_mode true by default, set it to false to disable debug mode
    * @access public
-   * @return void 
+   * @return void
    */
   function setDebug($debug_mode=true)
@@ -398,13 +398,13 @@
     $this->debug = $debug_mode;
   }
-  
+
   /**
    * Sets/unsets the WfRuntime in automatic mode. i.e : executing
    * non-interactive or interactive activities. Automatic mode have big impacts
    * on error handling and on the way activities are executed
-   * 
+   *
    * @param bool $auto_mode true by default, set it to false to disable automatic mode
    * @access public
-   * @return void 
+   * @return void
    */
   function setAuto($auto_mode=true)
@@ -412,10 +412,10 @@
     $this->auto_mode = $auto_mode;
   }
-  
+
   /**
    * This function will start a transaction, call it before setActivityUser()
-   * 
-   * @access public
-   * @return void 
+   *
+   * @access public
+   * @return void
    */
   function StartRun()
@@ -424,8 +424,8 @@
     $this->db->StartTrans();
   }
-  
+
   /**
    * This function ends the transactions started in StartRun()
-   * 
+   *
    * @access public
    * @return void
@@ -433,5 +433,5 @@
   function EndStartRun()
   {
-    if ($this->transaction_in_progress) 
+    if ($this->transaction_in_progress)
     {
       $this->db->CompleteTrans();
@@ -439,19 +439,19 @@
     }
   }
-  
-  /**
-   * For interactive activities this function will set the current user on the instance-activities table. 
+
+  /**
+   * For interactive activities this function will set the current user on the instance-activities table.
    * This will prevent having several user using the same activity on the same intsance at the same time
    * But if you want this function to behave well you should call it after a checkUserRun or a checkUserRelease
    * and inside a transaction. Theses others function will ensure the table will be locked and the user
    * is really granted the action
-   * 
+   *
    * @param bool $grab true by default, if false the user will be set to '*', releasing the instance-activity record
    * @access public
-   * @return bool 
+   * @return bool
    */
   function setActivityUser($grab=true)
   {
-    if(isset($GLOBALS['user']) && !empty($this->instance->instanceId) && !empty($this->activity_id)) 
+    if(isset($GLOBALS['user']) && !empty($this->instance->instanceId) && !empty($this->activity_id))
     {
       if ($this->activity->isInteractive())
@@ -480,10 +480,10 @@
       $this->error[] = $errors;
       return false;
-    }    
-  }
-  
+    }
+  }
+
   /**
    * Tries to give some usefull info about the current runtime
-   * 
+   *
    * @return array associative arrays with keys/values which could be usefull
    * @access public
@@ -510,5 +510,5 @@
    * This part of the runtime will be runned just after the activity code inclusion.
    * We are in fact after all the "user code" part. We should decide what to do next
-   * 
+   *
    * @param bool $debug false by default
    * @return array an array which must be analysed by the application run class. It contains 2 keys
@@ -525,8 +525,8 @@
   {
     $result = Array();
-    
+
      // re-retrieve instance id which could have been modified by a complete
      $this->instance_id	= $this->instance->getInstanceId();
-     
+
      //synchronised instance object with the database
      $this->instance->sync();
@@ -537,5 +537,5 @@
       if ($this->instance->getActivityCompleted())
       {
-        // activity is interactive and completed, 
+        // activity is interactive and completed,
         // we have to continue the workflow
         // and send any autorouted activity which could be after this one
@@ -554,5 +554,5 @@
         if ($GLOBALS['workflow']['__leave_activity'])
         {
-          // activity is interactive and the activity source set the 
+          // activity is interactive and the activity source set the
           // $GLOBALS[workflow][__leave_activity] it's a 'cancel' mode.
           // we redirect the user to the leave activity page
@@ -561,5 +561,5 @@
         }
         else
-        { 
+        {
           //the activity is not completed and the user doesn't want to leave
           // we loop on the form
@@ -570,5 +570,5 @@
     }
     else
-    { 
+    {
       // in auto mode or with non interactive activities we return engine info
       // and we collect our errors, we do not let them for other objects
@@ -583,7 +583,7 @@
   /**
    * Gets the the 'Activity Completed' status
-   * 
-   * @access public
-   * @return string 
+   *
+   * @access public
+   * @return string
    */
   function getActivityCompleted()
@@ -592,19 +592,19 @@
   }
 
-  
+
   //----------- Instance public function mapping -------------------------------------------
-  
+
   /**
    * Sets the next activity to be executed, if the current activity is
    * a switch activity the complete() method will use the activity setted
-   * in this method as the next activity for the instance. 
+   * in this method as the next activity for the instance.
    * Note that this method receives an activity name as argument (Not an Id)
    * and that it does not need the activityId like the instance method
-   * 
+   *
    * @param string $actname name of the next activity
    * @return bool
    * @access public
    */
-  function setNextActivity($actname) 
+  function setNextActivity($actname)
   {
     return $this->instance->setNextActivity($this->activity_id,$actname);
@@ -612,11 +612,11 @@
 
   /**
-   * Sets the user that must perform the next 
+   * Sets the user that must perform the next
    * activity of the process. this effectively "assigns" the instance to
    * some user
-   * 
+   *
    * @param int $user the next user id
    * @param string $activityName The name of the activity that the user will be able to executed. '*' means the next activity.
-   * @return bool 
+   * @return bool
    * @access public
    */
@@ -631,8 +631,8 @@
 
   /**
-   * Sets the user role that must perform the next 
+   * Sets the user role that must perform the next
    * activity of the process. this effectively "assigns" the instance to
    * some user
-   * 
+   *
    * @param string $roleName the next activity role
    * @param string $activityName The name of the activity that the role will be able to executed. '*' means the next activity.
@@ -655,24 +655,24 @@
 
   /**
-   * Gets the user that must perform the next activity of the process. 
+   * Gets the user that must perform the next activity of the process.
    * This can be empty if no setNextUser() was done before.
    * It wont return the default user but only the user which was assigned by a setNextUser
-   * 
-   * @return int 
-   * @access public
-   */
-  function getNextUser() 
+   *
+   * @return int
+   * @access public
+   */
+  function getNextUser()
   {
     return $this->instance->getNextUser();
   }
- 
+
   /**
    * Sets the name of this instance.
-   * 
+   *
    * @param string $value new name of the instance
-   * @return bool 
-   * @access public
-   */
-  function setName($value) 
+   * @return bool
+   * @access public
+   */
+  function setName($value)
   {
     return $this->instance->setName($value);
@@ -681,6 +681,6 @@
   /**
    * Gets the name of this instance
-   * 
-   * @return string 
+   *
+   * @return string
    * @access public
    */
@@ -691,10 +691,10 @@
   /**
    * Sets the category of this instance
-   * 
+   *
    * @param string $value
    * @return bool
    * @access public
    */
-  function setCategory($value) 
+  function setCategory($value)
   {
     return $this->instance->setcategory($value);
@@ -703,13 +703,13 @@
   /**
    * Gets category of this instance
-   * 
-   * @return string 
-   * @access public
-   */
-  function getCategory() 
+   *
+   * @return string
+   * @access public
+   */
+  function getCategory()
   {
     return $this->instance->getCategory();
   }
-  
+
   /**
    * Sets a property in this instance. This method is used in activities to
@@ -718,15 +718,15 @@
    * problems (A->z, digits and _ for spaces). If you have several set to call look
    * at the setProperties function. Each call to this function has an impact on database
-   * 
+   *
    * @param string $name property name (it will be normalized)
    * @param mixed $value value for this property
-   * @return bool 
-   * @access public
-   */
-  function set($name,$value) 
+   * @return bool
+   * @access public
+   */
+  function set($name,$value)
   {
     return $this->instance->set($name,$value);
   }
-  
+
   /**
    * Unsets a property in this instance. This method is used in activities to
@@ -734,10 +734,10 @@
    * All property names are normalized for security reasons and to avoid localisation
    * problems (A->z, digits and _ for spaces). Each call to this function has an impact on database
-   * 
+   *
    * @param string $name property name (it will be normalized)
    * @return bool true if it was ok
    * @access public
    */
-  function clear($name) 
+  function clear($name)
   {
     return $this->instance->clear($name);
@@ -749,5 +749,5 @@
    * All property names are normalized for security reasons and to avoid localisation
    * problems (A->z, digits and _ for spaces)
-   * 
+   *
    * @param string $name property name (it will be normalized)
    * @return bool true if it exists and false otherwise
@@ -766,5 +766,5 @@
    * problems (A->z, digits and _ for spaces). If you have several set to call look
    * at the setProperties function. Each call to this function has an impact on database
-   * 
+   *
    * @param array $properties_array associative array containing for each record the
    * property name as the key and the property value as the value. You do not need the complete
@@ -780,5 +780,5 @@
   /**
    * Gets the value of an instance property
-   * 
+   *
    * @param string $name name of the instance
    * @param string $defaultValue
@@ -793,53 +793,53 @@
   /**
    * Describes the activities where the instance is present, can be more than one activity if the instance was "splitted"
-   * 
+   *
    * @access public
    * @return array Vector of assocs
    */
-  function getActivities() 
+  function getActivities()
   {
     return $this->instance->getActivities();
   }
-  
+
   /**
    * Gets the instance status can be 'completed', 'active', 'aborted' or 'exception'
-   * 
+   *
    * @access public
    * @return string Instance status
    */
-  function getStatus() 
+  function getStatus()
   {
     return $this->instance->getStatus();
   }
-  
+
   /**
    * Sets the instance status
-   * 
+   *
    * @param $status Desired status, it can be: 'completed', 'active', 'aborted' or 'exception'
    * @return bool
    * @access public
    */
-  function setStatus($status) 
+  function setStatus($status)
   {
     return $this->instance->setStatus($status);
   }
-  
+
   /**
    * Gets the instance priority
-   * 
-   * @access public
-   * @return int 
+   *
+   * @access public
+   * @return int
    */
   function getPriority()
   {
     return $this->instance->getPriority();
-  } 
+  }
 
   /**
    * Sets the instance priority
-   * 
+   *
    * @param int $priority
    * @access public
-   * @return bool 
+   * @return bool
    */
   function setPriority($priority)
@@ -847,134 +847,134 @@
     return $this->instance->setPriority($priority);
   }
-   
+
   /**
    * Returns the instance id
-   * 
-   * @return int 
-   * @access public
-   */
-  function getInstanceId() 
+   *
+   * @return int
+   * @access public
+   */
+  function getInstanceId()
   {
     return $this->instance->getInstanceId();
   }
-  
+
   /**
    * Returns the process id for this instance
-   * 
-   * @return int 
-   * @access public 
+   *
+   * @return int
+   * @access public
    */
   function getProcessId() {
     return $this->instance->getProcessId();
   }
-  
+
   /**
    * Returns the owner of the instance
-   * 
-   * @return string 
-   * @access public
-   */
-  function getOwner() 
+   *
+   * @return string
+   * @access public
+   */
+  function getOwner()
   {
     return $this->instance->getOwner();
   }
-  
+
   /**
    * Sets the instance owner
-   * 
-   * @param string $user 
-   * @access public
-   * @return bool  
-   */
-  function setOwner($user) 
+   *
+   * @param string $user
+   * @access public
+   * @return bool
+   */
+  function setOwner($user)
   {
     return $this->instance->setOwner($user);
   }
-  
+
   /**
    * Returns the user that must execute or is already executing an activity where the instance is present
-   * 
+   *
    * @param int $activityId
    * @return bool False if the activity was not found for the instance, else return the user id or '*' if no user is defined yet
    * @access public
-   */  
-  function getActivityUser($activityId) 
+   */
+  function getActivityUser($activityId)
   {
     return $this->instance->getActivityUser($activityId);
   }
-  
+
   /**
    * Sets the status of the instance in some activity
-   * 
+   *
    * @param int $activityId Activity id
    * @param string $status New status, it can be 'running' or 'completed'
    * @return bool False if no activity was found for the instance
    * @access public
-   */  
-  function setActivityStatus($activityId,$status) 
+   */
+  function setActivityStatus($activityId,$status)
   {
     return $this->instance->setActivityStatus($activityId,$status);
   }
-  
-  
-  /**
-   * Gets the status of the instance in some activity 
-   * 
-   * @param int $activityId 
+
+
+  /**
+   * Gets the status of the instance in some activity
+   *
+   * @param int $activityId
    * @return string 'running' or 'completed'
    * @access public
    */
-  function getActivityStatus($activityId) 
+  function getActivityStatus($activityId)
   {
     return $this->instance->getActivityStatus($activityId);
   }
-  
+
   /**
    * Resets the start time of the activity indicated to the current time
-   * 
+   *
    * @param int $activityId
-   * @return bool 
-   * @access public
-   */
-  function setActivityStarted($activityId) 
+   * @return bool
+   * @access public
+   */
+  function setActivityStarted($activityId)
   {
     return $this->instance->setActivityStarted($activityId);
   }
-  
+
   /**
    * Gets the Unix timstamp of the starting time for the given activity
-   * 
+   *
    * @param int $activityId
-   * @return int 
-   * @access public
-   */
-  function getActivityStarted($activityId) 
+   * @return int
+   * @access public
+   */
+  function getActivityStarted($activityId)
   {
     return $this->instance->getActivityStarted($activityId);
   }
-  
+
   /**
    * Gets the time where the instance was started
-   * 
-   * @return int 
-   * @access public
-   */
-  function getStarted() 
+   *
+   * @return int
+   * @access public
+   */
+  function getStarted()
   {
     return $this->instance->getStarted();
   }
-  
+
   /**
    * Gets the end time of the instance (when the process was completed)
-   * 
-   * @return int 
-   * @access public 
-   */
-  function getEnded() 
+   *
+   * @return int
+   * @access public
+   */
+  function getEnded()
   {
     return $this->instance->getEnded();
   }
-  
-  
+
+
   /**
    * Completes an activity.
@@ -982,10 +982,10 @@
    * the engine does automatically complete automatic activities after
    * executing them
-   * 
+   *
    * @return bool True or false, if false it means the complete was not done for some internal reason
    * consult get_error() for more informations
    * @access public
    */
-  function complete() 
+  function complete()
   {
     if (!($this->activity->isInteractive()))
@@ -994,5 +994,5 @@
       return false;
     }
-    
+
     return $this->instance->complete($this->activity_id);
   }
@@ -1001,61 +1001,61 @@
    * Aborts an activity and terminates the whole instance. We still create a workitem to keep track
    * of where in the process the instance was aborted
-   * 
-   * @return bool 
-   * @access public
-   */
-  function abort() 
+   *
+   * @return bool
+   * @access public
+   */
+  function abort()
   {
     return $this->instance->abort();
   }
-  
+
   /**
    * Gets a comment for this instance
-   * 
+   *
    * @param int $cId Comment id
-   * @return string 
-   * @access public
-   */
-  function get_instance_comment($cId) 
+   * @return string
+   * @access public
+   */
+  function get_instance_comment($cId)
   {
     return $this->instance->get_instance_comment($cId);
   }
-  
+
   /**
    * Inserts or updates an instance comment
-   * 
+   *
    * @param int $cId Commend id
-   * @param int $activityId 
-   * @param object $activity 
+   * @param int $activityId
+   * @param object $activity
    * @param int	$user User id
    * @param string $title Comment's title
    * @param string $comment Comment's contents
-   * @return bool 
-   * @access public
-   */
-  function replace_instance_comment($cId, $activityId, $activity, $user, $title, $comment) 
+   * @return bool
+   * @access public
+   */
+  function replace_instance_comment($cId, $activityId, $activity, $user, $title, $comment)
   {
     return $this->instance->replace_instance_comment($cId, $activityId, $activity, $user, $title, $comment);
   }
-  
+
   /**
    * Removes an instance comment
-   * 
+   *
    * @param int $cId Comment id
-   * @return bool 
-   * @access public
-   */
-  function remove_instance_comment($cId) 
+   * @return bool
+   * @access public
+   */
+  function remove_instance_comment($cId)
   {
     return $this->instance->remove_instance_comment($cId);
   }
- 
+
   /**
    * Lists instance comments
-   * 
-   * @return array 
-   * @access public
-   */
-  function get_instance_comments() 
+   *
+   * @return array
+   * @access public
+   */
+  function get_instance_comments()
   {
     return $this->instance->get_instance_comments();
@@ -1087,7 +1087,6 @@
     $workflow = $GLOBALS['workflow'];
     unset($_REQUEST['iid']);
-    $run_activity = Factory::getInstance('run_activity');
+    $run_activity = Factory::newInstance('run_activity');
     $run_activity->runtime->instance->parentInstanceId = $this->instance_id;
-    $run_activity->runtime->instance->parentActivityId = $this->activity_id;
     $output = $run_activity->goChildInstance($activityID, $properties, $user, $parentLock);
     $_REQUEST['iid'] = $iid;
@@ -1128,7 +1127,7 @@
   function getParent()
   {
-    $resultSet = $this->query("SELECT wf_parent_instance_id, wf_parent_activity_id, wf_parent_lock FROM egw_wf_interinstance_relations WHERE (wf_child_instance_id = ?)", array($this->getInstanceId()));
+    $resultSet = $this->query("SELECT wf_parent_instance_id, wf_parent_lock FROM egw_wf_interinstance_relations WHERE (wf_child_instance_id = ?)", array($this->getInstanceId()));
     if (($row = $resultSet->fetchRow()))
-      return array('instance_id' => $row['wf_parent_instance_id'], 'activity_id' => $row['wf_parent_activity_id'], 'lock' => ($row['wf_parent_lock'] == 1));
+      return array('instance_id' => $row['wf_parent_instance_id'], 'lock' => ($row['wf_parent_lock'] == 1));
     else
       return false;
Index: sandbox/workflow/branches/1015/inc/engine/src/API/Instance.php
===================================================================
--- sandbox/workflow/branches/1015/inc/engine/src/API/Instance.php	(revision 2588)
+++ sandbox/workflow/branches/1015/inc/engine/src/API/Instance.php	(revision 3061)
@@ -84,9 +84,4 @@
    */
   var $parentLock = false;
-  /**
-   * @var int $parentActivityId The activity ID of the parent instance
-   * @access public
-   */
-  var $parentActivityId;
   /**
    * @var int $parentInstanceId The instance ID of the parent instance
@@ -490,5 +485,5 @@
     return '';
   }
- 
+
   /**
    * Creates a new instance.
@@ -503,5 +498,5 @@
   function _createNewInstance($activityId,$user) {
     // Creates a new instance setting up started, ended, user, status and owner
-    $pid = $this->getOne('select wf_p_id from '.GALAXIA_TABLE_PREFIX.'activities where wf_activity_id=?',array((int)$activityId));
+    $pid = $this->getOne('SELECT wf_p_id FROM '.GALAXIA_TABLE_PREFIX.'activities WHERE wf_activity_id=?',array((int)$activityId));
     $this->pId = $pid;
     $this->setStatus('active');
@@ -510,29 +505,37 @@
     $this->setStarted($now);
     $this->setOwner($user);
-    
-    $query = 'insert into '.GALAXIA_TABLE_PREFIX.'instances
-      (wf_started,wf_ended,wf_status,wf_p_id,wf_owner,wf_properties) 
-      values(?,?,?,?,?,?)';
-    $this->query($query,array($now,0,'active',$pid,$user,$this->security_cleanup(Array(),false)));
-    $this->instanceId = $this->getOne('select max(wf_instance_id) from '.GALAXIA_TABLE_PREFIX.'instances 
-                      where wf_started=? and wf_owner=?',array((int)$now,$user));
+
+    //Get the id of new instance, before insert values in table and use this value from main table and relationship tables.
+    $this->instanceId = $this->getOne("SELECT nextval('seq_egw_wf_instances')");
     $iid=$this->instanceId;
-    
+
+    $query = 'INSERT INTO '.GALAXIA_TABLE_PREFIX.'instances
+                (wf_instance_id, wf_started,wf_ended,wf_status,wf_p_id,wf_owner,wf_properties)
+              VALUES
+                (?,?,?,?,?,?,?)';
+
+    $this->query($query,array((int)$iid, $now,0,'active',$pid,$user,$this->security_cleanup(Array(),false)));
+
     // Then add in ".GALAXIA_TABLE_PREFIX."instance_activities an entry for the
     // activity the user and status running and started now
-    $query = 'insert into '.GALAXIA_TABLE_PREFIX.'instance_activities (wf_instance_id,wf_activity_id,wf_user,
-            wf_started,wf_status) values(?,?,?,?,?)';
+    $query = 'INSERT INTO '.GALAXIA_TABLE_PREFIX.'instance_activities
+                (wf_instance_id,wf_activity_id,wf_user,wf_started,wf_status)
+              VALUES
+                (?,?,?,?,?)';
     $this->query($query,array((int)$iid,(int)$activityId,$user,(int)$now,'running'));
 
     if (($this->isChildInstance) && (!is_null($this->parentInstanceId)))
     {
-      $query = 'INSERT INTO '.GALAXIA_TABLE_PREFIX.'interinstance_relations(wf_parent_instance_id, wf_parent_activity_id, wf_child_instance_id, wf_parent_lock) VALUES(?,?,?,?)';
-      $this->query($query,array((int) $this->parentInstanceId, (int) $this->parentActivityId, (int) $iid, (int) (($this->parentLock) ? 1 : 0)));
-    }
-    
+      $query = 'INSERT INTO '.GALAXIA_TABLE_PREFIX.'interinstance_relations
+                  (wf_parent_instance_id, wf_child_instance_id, wf_parent_lock)
+                VALUES
+                  (?,?,?)';
+      $this->query($query,array((int) $this->parentInstanceId, (int) $iid, (int) (($this->parentLock) ? 1 : 0)));
+    }
+
     //update database with other datas stored in the object
     return $this->sync();
   }
-  
+
   /**
    * Sets the name of this instance
@@ -1140,9 +1143,9 @@
     return $this->__activity_completed;
   }
- 
+
   /**
    * This function can be called by the instance object himself (for automatic activities)
-   * or by the WfRuntime object. In interactive activities code users use complete() --without args-- 
-   * which refer to the WfRuntime->complete() function which call this one. 
+   * or by the WfRuntime object. In interactive activities code users use complete() --without args--
+   * which refer to the WfRuntime->complete() function which call this one.
    * In non-interactive activities a call to a complete() will generate errors because the engine
    * does it his own way as I said first.
@@ -1160,5 +1163,5 @@
   {
     //$this->db->
-    $result = $this->query("SELECT 1 FROM " . GALAXIA_TABLE_PREFIX . "instances i, " . GALAXIA_TABLE_PREFIX . "interinstance_relations ir WHERE (ir.wf_child_instance_id = i.wf_instance_id) AND (i.wf_status IN ('active', 'exception')) AND (ir.wf_parent_lock = 1) AND (ir.wf_parent_instance_id = ?) AND (ir.wf_parent_activity_id = ?)", array($this->instanceId, $activityId));
+    $result = $this->query("SELECT 1 FROM " . GALAXIA_TABLE_PREFIX . "instances i, " . GALAXIA_TABLE_PREFIX . "interinstance_relations ir WHERE (ir.wf_child_instance_id = i.wf_instance_id) AND (i.wf_status IN ('active', 'exception')) AND (ir.wf_parent_lock = 1) AND (ir.wf_parent_instance_id = ?)", array($this->instanceId));
     if ($result->numRows() > 0)
       die("Esta instância está aguardando que outras instâncias, das quais depende, sejam finalizadas.");
@@ -1168,5 +1171,5 @@
     //The complete() is in a transaction, it will be completly done or not at all
     $this->db->StartTrans();
-    
+
     //lock rows and ensure access is granted
     if (!(isset($this->security))) $this->security = &Factory::getInstance('WfSecurity');
Index: sandbox/workflow/branches/1015/inc/engine/src/API/BaseActivity.php
===================================================================
--- sandbox/workflow/branches/1015/inc/engine/src/API/BaseActivity.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/engine/src/API/BaseActivity.php	(revision 3061)
@@ -84,8 +84,9 @@
    * Seems to be the rest of a bad object architecture
    * 
-   * @deprecated
+   * @deprecated 2.2.00.000
    */
   function setDb(&$db)
   {
+	wf_warn_deprecated_method();
     $this->db =& $db;
   }
@@ -550,8 +551,9 @@
    * e.g. $isadmin = $activity->checkUserRole($user,'admin')
    * 
-   * @deprecated Unused function. Old API, do not use it. Return always false
+   * @deprecated 2.2.00.000 - Unused function. Old API, do not use it. Return always false
    */
   function checkUserRole($user,$rolename) 
   {
+	wf_warn_deprecated_method();
     $this->error[] = 'use of an old deprecated function checkUserRole, return always false';
     return false;
Index: sandbox/workflow/branches/1015/inc/common_functions.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/common_functions.inc.php	(revision 3061)
+++ sandbox/workflow/branches/1015/inc/common_functions.inc.php	(revision 3061)
@@ -0,0 +1,68 @@
+<?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.                                              *
+\**************************************************************************/
+
+
+/**
+ * Redefines the apache_request_headers function if it was not done before by a phpmodule
+ * This usually happens if php runs as cgi
+ * @return array HTTP info presents in $_SERVER array
+ * @package Workflow
+ * @access public
+ */
+if( !function_exists('apache_request_headers') ) {
+	///
+	function apache_request_headers() {
+		$arh = array();
+		$rx_http = '/\AHTTP_/';
+		foreach($_SERVER as $key => $val) {
+			if( preg_match($rx_http, $key) ) {
+				$arh_key = preg_replace($rx_http, '', $key);
+				$rx_matches = array();
+				// do some nasty string manipulations to restore the original letter case
+				// this should work in most cases
+				$rx_matches = explode('_', $arh_key);
+				if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
+					foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
+					$arh_key = implode('-', $rx_matches);
+				}
+				$arh[$arh_key] = $val;
+			}
+		}
+		return( $arh );
+	}
+	///
+}
+
+/**
+ * Generates warning message of deprecated methods executing PHP function trigger_error
+ * @author Anderson Tadayuki Saikawa
+ * @param string $new_class The name of the class that has the method that replaces the deprecated one
+ * @param string $new_method The name of the method that replaces the deprecated one
+ * @return boolean
+ * @license http://www.gnu.org/copyleft/gpl.html GPL
+ * @package Workflow
+ * @access public
+ */
+function wf_warn_deprecated_method($new_class = null, $new_method = null)
+{
+	$caller = next(debug_backtrace());
+	$old_class = !empty($caller['class']) ? " of <strong>" . $caller['class'] . "</strong> object" : "";
+	$deprecated_msg = sprintf("Deprecated method <strong>%s</strong>%s was called in <strong>%s</strong> on line <strong>%s</strong>. It MUST be replaced by its equivalent",
+								$caller['function'], $old_class, $caller['file'], $caller['line']);
+	if(!empty($new_class) && !empty($new_method)){
+		$new_class = !empty($new_class) ? " of <strong>" . $new_class . "</strong> object" : "";
+		$deprecated_msg .= sprintf(' <strong>%s</strong>%s', $new_method, $new_class);
+	}
+	$error_msg = $deprecated_msg . ".\n<br>Error handler";
+	return trigger_error("[WORKFLOW WARNING]: " . $error_msg, E_USER_WARNING);
+}
+
+?>
Index: sandbox/workflow/branches/1015/inc/class.bo_participants.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.bo_participants.inc.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/class.bo_participants.inc.php	(revision 3061)
@@ -74,5 +74,5 @@
 		{
 			$preffix = ($usePreffix) ? 'u' : '';
-			$ents = $this->ldap->getUsers($params['context']);
+			$ents = $this->ldap->getUsers($params['context'], $params['onlyVisibleAccounts']);
 			foreach ($ents as $ent)
 				$output[$preffix . $ent[$id]] = $ent['name'];
@@ -162,7 +162,9 @@
 		$searchLists = (strpos($entities, 'l') !== false);
 
+		$onlyVisibleAccounts = $params['onlyVisibleAccounts'];
+
 		/* faz a busca */
 		$output = array();
-		$output['participants'] = $this->ldap->search($searchTerm, $searchUsers, $searchGroups, $searchLists);
+		$output['participants'] = $this->ldap->search($searchTerm, $searchUsers, $searchGroups, $searchLists, null, $onlyVisibleAccounts);
 
 		/* limita os resultados e define uma mensagem que será exibida */
Index: sandbox/workflow/branches/1015/inc/common.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/common.inc.php	(revision 2588)
+++ sandbox/workflow/branches/1015/inc/common.inc.php	(revision 3061)
@@ -70,3 +70,4 @@
 require_once WF_LIB_ROOT . 'factory/WorkflowFactory.php';
 require_once WF_LIB_ROOT . 'factory/ProcessFactory.php';
+require_once WF_INC_ROOT . 'common_functions.inc.php';
 ?>
Index: sandbox/workflow/branches/1015/inc/class.ui_adminroles.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.ui_adminroles.inc.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/class.ui_adminroles.inc.php	(revision 3061)
@@ -276,7 +276,7 @@
 					$entry = $cachedLDAP->getEntryByID($mapping['wf_user']);
 					$cname = $GLOBALS['phpgw']->translation->convert($entry['cn'],'utf-8');
-					$glabel = "";
+					$glabel = (!empty($entry['uid'])) ? '[' . $entry['uid'] . ']' : '';
 					if (is_null($entry['last_update']))
-						$glabel = '<font color="red">(excluído)</font>';
+						$glabel = '<font color="red">(inativo)</font>';
 				}
 
Index: sandbox/workflow/branches/1015/inc/class.ui_participants.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.ui_participants.inc.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/class.ui_participants.inc.php	(revision 3061)
@@ -92,4 +92,10 @@
 		$hideSectors = ($_REQUEST['hideSectors'] == '1') ? true : false;
 
+		// the default value of $onlyVisibleAccounts is true
+		if((isset($_REQUEST['onlyVisibleAccounts'])) && (empty($_REQUEST['onlyVisibleAccounts']) || $_REQUEST['onlyVisibleAccounts'] === 'false'))
+			$onlyVisibleAccounts = false;
+		else
+			$onlyVisibleAccounts = true;
+
 		/* define the initial organization */
 		$selectedOrganization = $ldap->getOrganizationFromDN($userDN);
@@ -117,7 +123,7 @@
 		$smarty->assign('organizations', $organizationList);
 		$smarty->assign('selectedOrganization', $selectedOrganization);
-		$smarty->assign('sectors', $this->bo->getSectors(array('organization' => $selectedOrganization), true));
+		$smarty->assign('sectors', $this->bo->getSectors(array('organization' => $selectedOrganization, 'onlyVisibleAccounts' => $onlyVisibleAccounts), true));
 		$smarty->assign('selectedSector', $selectedSector);
-		$smarty->assign('participants', $this->bo->getEntities(array('entities' => $entities, 'id' => $id, 'context' => $selectedSector, 'usePreffix' => $usePreffix), true));
+		$smarty->assign('participants', $this->bo->getEntities(array('entities' => $entities, 'id' => $id, 'context' => $selectedSector, 'onlyVisibleAccounts' => $onlyVisibleAccounts, 'usePreffix' => $usePreffix), true));
 		$smarty->assign('entities', $entities);
 		$smarty->assign('id', $id);
@@ -126,4 +132,5 @@
 		$smarty->assign('hideOrganizations', $hideOrganizations);
 		$smarty->assign('hideSectors', $hideSectors);
+		$smarty->assign('onlyVisibleAccounts', $onlyVisibleAccounts);
 		$smarty->assign('header', $smarty->expressoHeader);
 		$smarty->assign('txt_loading', lang("loading"));
Index: sandbox/workflow/branches/1015/inc/class.so_userinterface.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.so_userinterface.inc.php	(revision 2588)
+++ sandbox/workflow/branches/1015/inc/class.so_userinterface.inc.php	(revision 3061)
@@ -333,5 +333,5 @@
 			{
 				$employees[$i]['telephoneNumber'] = is_null($entry['telephonenumber']) ? '' : $entry['telephonenumber'];
-				$employees[$i]['cn'] = is_null($entry['cn']) ? '' : $entry['cn'] . (is_null($entry['last_update']) ? ' <font color="red">(excluído)</font>' : '');
+				$employees[$i]['cn'] = is_null($entry['cn']) ? '' : $entry['cn'] . (is_null($entry['last_update']) ? ' <font color="red">(inativo)</font>' : '');
 			}
 		}
Index: sandbox/workflow/branches/1015/inc/class.ui_adminactivities.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.ui_adminactivities.inc.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/class.ui_adminactivities.inc.php	(revision 3061)
@@ -1035,35 +1035,54 @@
 		$image_name = $proc_info['wf_normalized_name'] . SEP . 'graph' . SEP . $proc_info['wf_normalized_name'] . '.png';
 		$image = GALAXIA_PROCESSES . SEP . $image_name;
-		if (Factory::getInstance('BrowserInfo')->isOpera())
-			$maximumDimension = 1000000;
+		if (file_exists($image))
+		{
+			if (Factory::getInstance('BrowserInfo')->isOpera())
+				$maximumDimension = 1000000;
+			else
+				$maximumDimension = 2500;
+
+			$dims = getimagesize($image);
+			list($originalWidth, $originalHeight) = $dims;
+
+			/* the image must be resized */
+			if (max($originalWidth, $originalHeight) > $maximumDimension)
+			{
+				/* define the new width and height */
+				$newWidth = $newHeight = $maximumDimension;
+				if ($originalWidth > $originalHeight)
+					$newHeight = $maximumDimension * ($originalHeight / $originalWidth);
+				else
+					$newWidth = $maximumDimension * ($originalWidth / $originalHeight);
+
+				/* create the new image and send to the browser */
+				$smallerImage = imagecreatetruecolor($newWidth, $newHeight);
+				imagecopyresampled($smallerImage, imagecreatefrompng($image), 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
+				header('content-disposition: inline; filename=' . $image_name);
+				header('content-type: ' . $dims['mime']);
+				imagepng($smallerImage);
+			}
+			else
+			{
+				header('content-disposition: inline; filename=' . $image_name);
+				header('content-type: ' . $dims['mime']);
+				header('content-length: ' . filesize($image));
+				readfile($image);
+			}
+		}
+		// if there is no graph, show "graph not found" message
 		else
-			$maximumDimension = 2500;
-
-		$dims = getimagesize($image);
-		list($originalWidth, $originalHeight) = $dims;
-
-		/* the image must be resized */
-		if (max($originalWidth, $originalHeight) > $maximumDimension)
-		{
-			/* define the new width and height */
-			$newWidth = $newHeight = $maximumDimension;
-			if ($originalWidth > $originalHeight)
-				$newHeight = $maximumDimension * ($originalHeight / $originalWidth);
-			else
-				$newWidth = $maximumDimension * ($originalWidth / $originalHeight);
-
-			/* create the new image and send to the browser */
-			$smallerImage = imagecreatetruecolor($newWidth, $newHeight);
-			imagecopyresampled($smallerImage, imagecreatefrompng($image), 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
-			header('content-disposition: inline; filename=' . $image_name);
-			header('content-type: ' . $dims['mime']);
-			imagepng($smallerImage);
-		}
-		else
-		{
-			header('content-disposition: inline; filename=' . $image_name);
-			header('content-type: ' . $dims['mime']);
-			header('content-length: ' . filesize($image));
-			readfile($image);
+		{
+			header ('Content-type: image/png');
+			$text = 'GRAFICO NAO ENCONTRADO';
+			$font_size = 5;
+			$width = imagefontwidth($font_size) * strlen($text);
+			$height = imagefontheight($font_size);
+			$im = imagecreate($width, $height);
+			$text_color = imagecolorallocate($im, 0, 0, 0);		// black
+			$bg_color = imagecolorallocate($im, 255, 255, 255);	// white
+			imagefill($im, 0, 0, $bg_color);
+			imagestring($im, $font_size, 0, 0, $text, $text_color);
+			imagepng($im);
+			imagedestroy($im);
 		}
 	}
Index: sandbox/workflow/branches/1015/inc/class.WorkflowLDAP.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.WorkflowLDAP.inc.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/class.WorkflowLDAP.inc.php	(revision 3061)
@@ -377,7 +377,10 @@
 	 * @access public
 	 */
-	function getUsers($context)
-	{
-		$filter = '(&(phpgwaccounttype=u)(!(phpgwAccountVisible=-1)))';
+	function getUsers($context, $onlyVisibleAccounts = true)
+	{
+		$filter = '(phpgwaccounttype=u)';
+		if($onlyVisibleAccounts)
+			$filter = '(&' . $filter . '(!(phpgwAccountVisible=-1)))';
+
 		$elements = array('uidnumber', 'cn', 'mail');
 		return $this->getEntities($context, $filter, $elements, 'u', false);
@@ -561,5 +564,5 @@
 	 * @access public
 	 */
-	function search($searchTerm, $includeUsers = true, $includeGroups = false, $includeLists = false, $context = null)
+	function search($searchTerm, $includeUsers = true, $includeGroups = false, $includeLists = false, $context = null, $onlyVisibleAccounts = true)
 	{
 		if (!($includeUsers || $includeGroups || $includeLists))
@@ -586,5 +589,9 @@
 			$entityFilter = $entityFilter[0];
 
-		$filter = "(&{$entityFilter}(cn={$searchTerm})(!(phpgwAccountVisible=-1)))";
+		if($onlyVisibleAccounts)
+			$filter = "(&{$entityFilter}(cn={$searchTerm})(!(phpgwAccountVisible=-1)))";
+		else
+			$filter = "(&{$entityFilter}(cn={$searchTerm}))";
+
 		$resourceIdentifier = ldap_search($this->dataSource, $context, $filter, array('cn', 'uidnumber', 'gidnumber', 'phpgwaccounttype', 'mail'));
 		ldap_sort($this->dataSource, $resourceIdentifier, 'cn');
Index: sandbox/workflow/branches/1015/inc/smarty/plugins/function.html_options.php
===================================================================
--- sandbox/workflow/branches/1015/inc/smarty/plugins/function.html_options.php	(revision 795)
+++ sandbox/workflow/branches/1015/inc/smarty/plugins/function.html_options.php	(revision 3061)
@@ -96,4 +96,71 @@
 }
 
+function smarty_function_html_boxoptions($params, &$smarty)
+{
+    require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
+    
+    $name = null;
+    $values = null;
+    $options = null;
+    $selected = array();
+    $output = null;
+    
+    $extra = '';
+    
+    foreach($params as $_key => $_val) {
+        switch($_key) {
+            case 'name':
+                $$_key = (string)$_val;
+                break;
+            
+            case 'options':
+                $$_key = (array)$_val;
+                break;
+                
+            case 'values':
+            case 'output':
+                $$_key = array_values((array)$_val);
+                break;
+
+            case 'selected':
+                $$_key = array_map('strval', array_values((array)$_val));
+                break;
+
+            default:
+                if(!is_array($_val)) {
+                    $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
+                } else {
+                    $smarty->trigger_error("html_options: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
+                }
+                break;
+        }
+    }
+
+    if (!isset($options) && !isset($values))
+        return ''; /* raise error here? */
+
+    $_html_result = '';
+
+    if (isset($options)) {
+
+        foreach ($options as $_key=>$_val)
+            $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected);
+
+    } else {
+
+        foreach ($values as $_i=>$_key) {
+            $_val = isset($output[$_i]) ? $output[$_i] : '';
+            $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected);
+        }
+
+    }
+
+    if(!empty($name)) {
+        $_html_result = '<select name="' . $name . '"' . $extra . ' style="height: 100px;" size="5">' . "\n" . $_html_result . '</select>' . "\n";
+    }
+
+    return $_html_result;
+
+}
 function smarty_function_html_options_optoutput($key, $value, $selected) {
     if(!is_array($value)) {
Index: sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_user.php
===================================================================
--- sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_user.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_user.php	(revision 3061)
@@ -12,4 +12,5 @@
  * - email_as_textarea : indica se o campo que receberá os emails deve ser um textarea (valor true) ou input type text (valor false). Este parâmetro só tem validade se get_email for true.
  * - hide_groups : indica se deve-se omitir os grupos na tela de seleção.
+ * - onlyVisibleAccounts : indica se devem ser recuperadas apenas as contas visíveis, ou se as ocultas também devem ser listadas.
  * - organization : nome da organização que estará previamente selecionada.
  * - title : texto da tooltip que aparecerá quando o usuário colocar o mouse sobre o ícone para adicionar usuário.
@@ -35,4 +36,5 @@
 		'hide_organizations' => false,
 		'hide_sectors' => false,
+		'onlyVisibleAccounts' => true,
 		'rows'=> 2);
 	$extractParams = array(
@@ -42,5 +44,6 @@
 		'title',
 		'cols',
-		'rows');
+		'rows',
+		'onlyVisibleAccounts');
 
 	/* verifica se todos os parâmetros obrigatórios foram passados */
@@ -93,9 +96,13 @@
 	if ($params['hide_sectors'] == true)
 		$extraParams .= "&hideSectors=1";
+	if (empty($onlyVisibleAccounts) || $onlyVisibleAccounts === 'false')
+		$extraParams .= "&onlyVisibleAccounts=false";
+	else
+		$extraParams .= "&onlyVisibleAccounts=true";
 
 	$image = Factory::getInstance('TemplateServer')->generateImageLink('add_user.png');
 
-$output .= <<<EOF
-	<a alt="$title" title="$title" href="javascript:void(0)" onclick="openParticipants('$name', '$extraParams');"><img border="0" alt="" src="$image" /></a>
+	$output .= <<<EOF
+		<a alt="$title" title="$title" href="javascript:void(0)" onclick="openParticipants('$name', '$extraParams');"><img border="0" alt="" src="$image" /></a>
 EOF;
 	return $output;
Index: sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_ldap_users.php
===================================================================
--- sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_ldap_users.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_ldap_users.php	(revision 3061)
@@ -23,5 +23,5 @@
  */
 function smarty_function_wf_select_ldap_users($params, &$smarty)
-{
+{ 
     require_once $smarty->_get_plugin_filepath('function','html_options');
 	$imagesPath = substr(Factory::getInstance('TemplateServer')->generateImageLink(''), 0, -1);
@@ -34,5 +34,6 @@
 		'size_input'            => '20',
 		'opt_id'                => 'dn',
-		'opt_name'              => 'cn');
+		'opt_name'              => 'cn',
+		'opt_complement'        => '');
 	$extractParams = array(
 		'name',
@@ -42,5 +43,6 @@
 		'class_btn',
 		'opt_id',
-		'opt_name');
+		'opt_name',
+		'opt_complement');
 
 	/* verifica se todos os parâmetros obrigatórios foram passados */
@@ -78,10 +80,10 @@
 	$output = <<<EOF
 		<input type="text" id="$name_input" name="$name_input" size="$size_input" />
-		<input type="button" class="$class_btn" value="$value_btn" onclick="search_ldap_users_by_cn(document.getElementById('$name_input').value, '$name', '$opt_id', '$opt_name', $handleExpiredSessions)" />
+		<input type="button" class="$class_btn" value="$value_btn" onclick="search_ldap_users_by_cn(document.getElementById('$name_input').value, '$name', '$opt_id', '$opt_name', $handleExpiredSessions, '$opt_complement')" />
 		&nbsp;<img id="$name_img" border="0" src="$imagesPath/loading.gif" style="display:none">
-		<span id="$name_span" style="display:none">&nbsp;&nbsp;&nbsp;&nbsp;<b>Selecione o nome: </b>
+		<span id="$name_span" style="display:none"><br><br><b>Selecione um nome abaixo: </b><br><br>
 EOF;
 
-	$output .= smarty_function_html_options(array_merge(array(
+	$output .= smarty_function_html_boxoptions(array_merge(array(
 											'name'    => $name,
 											'id'      => $name,
Index: sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_users.php
===================================================================
--- sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_users.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/smarty/wf_plugins/function.wf_select_users.php	(revision 3061)
@@ -8,4 +8,5 @@
  * - value : usuários e grupos previamente selecionados. Deve estar no formato de matriz, seguindo o seguinte padrão: ::$matriz["u123"]="Nome do usuário 123" ; $matriz["g321"]="Nome do grupo 321" e, assim por diante.
  * - hide_groups : indica se deve-se omitir os grupos na tela de seleção.
+ * - onlyVisibleAccounts : indica se devem ser recuperadas apenas as contas visíveis, ou se as ocultas também devem ser listadas.
  * - organization : nome da organização que estará previamente selecionada.
  * @param object &$smarty Instância do objeto smarty em uso
@@ -24,8 +25,10 @@
 		'hide_organizations' => false,
 		'hide_sectors' => false,
+		'onlyVisibleAccounts' => true,
 		'value' => array());
 	$extractParams = array(
 		'name',
-		'value');
+		'value',
+		'onlyVisibleAccounts');
 
 	/* verifica se todos os parâmetros obrigatórios foram passados */
@@ -54,4 +57,8 @@
 	if ($params['hide_sectors'] == true)
 		$extraParams .= "&hideSectors=1";
+	if (empty($onlyVisibleAccounts) || $onlyVisibleAccounts === 'false')
+		$extraParams .= "&onlyVisibleAccounts=false";
+	else
+		$extraParams .= "&onlyVisibleAccounts=true";
 
 	$output = '<table border="0"><tr><td>';
@@ -66,7 +73,7 @@
 	$output .= "</td><td>";
 	$output .= <<<EOF
-		<a href='javascript:void(0)' onclick="openParticipants(500, 270, '$name', '$extraParams');"><img border="0" src="$imagesPath/add_group.png"></a>
+		<a href='javascript:void(0)' onclick="openParticipants(500, 315, '$name', '$extraParams');"><img border="0" src="$imagesPath/add_group.png"></a>
 		<br />
-		<a href='javascript:void(0)' onclick="openParticipants(500, 270, '$name', '$extraParams');">Adicionar</a>
+		<a href='javascript:void(0)' onclick="openParticipants(500, 315, '$name', '$extraParams');">Adicionar</a>
 		<br /><br />
 		<a href='javascript:void(0)' onclick="delUsers('$name');"><img border="0" src="$imagesPath/delete_group.png"></a>
Index: sandbox/workflow/branches/1015/inc/class.bo_userinterface.inc.php
===================================================================
--- sandbox/workflow/branches/1015/inc/class.bo_userinterface.inc.php	(revision 2372)
+++ sandbox/workflow/branches/1015/inc/class.bo_userinterface.inc.php	(revision 3061)
@@ -91,10 +91,17 @@
 					$recset[$procname_ver]['useHTTPS'] = 0;
 			}
-			$recset[$procname_ver][] = array('wf_activity_id' 	=> $line['wf_activity_id'],
-										'wf_name' 			=> $line['wf_name'],
-										'wf_menu_path' 		=> $line['wf_menu_path'],
-										'wf_type' 			=> $line['wf_type'],
-										'wf_is_autorouted' 	=> $line['wf_is_autorouted'],
-										'wf_is_interactive' => $line['wf_is_interactive']);
+			if (!is_dir(GALAXIA_PROCESSES . '/' . $line['wf_normalized_name']))
+			{
+				$recset[$procname_ver]['wf_iconfile'] = $templateServer->generateImageLink('navbar_nocode.png');
+			}
+			else
+			{
+				$recset[$procname_ver][] = array('wf_activity_id' 	=> $line['wf_activity_id'],
+												'wf_name' 			=> $line['wf_name'],
+												'wf_menu_path' 		=> $line['wf_menu_path'],
+												'wf_type' 			=> $line['wf_type'],
+												'wf_is_autorouted' 	=> $line['wf_is_autorouted'],
+												'wf_is_interactive' => $line['wf_is_interactive']);
+			}
 		}
 
Index: sandbox/workflow/branches/1015/js/htmlarea/plugins/UploadImage/popups/ImageEditor/Transform.php
===================================================================
--- sandbox/workflow/branches/1015/js/htmlarea/plugins/UploadImage/popups/ImageEditor/Transform.php	(revision 795)
+++ sandbox/workflow/branches/1015/js/htmlarea/plugins/UploadImage/popups/ImageEditor/Transform.php	(revision 3061)
@@ -130,5 +130,5 @@
 
         $classname = "Image_Transform_Driver_{$driver}";
-        $obj =& new $classname;
+        $obj = new $classname;
         return $obj;
     }
Index: sandbox/workflow/branches/1015/js/userinterface/orgchart.js
===================================================================
--- sandbox/workflow/branches/1015/js/userinterface/orgchart.js	(revision 2371)
+++ sandbox/workflow/branches/1015/js/userinterface/orgchart.js	(revision 3061)
@@ -348,5 +348,5 @@
 				complement = '';
 			if (employees[i]['removed'])
-				complement += ' <font color="red">(excluído)</font>';
+				complement += ' <font color="red">(inativo)</font>';
 			content += '<tr class="linha'+ i%2 + (useCategories ? ' categoria_' + employees[i]['funcionario_categoria_id'] : '') + '" onmouseover="this.className=\'highlight0\'" onmouseout="this.className=\'linha'+ i%2 + (useCategories ? ' categoria_' + employees[i]['funcionario_categoria_id'] : '') + '\'">';
 			content += '<td><a href="javascript:void(0);" onmouseover="getEmployeeInfoTimer(event, ' + employees[i]['funcionario_id'] + '); return false;" onmouseout="hideEmployeeInfo(); return false;">' + employees[i]['cn'] + complement + '</a></td>';
Index: sandbox/workflow/branches/1015/js/jscode/wf_file_upload.js
===================================================================
--- sandbox/workflow/branches/1015/js/jscode/wf_file_upload.js	(revision 795)
+++ sandbox/workflow/branches/1015/js/jscode/wf_file_upload.js	(revision 3061)
@@ -149,4 +149,6 @@
 		};
 
+
+
 		// Set row value
 		new_row.innerHTML = element.value + '&nbsp;&nbsp;';
@@ -160,3 +162,9 @@
 	};
 
+	this.removeFile = function (me, nome){
+		me.parentNode.parentNode.removeChild(me.parentNode);
+		hd = document.getElementById("hd_remover_anexos");
+		hd.value += nome+"; ";
+	}
+
 };
Index: sandbox/workflow/branches/1015/js/jscode/wf_select_ldap_users.js
===================================================================
--- sandbox/workflow/branches/1015/js/jscode/wf_select_ldap_users.js	(revision 795)
+++ sandbox/workflow/branches/1015/js/jscode/wf_select_ldap_users.js	(revision 3061)
@@ -9,6 +9,11 @@
  * @param String opt_name Atributo que será atribuído ao name (innerHTML) das options da combo, por padrão é o 'cn'
  */
-function search_ldap_users_by_cn(cn, target, opt_id, opt_name, handleExpiredSessions)
-{
+function search_ldap_users_by_cn(cn, target, opt_id, opt_name, handleExpiredSessions, opt_complement)
+{  
+	// o parâmetro opt_complement foi acrescentado posteriormente a esta função, devido alguns métodos não utilizá-lo é
+	// necessário fazer o tratamento do mesmo caso não seja passado.
+	if(opt_complement == undefined)
+		opt_complement = '';
+
 /* Método que trata o retorno da chamada Ajax. Atribui os valores retornados à combobox */
 	function result_search_ldap_users_by_cn(data)
@@ -35,5 +40,5 @@
 			var container = document.getElementById(data["target"]);
 			container.innerHTML = "";
-			if(data['values'].length > 1){
+			if(data['values'].length >= 1){
 				container.disabled = true;
 				fill_combo_employee(data["target"], data["values"]);
@@ -44,8 +49,10 @@
 			}
 		}
+
+		return false;
 	}
 
 	var url = '$this.bo_utils.search_ldap_users_by_cn';
-	var param = "cn=" + cn + "&target=" + target + "&id=" + opt_id + "&name=" + opt_name;
+	var param = "cn=" + cn + "&target=" + target + "&id=" + opt_id + "&name=" + opt_name + "&complement=" + opt_complement;
 
 	document.getElementById(target + "_img").show();
Index: sandbox/workflow/branches/1015/js/jscode/participants.js
===================================================================
--- sandbox/workflow/branches/1015/js/jscode/participants.js	(revision 795)
+++ sandbox/workflow/branches/1015/js/jscode/participants.js	(revision 3061)
@@ -1,3 +1,4 @@
 var participantsClone = null;
+var chkOnlyVisibleAccountsClone = null;
 var searchTimer = null;
 var globalSearchEnter = true;
@@ -23,4 +24,5 @@
 	var params = {
 		organization: $F('organization'),
+		onlyVisibleAccounts: $F('onlyVisibleAccounts'),
 		entities: $F('entities'),
 		id: $F('id'),
@@ -34,4 +36,5 @@
 	var params = {
 		context: $F('sector'),
+		onlyVisibleAccounts: $F('onlyVisibleAccounts'),
 		entities: $F('entities'),
 		id: $F('id'),
@@ -46,4 +49,6 @@
 	setSelectValue($('participants'), data);
 	participantsClone = data;
+	if($('onlyVisibleAccounts'))
+		chkOnlyVisibleAccountsClone = $('onlyVisibleAccounts').checked;
 }
 
@@ -63,4 +68,6 @@
 	var reg = new RegExp("<option[^>]*>[^<]*" + searchString + "[^<]*<\/option>", "gi");
 	setSelectValue($('participants'), participantsClone.match(reg));
+	if($('onlyVisibleAccounts'))
+		$('onlyVisibleAccounts').checked = chkOnlyVisibleAccountsClone;
 
 	var participants = $('participants');
@@ -126,6 +133,9 @@
 
 		obj = $('participants');
-		if (obj)
+		if (obj){
 			participantsClone = obj.innerHTML;
+			if($('onlyVisibleAccounts'))
+				chkOnlyVisibleAccountsClone = $('onlyVisibleAccounts').checked;
+		}
 
 		obj = $('exitLink');
@@ -140,4 +150,8 @@
 		if (obj)
 			obj.focus();
+
+		obj = $('onlyVisibleAccounts');
+		if (obj)
+			obj.onclick = checkOnlyVisibleAccounts;
 
 		obj = $('useGlobalSearch');
@@ -149,4 +163,12 @@
 	});
 };
+
+function checkOnlyVisibleAccounts()
+{
+	if(!$('useGlobalSearch').checked)
+		getParticipants();
+	else
+		toggleFullSearch();
+}
 
 function participantsFilterName(name)
@@ -330,4 +352,5 @@
 	$('globalSearchWarnings').innerHTML = '';
 	var params = {
+		onlyVisibleAccounts: $F('onlyVisibleAccounts'),
 		searchTerm: $F('search'),
 		entities: $F('entities'),
@@ -341,5 +364,5 @@
 {
 	newWidth   = 500;
-	newHeight  = 290;
+	newHeight  = 315;
 	newScreenX = screen.width - newWidth;
 	newScreenY = 0;
Index: sandbox/workflow/branches/1015/js/orgchart/organization.js
===================================================================
--- sandbox/workflow/branches/1015/js/orgchart/organization.js	(revision 2063)
+++ sandbox/workflow/branches/1015/js/orgchart/organization.js	(revision 3061)
@@ -483,5 +483,5 @@
 			data[i]['tr_attributes']['class'] = "linha" + i%2;
 			data[i]['tr_attributes']['className'] = "linha" + i%2;
-			data[i]['funcionario_id_desc'] = '<a href="javascript:void(0)" class="lbOn" onmouseover="getEmployeeInfoTimer(event, ' + data[i]['funcionario_id'] + ', ' + organizationID + '); return false;" onmouseout="hideEmployeeInfo(); return false;" onclick="loadAddEmployeeUI(' + organizationID + ', function(){objEmployee.fillForm(' + dataHash.customInspect() + ')}); $(\'addEmployeeLink\').parentNode.removeChild($(\'addEmployeeLink\')); return false;">' + data[i]['funcionario_id_desc'] + '</a>' + (data[i]['removed'] ? ' <font color="red">(excluído)</font>' : '');
+			data[i]['funcionario_id_desc'] = '<a href="javascript:void(0)" class="lbOn" onmouseover="getEmployeeInfoTimer(event, ' + data[i]['funcionario_id'] + ', ' + organizationID + '); return false;" onmouseout="hideEmployeeInfo(); return false;" onclick="loadAddEmployeeUI(' + organizationID + ', function(){objEmployee.fillForm(' + dataHash.customInspect() + ')}); $(\'addEmployeeLink\').parentNode.removeChild($(\'addEmployeeLink\')); return false;">' + data[i]['funcionario_id_desc'] + '</a>' + (data[i]['removed'] ? ' <font color="red">(inativo)</font>' : '');
 			data[i]['actions'] = '<a href="#" onclick="objEmployee.remove({\'funcionario_id\': ' + data[i]['funcionario_id'] + ', \'organizacao_id\': ' + organizationID + '} , this.parentNode.parentNode); return false;"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/button_cancel.png" /></a>';
 		}
@@ -537,5 +537,5 @@
 			data[i]['tr_attributes']['class'] = "linha" + i%2;
 			data[i]['tr_attributes']['className'] = "linha" + i%2;
-			data[i]['funcionario_id_desc'] = '<a href="javascript:void(0)" class="lbOn" onmouseover="getEmployeeInfoTimer(event, ' + data[i]['funcionario_id'] + ', ' + organizationID + '); return false;" onmouseout="hideEmployeeInfo(); return false;" onclick="loadAddEmployeeUI(' + organizationID + ', function(){objEmployee.fillForm(' + dataHash.customInspect() + ')}); $(\'addEmployeeLink\').parentNode.removeChild($(\'addEmployeeLink\')); return false;">' + data[i]['funcionario_id_desc'] + ' ' + complement + '</a>' + (data[i]['removed'] ? ' <font color="red">(excluído)</font>' : '');
+			data[i]['funcionario_id_desc'] = '<a href="javascript:void(0)" class="lbOn" onmouseover="getEmployeeInfoTimer(event, ' + data[i]['funcionario_id'] + ', ' + organizationID + '); return false;" onmouseout="hideEmployeeInfo(); return false;" onclick="loadAddEmployeeUI(' + organizationID + ', function(){objEmployee.fillForm(' + dataHash.customInspect() + ')}); $(\'addEmployeeLink\').parentNode.removeChild($(\'addEmployeeLink\')); return false;">' + data[i]['funcionario_id_desc'] + ' ' + complement + '</a>' + (data[i]['removed'] ? ' <font color="red">(inativo)</font>' : '');
 			data[i]['actions'] = '<a href="#" onclick="objEmployee.remove({\'funcionario_id\': ' + data[i]['funcionario_id'] + ', \'organizacao_id\': ' + organizationID + '} , this.parentNode.parentNode); return false;"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/button_cancel.png" /></a>';
 			window.scrollTo(0,0);
Index: sandbox/workflow/branches/1015/index.php
===================================================================
--- sandbox/workflow/branches/1015/index.php	(revision 2372)
+++ sandbox/workflow/branches/1015/index.php	(revision 3061)
@@ -9,4 +9,7 @@
 *  option) any later version.                                              *
 \**************************************************************************/
+
+/* Including common stuff to prepare workflow to run. A session start is needed */
+require_once 'inc/common.inc.php';
 
 /* if the menuaction variable is set, then let the expresso index deal with it */
@@ -38,5 +41,4 @@
 	);
 	require_once '../header.inc.php';
-	require_once 'inc/common.inc.php';
 
 	if (isset($_GET['start_tab']))
Index: sandbox/workflow/branches/1015/templates/default/participants.tpl
===================================================================
--- sandbox/workflow/branches/1015/templates/default/participants.tpl	(revision 795)
+++ sandbox/workflow/branches/1015/templates/default/participants.tpl	(revision 3061)
@@ -32,4 +32,9 @@
 		<td colspan="2">
 			<p style="text-align: center; font-weight: bold; font-size: 130%;">Busca Global</p>
+		</td>
+	</tr>
+	<tr>
+		<td colspan="2">
+			<label><input type="checkbox" name="onlyVisibleAccounts" id="onlyVisibleAccounts" value="true" {if $onlyVisibleAccounts} checked {/if}/> Exibir apenas contas vis&iacute;veis</label>
 		</td>
 	</tr>
