source: companies/serpro/workflow/inc/class.bo_userinterface.inc.php @ 903

Revision 903, 33.3 KB checked in by niltonneto, 15 years ago (diff)

Importacao inicial do Expresso do Serpro

Line 
1<?php
2/**************************************************************************\
3* eGroupWare                                                                       *
4* http://www.egroupware.org                                                *
5* --------------------------------------------                             *
6*  This program is free software; you can redistribute it and/or modify it *
7*  under the terms of the GNU General Public License as published by the   *
8*  Free Software Foundation; either version 2 of the License, or (at your  *
9*  option) any later version.                                              *
10\**************************************************************************/
11
12require_once('class.so_userinterface.inc.php');
13require_once('class.bo_ajaxinterface.inc.php');
14require_once('class.Paging.inc.php');
15
16require_once(GALAXIA_LIBRARY . SEP . 'src' . SEP . 'GUI' . SEP . 'GUI.php');
17require_once(GALAXIA_LIBRARY . SEP . 'src' . SEP . 'ProcessManager' . SEP . 'ActivityManager.php');
18/**
19 * @package Workflow
20 * @license http://www.gnu.org/copyleft/gpl.html GPL
21 * @author Mauricio Luiz Viani - viani@celepar.pr.gov.br
22 * @author Sidnei Augusto Drovetto - drovetto@gmail.com
23 */
24class bo_userinterface extends bo_ajaxinterface
25{
26        /**
27         * @var object Acesso à camada Model
28         * @access public
29         */
30        var $so;
31
32        /**
33         * @var array Informações sobre a organização do usuário
34         * @access private
35         */
36        private $organizationInfo;
37
38        /**
39         * Construtor da classe bo_userinterface
40         * @access public
41         * @return object
42         */
43        function bo_userinterface()
44        {
45                parent::bo_ajaxinterface();     
46                $this->so = new so_userinterface();
47                $GLOBALS['ajax']->gui = new GUI($GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID);
48        }
49
50        /**
51         * Retorna os processos do usuário
52         * @access public
53         * @return mixed retorna uma string com uma mensagem de erro ou um array com dados dos processos
54         */
55        function processes()
56        {
57                $account_id = $_SESSION['phpgw_info']['workflow']['account_id'];
58                $result = $GLOBALS['ajax']->gui->gui_list_user_activities($account_id, '0', '-1', "wf_menu_path__ASC, ga.wf_name__ASC", '', '', '', true, true, true, '');
59
60                $errorMessage = $GLOBALS['ajax']->gui->get_error(false);
61                if (!empty($errorMessage))
62                {
63                        $this->disconnect_all();
64                        return array('error' => $errorMessage);
65                }
66
67                $recset = array();
68                $webserver_url = $_SESSION['phpgw_info']['workflow']['server']['webserver_url'];
69
70                $templateServer = &$GLOBALS['workflow']['factory']->getInstance('TemplateServer');
71                foreach ($result['data'] as $line)
72                {
73                        /* don't include activities whose menu_path is equal to ! */
74                        if ($line['wf_menu_path'] === '!')
75                                continue;
76
77                        if (file_exists(GALAXIA_PROCESSES . '/' . $line['wf_normalized_name'] . '/resources/icon.png'))
78                                $iconweb = $webserver_url . '/workflow/redirect.php?pid=' . $line['wf_p_id'] . '&file=/icon.png';
79                        else
80                                $iconweb = $templateServer->generateImageLink('navbar.png');
81                        $procname_ver = $line['wf_normalized_name'];
82                        if (!isset($recset[$procname_ver]))
83                        {
84                                $recset[$procname_ver]['wf_p_id'] = $line['wf_p_id'];
85                                $recset[$procname_ver]['wf_procname'] = $line['wf_procname'];
86                                $recset[$procname_ver]['wf_version'] = $line['wf_version'];
87                                $recset[$procname_ver]['wf_is_active'] = $line['wf_is_active'];
88                                $recset[$procname_ver]['wf_iconfile'] = $iconweb;
89                                if ($_SESSION['phpgw_info']['workflow']['server']['use_https'] > 0)
90                                {
91                                        $GLOBALS['ajax']->gui->wf_security->loadConfigValues($line['wf_p_id']);
92                                        $recset[$procname_ver]['useHTTPS'] = $GLOBALS['ajax']->gui->wf_security->processesConfig[$line['wf_p_id']]['execute_activities_using_secure_connection'];
93                                }
94                                else
95                                        $recset[$procname_ver]['useHTTPS'] = 0;
96                        }
97                        $recset[$procname_ver][] = array('wf_activity_id'       => $line['wf_activity_id'],
98                                                                                'wf_name'                       => $line['wf_name'],
99                                                                                'wf_menu_path'          => $line['wf_menu_path'],
100                                                                                'wf_type'                       => $line['wf_type'],
101                                                                                'wf_is_autorouted'      => $line['wf_is_autorouted'],
102                                                                                'wf_is_interactive' => $line['wf_is_interactive']);
103                }
104
105                $recset = array_values($recset);
106                usort($recset, create_function('$a,$b', 'return strcasecmp($a[\'wf_procname\'] . $a[\'wf_version\'],$b[\'wf_procname\'] . $b[\'wf_version\']);'));
107
108                $this->disconnect_all();
109                return $recset;
110        }
111
112        /**
113         * Informacoes sobre o processo
114         * @param $params parametros
115         * @return array
116         * @access public
117         */
118        function process_about($params)
119        {
120                $pid = $params['pid'];
121                $result = array();
122               
123                $process = new Process($GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID);
124                $process->getProcess($pid);
125                $result['wf_procname'] = $process->name;
126                $result['wf_version'] = $process->version;
127                $result['wf_description'] = $process->description;
128               
129                $activ_manager = new ActivityManager($GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID);
130                $result['wf_activities'] = $activ_manager->get_process_activities($pid);
131               
132                $this->disconnect_all();
133               
134                return $result;
135        }
136
137        /**
138         * Fornece os dados para a contrução da interface de Tarefas Pendentes
139         * @param $params Parâmetros advindos da chamada Ajax
140         * @return array Contendo os dados para construção da interface ou uma mensagem de erro
141         * @access public
142         */
143        function inbox($params)
144        {
145                $preferences = $_SESSION['phpgw_info']['workflow']['user']['preferences'];
146
147                /* initialize Paging Class */
148                $itemsPerPage = isset($preferences['ui_items_per_page']) ? $preferences['ui_items_per_page'] : 15;
149                $lightVersion = ((isset($preferences['use_light_interface']) ? $preferences['use_light_interface'] : 0) == 1);
150                $paging = new Paging($itemsPerPage, $_POST);
151
152                /* define the sorting */
153                $sort = 'wf_act_started__DESC';
154                if ($params['sort'])
155                        $sort = $params['sort'];
156                else
157                        if (isset($preferences['inbox_sort']))
158                                $sort = $preferences['inbox_sort'];
159                /* make sure that the sorting parameter is one of the expected values */
160                $sortFields = explode('__', strtolower($sort));
161                if (count($sortFields) != 2)
162                        $sort = 'wf_act_started__DESC';
163                else
164                        if (!(in_array($sortFields[0], array('wf_act_started', 'wf_procname', 'wf_name', 'insname')) && in_array($sortFields[1], array('desc', 'asc'))))
165                                $sort = 'wf_act_started__DESC';
166                $params['sort'] = $sort;
167
168                /* get other parameters */
169                $pid = (int) $params['pid'];
170                $search_term = $params['search_term'];
171                $account_id = $_SESSION['phpgw_info']['workflow']['account_id'];
172                $result = $GLOBALS['ajax']->gui->gui_list_user_instances($account_id, 0, -1, $sort, $search_term, "ga.wf_is_interactive = 'y'", false, $pid, true, false, true, false, false, false);
173
174                $errorMessage = $GLOBALS['ajax']->gui->get_error(false);
175                if (!empty($errorMessage))
176                {
177                        $this->disconnect_all();
178                        return array('error' => $errorMessage);
179                }
180
181                $output = array();
182                $output['instances'] = array();
183                $output['processes'] = array();
184                $list_process = array();
185                $actionKeys = array(
186                        'run',
187                        'viewrun',
188                        'view',
189                        'send',
190                        'release',
191                        'grab',
192                        'exception',
193                        'resume',
194                        'abort',
195                        'monitor');
196
197                foreach ($result['data'] as $row)
198                {
199                        /* don't show the instance if the user can't run it */
200                        if (($row['wf_user'] != $account_id) && ($row['wf_user'] != '*'))
201                                continue;
202                        if (($row['wf_status'] == 'active') || ($row['wf_status'] == 'exception'))
203                        {
204                                $availableActions = $GLOBALS['ajax']->gui->getUserActions(
205                                                        $account_id,
206                                                        $row['wf_instance_id'],
207                                                        $row['wf_activity_id'],
208                                                        $row['wf_readonly'],
209                                                        $row['wf_p_id'],
210                                                        $row['wf_type'],
211                                                        $row['wf_is_interactive'],
212                                                        $row['wf_is_autorouted'],
213                                                        $row['wf_act_status'],
214                                                        $row['wf_owner'],
215                                                        $row['wf_status'],
216                                                        $row['wf_user']);
217
218                                $row['viewRunAction'] = false;
219                                if (isset($availableActions['viewrun']))
220                                        $row['viewRunAction'] = array('viewActivityID' => $availableActions['viewrun']['link'], 'height' => $availableActions['viewrun']['iframe_height']);
221
222                                foreach ($actionKeys as $key)
223                                        $availableActions[$key] = (isset($availableActions[$key]));
224
225                                if ($GLOBALS['ajax']->gui->wf_security->processesConfig[$row['wf_p_id']]['disable_advanced_actions'] == 1)
226                                {
227                                        $availableActions['release'] = false;
228                                        $availableActions['grab'] = false;
229                                        $availableActions['exception'] = false;
230                                        $availableActions['resume'] = false;
231                                        $availableActions['abort'] = false;
232                                        $availableActions['monitor'] = false;
233                                }
234
235                                /* define the advanced actions for javascript usage */
236                                $actionsArray = array();
237                                $actionsArray[] = array('name' => 'run', 'value' => $availableActions['run'], 'text' => 'Executar');
238                                $actionsArray[] = array('name' => 'view', 'value' => $availableActions['view'], 'text' => 'Visualizar');
239                                $actionsArray[] = array('name' => 'send', 'value' => $availableActions['send'], 'text' => 'Enviar');
240                                $actionsArray[] = array('name' => 'viewrun', 'value' => $availableActions['viewrun'], 'text' => '');
241                                $actionsArray[] = ($row['wf_user'] == '*') ?
242                                        array('name' => 'grab', 'value' => $availableActions['grab'], 'text' => 'Capturar') :
243                                        array('name' => 'release', 'value' => $availableActions['release'], 'text' => 'Liberar Acesso');
244                                $actionsArray[] = ($row['wf_status'] == 'active') ?
245                                        array('name' => 'exception', 'value' => $availableActions['exception'], 'text' => 'Colocar em Exceção') :
246                                        array('name' => 'resume', 'value' => $availableActions['resume'], 'text' => 'Retirar de Exceção');
247                                $actionsArray[] = array('name' => 'abort', 'value' => $availableActions['abort'], 'text' => 'Abortar');
248
249                                $row['wf_actions'] = $actionsArray;
250
251                                $row['wf_started'] = date('d/m/Y H:i', $row['wf_started']);
252                                $row['wf_act_started'] = date('d/m/Y H:i', $row['wf_act_started']);
253
254                                $row['wf_user_fullname'] = '';
255                                if ($row['wf_user'] == '*')
256                                        $row['wf_user_fullname'] = '*';
257                                else
258                                        if ($row['wf_user'] != '')
259                                                $row['wf_user_fullname'] = $GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP')->getName($row['wf_user']);
260
261                                /* unset unneeded information */
262                                unset($row['wf_ended'], $row['wf_owner'], $row['wf_category'], $row['wf_act_status'], $row['wf_started'], $row['wf_type'], $row['wf_is_interactive'], $row['wf_is_autorouted'], $row['wf_normalized_name'], $row['wf_readonly']);
263                                $output['instances'][] = $row;
264                        }
265                }
266
267                /* paginate the results */
268                $output['instances'] = $paging->restrictItems($output['instances']);
269                $output['paging_links'] = $paging->commonLinks();
270
271                /* only save different actions set */
272                $actions = array_values(array_map(create_function('$a', 'return unserialize($a);'), array_unique(array_map(create_function('$a', 'return serialize($a[\'wf_actions\']);'), $output['instances']))));
273
274                $actionsArray = array();
275                $userNames = array();
276                $processesInfo = array();
277                $activityNames = array();
278                foreach ($output['instances'] as $key => $value)
279                {
280                        $userNames[$value['wf_user']] = $value['wf_user_fullname'];
281                        unset($output['instances'][$key]['wf_user_fullname']);
282
283                        $processesInfo[$value['wf_p_id']] = array(
284                                'name' => $value['wf_procname'] . ' (v' . $value['wf_version'] . ')',
285                                'useHTTPS' => (($_SESSION['phpgw_info']['workflow']['server']['use_https'] > 0) ? $GLOBALS['ajax']->gui->wf_security->processesConfig[$value['wf_p_id']]['execute_activities_using_secure_connection'] : 0)
286                        );
287                        unset($output['instances'][$key]['wf_procname']);
288                        unset($output['instances'][$key]['wf_version']);
289
290                        $activityNames[$value['wf_activity_id']] = $value['wf_name'];
291                        unset($output['instances'][$key]['wf_name']);
292
293                        $output['instances'][$key]['wf_actions'] = array_search($value['wf_actions'], $actions);
294                        if (is_null($value['insname']))
295                                $output['instances'][$key]['insname'] = '';
296                }
297
298                $output['userNames'] = $userNames;
299                $output['processesInfo'] = $processesInfo;
300                $output['activityNames'] = $activityNames;
301                $output['actions'] = $actions;
302
303                /* load all the activities that have at least one instance */
304                $allActivities = $GLOBALS['ajax']->gui->gui_list_user_activities($account_id, 0, -1, "ga.wf_name__ASC", '', "gia.wf_user = '$account_id' OR gia.wf_user = '*'", true);
305                foreach ($allActivities['data'] as $activity)
306                        $list_process[$activity['wf_procname'] . " (v" . $activity['wf_version'] . ")"] = $activity['wf_p_id'];
307
308                $this->disconnect_all();
309
310                foreach ($list_process as $processName => $processId)
311                        $output['processes'][] = array('name' => $processName, 'pid' => $processId);
312
313                /* some extra params */
314                $output['params'] = $params;
315                $output['light'] = $lightVersion;
316                $output['instancesDigest'] = md5(serialize($output['instances']));
317
318                return $output;
319        }
320
321        /**
322         * Fornece os dados para a contrução da interface de Tarefas Pendentes (quando os dados estão agrupados)
323         * @return array Contendo os dados para construção da interface ou uma mensagem de erro
324         * @access public
325         */
326        function inbox_group()
327        {
328                $account_id = $_SESSION['phpgw_info']['workflow']['account_id'];
329                $result = $GLOBALS['ajax']->gui->gui_list_user_instances($account_id, 0, -1, 'wf_procname__ASC,wf_name__ASC', '', "ga.wf_is_interactive = 'y'", false, 0, true, false, true, false, false, false);
330
331                $output = array();
332                foreach ($result['data'] as $data)
333                {
334                        if (($data['wf_user'] != $account_id) && ($data['wf_user'] != "*"))
335                                continue;
336                        if (isset($output[$data['wf_activity_id']]))
337                                $output[$data['wf_activity_id']]['wf_instances']++;
338                        else
339                                $output[$data['wf_activity_id']] = array('wf_p_id' => $data['wf_p_id'], 'wf_procname' => $data['wf_procname'], 'wf_version' => $data['wf_version'], 'wf_name' => $data['wf_name'], 'wf_instances' => 1);
340                }
341
342                $errorMessage = $GLOBALS['ajax']->gui->get_error(false);
343                if (!empty($errorMessage))
344                {
345                        $this->disconnect_all();
346                        return array('error' => $errorMessage);
347                }
348
349                $this->disconnect_all();
350                return array_values($output);
351        }
352
353        /**
354         * Envia uma instância para próxima atividade
355         * @param $params Parâmetros advindos da chamada Ajax
356         * @return mixed Array contendo uma mensagem de erro ou um booleano (true) informando que a ação foi feita com sucesso
357         * @access public
358         */
359        function inboxActionSend($params)
360        {
361                $instanceID = (int) $params['instanceID'];
362                $activityID = (int) $params['activityID'];
363                $result = true;
364
365                if (!$GLOBALS['ajax']->gui->gui_send_instance($activityID, $instanceID))
366                        $result = array('error' => $GLOBALS['ajax']->gui->get_error(false) . "<br />Você não está autorizado a enviar esta instância.");
367
368                $this->disconnect_all();
369
370                return $result;
371        }
372
373        /**
374         * Libera uma instância (atribui a instância para *)
375         * @param $params Parâmetros advindos da chamada Ajax
376         * @return mixed Array contendo uma mensagem de erro ou um booleano (true) informando que a ação foi feita com sucesso
377         * @access public
378         */
379        function inboxActionRelease($params)
380        {
381                $instanceID = (int) $params['instanceID'];
382                $activityID = (int) $params['activityID'];
383                $result = true;
384
385                if (!$GLOBALS['ajax']->gui->gui_release_instance($activityID, $instanceID))
386                        $result = array('error' => $GLOBALS['ajax']->gui->get_error(false) . "<br />Você não está autorizado a liberar esta instância.");
387
388                $this->disconnect_all();
389
390                return $result;
391        }
392
393        /**
394         * Captura uma instância (atribui a instância para o usuário atual)
395         * @param $params Parâmetros advindos da chamada Ajax
396         * @return mixed Array contendo uma mensagem de erro ou um booleano (true) informando que a ação foi feita com sucesso
397         * @access public
398         */
399        function inboxActionGrab($params)
400        {
401                $instanceID = (int) $params['instanceID'];
402                $activityID = (int) $params['activityID'];
403                $result = true;
404
405                if (!$GLOBALS['ajax']->gui->gui_grab_instance($activityID, $instanceID))
406                        $result = array('error' => $GLOBALS['ajax']->gui->get_error(false) . "<br />Você não tem permissão para capturar esta instância.");
407
408                $this->disconnect_all();
409
410                return $result;
411        }
412
413        /**
414         * Transforma a instância em exceção
415         * @param $params Parâmetros advindos da chamada Ajax
416         * @return mixed Array contendo uma mensagem de erro ou um booleano (true) informando que a ação foi feita com sucesso
417         * @access public
418         */
419        function inboxActionException($params)
420        {
421                $instanceID = (int) $params['instanceID'];
422                $activityID = (int) $params['activityID'];
423                $result = true;
424
425                if (!$GLOBALS['ajax']->gui->gui_exception_instance($activityID, $instanceID))
426                        $result = array('error' => $GLOBALS['ajax']->gui->get_error(false) . "<br />Você não tem permissão para transformar esta instância em exceção.");
427
428                $this->disconnect_all();
429
430                return $result;
431        }
432
433        /**
434         * Retira uma instância em exceção
435         * @param $params Parâmetros advindos da chamada Ajax
436         * @return mixed Array contendo uma mensagem de erro ou um booleano (true) informando que a ação foi feita com sucesso
437         * @access public
438         */
439        function inboxActionResume($params)
440        {
441                $instanceID = (int) $params['instanceID'];
442                $activityID = (int) $params['activityID'];
443                $result = true;
444
445                if (!$GLOBALS['ajax']->gui->gui_resume_instance($activityID, $instanceID))
446                        $result = array('error' => $GLOBALS['ajax']->gui->get_error(false) . "<br />Você não tem permissão para retirar de exceção esta instância.");
447
448                $this->disconnect_all();
449
450                return $result;
451        }
452
453        /**
454         * Aborta uma instância
455         * @param $params Parâmetros advindos da chamada Ajax
456         * @return mixed Array contendo uma mensagem de erro ou um booleano (true) informando que a ação foi feita com sucesso
457         * @access public
458         */
459        function inboxActionAbort($params)
460        {
461                $instanceID = (int) $params['instanceID'];
462                $activityID = (int) $params['activityID'];
463                $result = true;
464
465                if (!$GLOBALS['ajax']->gui->gui_abort_instance($activityID, $instanceID))
466                        $result = array('error' => $GLOBALS['ajax']->gui->get_error(false) . "<br />Você não tem permissão para abortar esta instância.");
467
468                $this->disconnect_all();
469
470                return $result;
471        }
472
473        /**
474         * Visualiza dados de uma instância
475         * @param $params Parâmetros advindos da chamada Ajax
476         * @return mixed Array contendo uma mensagem de erro ou um booleano (true) informando que a ação foi feita com sucesso
477         * @access public
478         */
479        function inboxActionView($params)
480        {
481                $instanceID = $params['instanceID'];
482                $result = $GLOBALS['ajax']->gui->wf_security->checkUserAction(0, $instanceID, 'view');
483
484                $errorMessage = $GLOBALS['ajax']->gui->get_error(false);
485                if (!empty($errorMessage))
486                {
487                        $this->disconnect_all();
488                        return array('error' => $errorMessage);
489                }
490
491                $instance = new Instance($GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID);
492                $instance->getInstance($instanceID);
493
494                $process = new Process($GLOBALS['workflow']['workflowObjects']->getDBGalaxia()->Link_ID);
495                $process->getProcess($instance->pId);
496
497                $result = array(
498                        'wf_status' => $instance->status,
499                        'wf_p_id' => $instance->pId,
500                        'wf_procname' => $process->name,
501                        'wf_version' => $process->version,
502                        'wf_instance_id' => $instance->instanceId,
503                        'wf_priority' => $instance->priority,
504                        'wf_owner' => $GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP')->getName($instance->owner),
505                        'wf_next_activity' => $instance->nextActivity,
506                        'wf_next_user' => $GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP')->getName($instance->nextUser),
507                        'wf_name' => $instance->name,
508                        'wf_category' => $instance->category,
509                        'wf_started' => date('d/m/Y H:i', $instance->started)
510                );
511
512                $viewActivityID = $GLOBALS['ajax']->gui->gui_get_process_view_activity($instance->pId);
513                if ($viewActivityID !== false)
514                        if ($GLOBALS['ajax']->gui->wf_security->checkUserAction($viewActivityID, $instanceID, 'viewrun'))
515                                $result['viewRunAction'] = array('viewActivityID' => $viewActivityID, 'height' => $GLOBALS['ajax']->gui->wf_security->processesConfig[$instance->pId]['iframe_view_height'], 'useHTTPS' => (($_SESSION['phpgw_info']['workflow']['server']['use_https'] > 0) ? $GLOBALS['ajax']->gui->wf_security->processesConfig[$instance->pId]['execute_activities_using_secure_connection'] : 0));
516
517        if ($instance->ended > 0)
518                $result['wf_ended'] = date('d/m/Y H:i', $instance->ended);
519        else
520                $result['wf_ended'] = "";
521
522                $ldap = &$GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP');
523                foreach ($instance->workitems as $line)
524                {
525                $line['wf_duration'] = $this->time_diff($line['wf_ended']-$line['wf_started']);
526                $line['wf_started'] = date('d/m/Y H:i', $line['wf_started']);
527                $line['wf_ended'] = date('d/m/Y H:i', $line['wf_ended']);
528                $line['wf_user'] = $ldap->getName($line['wf_user']);
529                $result['wf_workitems'][] = $line;
530        }
531
532                foreach ($instance->activities as $line)
533                {
534                $line['wf_started'] = date('d/m/Y H:i', $line['wf_started']);
535                        if ($line['wf_ended'] > 0)
536                                $line['wf_ended'] = date('d/m/Y H:i', $line['wf_ended']);
537                        else
538                                $line['wf_ended'] = "";
539                $line['wf_user'] = $ldap->getName($line['wf_user']);
540                $result['wf_activities'][] = $line;
541        }
542
543        $show_properties = false;
544
545                $current_user_id = $_SESSION['phpgw_info']['workflow']['account_id'];
546
547                /* check if the current user is a process admin */
548        $is_admin_process = $GLOBALS['ajax']->acl->check_process_access($current_user_id, $instance->pId);
549        $is_admin_workflow = $_SESSION['phpgw_info']['workflow']['user_is_admin'];
550                $show_properties = ($is_admin_process || $is_admin_workflow);
551
552                if($show_properties)
553                {
554                        foreach ($instance->properties as $key => $value)
555                        {
556                        $result['wf_properties']['keys'][] = $key;
557                        $result['wf_properties']['values'][] = wordwrap(htmlspecialchars($value), 80, "<br>", 1);
558                }
559        }
560
561                $this->disconnect_all();
562                return $result;
563        }
564
565        /**
566         * Retorna os idiomas 
567         * @return array 
568         * @access public
569         */     
570        function getLang(){
571                       
572                $keys = array();
573                $values = array();
574                $langs = array();
575                foreach($_SESSION['phpgw_info']['workflow']['lang'] as $key => $value) {
576                        $keys[]         = $key;
577                        $values[]       = $value;
578                }
579                array_push($langs,$keys,$values);
580                return $langs;
581        }
582       
583        /**
584         * Return  a given duration in human readable form, usefull for workitems duration
585         *
586         *  @param $to
587         *  @return string a given duration in human readable form, usefull for workitems duration
588         */
589        function time_diff($to) {
590                $days = (int)($to/(24*3600));
591                $to = $to - ($days*(24*3600));
592                $hours = (int)($to/3600);
593                $to = $to - ($hours*3600);
594                $min = date("i", $to);
595                $to = $to - ($min*60);                 
596                $sec = date("s", $to);
597
598                return tra('%1 days, %2:%3:%4',$days,$hours,$min,$sec);
599        }
600       
601        /**
602         *  Instances
603         *  @param $params
604         *  @return string a given duration in human readable form, usefull for workitems duration
605         *  @access public
606         */
607        function instances($params)
608        {
609                $preferences = $_SESSION['phpgw_info']['workflow']['user']['preferences'];
610
611                $lightVersion = ((isset($preferences['use_light_interface']) ? $preferences['use_light_interface'] : 0) == 1);
612
613                /* get some parameters */
614                $userID = $_SESSION['phpgw_info']['workflow']['account_id'];
615                $pid = (int) $params['pid'];
616                $active = ($params['active'] == 1);
617
618                $defaultSorting = ($active ? 'wf_act_started__DESC' : 'wf_started__DESC');
619                $availableSortings = $active ?
620                        array('wf_act_started', 'wf_procname', 'wf_name', 'insname') :
621                        array('wf_started', 'wf_ended', 'wf_procname', 'insname');
622
623                /* define the sorting */
624                $sort = $defaultSorting;
625                if ($params['sort'])
626                        $sort = $params['sort'];
627                /* make sure that the sorting parameter is one of the expected values */
628                $sortFields = explode('__', strtolower($sort));
629                if (count($sortFields) != 2)
630                        $sort = $defaultSorting;
631                else
632                        if (!(in_array($sortFields[0], $availableSortings) && in_array($sortFields[1], array('desc', 'asc'))))
633                                $sort = $defaultSorting;
634                $params['sort'] = $sort;
635
636
637                /* retrieve the results */
638                $result = $GLOBALS['ajax']->gui->gui_list_instances_by_owner($userID, 0, -1, $sort, '', '', false, 0, $active, !$active, $active, !$active);
639
640                $errorMessage = $GLOBALS['ajax']->gui->get_error(false);
641                if (!empty($errorMessage))
642                {
643                        $this->disconnect_all();
644                        return array('error' => $errorMessage);
645                }
646
647                $output['params'] = $params;
648                $output['instances'] = array();
649                $output['processes'] = array();
650                $list_process = array();
651                $cod_process = array();
652
653                $ldap = &$GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP');
654                $viewActivitiesID = array();
655                foreach ($result['data'] as $row)
656                {
657                        if (($pid == 0) || ($row['wf_p_id'] == $pid))
658                        {
659                                $row['wf_started'] = date('d/m/Y H:i', $row['wf_started']);
660                                if ($row['wf_ended'])
661                                        $row['wf_ended'] = date('d/m/Y H:i', $row['wf_ended']);
662
663                                if ($row['wf_act_started'])
664                                        $row['wf_act_started'] = date('d/m/Y H:i', $row['wf_act_started']);
665
666                                $row['wf_user_fullname'] = '';
667                                if ($row['wf_user'] != '*' && $row['wf_user'] != '')
668                                        $row['wf_user_fullname'] = $ldap->getName($row['wf_user']);
669
670                                /* load information about the view activity */
671                                if (!isset($viewActivitiesID[$row['wf_p_id']]))
672                                        $viewActivitiesID[$row['wf_p_id']] = $GLOBALS['ajax']->gui->gui_get_process_view_activity($row['wf_p_id']);
673                                if ($viewActivitiesID[$row['wf_p_id']] !== false)
674                                        if ($GLOBALS['ajax']->gui->wf_security->checkUserAction($viewActivitiesID[$row['wf_p_id']], $row['wf_instance_id'], 'viewrun'))
675                                                $row['viewRunAction'] = array('viewActivityID' => $viewActivitiesID[$row['wf_p_id']], 'height' => $GLOBALS['ajax']->gui->wf_security->processesConfig[$instance->pId]['iframe_view_height']);
676
677                                $output['instances'][] = $row;
678                        }
679                        $processNameAndVersion = $row['wf_procname'] . " (v" . $row['wf_version'] . ")";
680                        if (!isset($list_process[$processNameAndVersion]))
681                                $list_process[$processNameAndVersion] = array('total' => 1, 'pid' => $row['wf_p_id'], 'name' => $processNameAndVersion);
682                        else
683                                $list_process[$processNameAndVersion]['total']++;
684                }
685
686                ksort($list_process);
687                $output['processes'] = array_values($list_process);
688
689                $userNames = array();
690                $processesInfo = array();
691                $activityNames = array();
692                foreach ($output['instances'] as $key => $value)
693                {
694                        $userNames[$value['wf_user']] = $value['wf_user_fullname'];
695                        unset($output['instances'][$key]['wf_user_fullname']);
696
697                        $processesInfo[$value['wf_p_id']] = array(
698                                'name' => $value['wf_procname'] . ' (v' . $value['wf_version'] . ')',
699                                'useHTTPS' => (($_SESSION['phpgw_info']['workflow']['server']['use_https'] > 0) ? $GLOBALS['ajax']->gui->wf_security->processesConfig[$value['wf_p_id']]['execute_activities_using_secure_connection'] : 0)
700                        );
701
702                        if ($active)
703                        {
704                                $activityNames[$value['wf_activity_id']] = $value['wf_name'];
705                                unset($output['instances'][$key]['wf_name']);
706                        }
707
708                        if (is_null($value['insname']))
709                                $output['instances'][$key]['insname'] = '';
710                }
711
712                $output['userNames'] = $userNames;
713                $output['processesInfo'] = $processesInfo;
714                $output['activityNames'] = $activityNames;
715
716                $output['light'] = $lightVersion;
717
718                if (!isset($params['group_instances']))
719                {
720                        /* paginate the result */
721                        $itemsPerPage = isset($_SESSION['phpgw_info']['workflow']['user']['preferences']['ui_items_per_page']) ? $_SESSION['phpgw_info']['workflow']['user']['preferences']['ui_items_per_page'] : 15;
722                        $paging = new Paging($itemsPerPage, $_POST);
723                        $output['instances'] = $paging->restrictItems($output['instances']);
724                        $output['paging_links'] = $paging->commonLinks();
725                }
726                else
727                        unset($output['instances']);
728
729                $this->disconnect_all();
730
731                return $output;
732        }
733
734        /**
735         * Aplicacoes externas do usuario
736         * @return array
737         * @access public
738         */
739        function externals()
740        {
741                $webserver_url = $_SESSION['phpgw_info']['workflow']['server']['webserver_url'];
742                $templateServer = &$GLOBALS['workflow']['factory']->getInstance('TemplateServer');
743
744                /* load the sites that the user can access */
745                $allowedSites = $this->so->getExternalApplications();
746
747                /* prepare the data for the javascript */
748                $output = array();
749                foreach ($allowedSites as $row)
750                {
751                        if ($row['image'] == "")
752                                $row['image'] = $templateServer->generateImageLink('navbar.png');
753                        else
754                                $row['image'] = $webserver_url . '/workflow/redirect.php?file=/external_applications/' . $row['image'];
755
756                        if ($row['authentication'] == 1)
757                                $row['wf_ext_link'] = (($_SESSION['phpgw_info']['workflow']['server']['use_https'] > 0) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . "$webserver_url/index.php?menuaction=workflow.external_bridge.render&site=" . $row['external_application_id'];
758                        else
759                                $row['wf_ext_link'] = $row['address'];
760
761                        $output[] = $row;
762                }
763
764                return $output;
765        }
766
767        /**
768         * Verifica se o usuário tem acesso ao Organograma (e se o mesmo está ativo)
769         * @return mixed true em caso de sucesso ou uma array contendo mensagens sobre o problema (não cadastrado ou organograma não ativo)
770         * @access private
771         */
772        private function checkOrgchartAccess()
773        {
774                $this->organizationInfo = $this->so->getUserOrganization($_SESSION['phpgw_info']['workflow']['account_id']);
775                if ($this->organizationInfo === false)
776                        return array('warning' => 'Você não está cadastrado em nenhuma organização');
777
778                if ($this->organizationInfo['ativa'] == 'N')
779                        return array('warning' => 'Organograma indisponível');
780
781                return true;
782        }
783
784        /**
785         * Organograma
786         * @return array com as areas da organizacao
787         * @access public
788         */
789        function orgchart()
790        {
791                /* check for access */
792                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
793                        return $checkWarnings;
794
795                $this->organizationInfo['areas'] = $this->getHierarchicalArea();
796                return $this->organizationInfo;
797        }
798
799        /**
800         * Retorna a lista de centros de custo
801         * @return array Lista de centros de custo
802         * @access public
803         */
804        function getCostCenters()
805        {
806                /* check for access */
807                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
808                        return $checkWarnings;
809
810                return $this->so->getCostCenters($this->organizationInfo['organizacao_id']);
811        }
812
813        /**
814         * Get the hierarchical Area
815         * @return array
816         * @access public
817         */
818        function getHierarchicalArea()
819        {
820                /* check for access */
821                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
822                        return $checkWarnings;
823
824                return $this->so->getHierarchicalArea($this->organizationInfo['organizacao_id']);
825        }
826
827        /**
828         * Retorna a lista de areas
829         * @return array lista de areas
830         * @access public
831         */
832        function getAreaList()
833        {
834                /* check for access */
835                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
836                        return $checkWarnings;
837
838                $areas = $this->so->getAreaList($this->organizationInfo['organizacao_id']);
839                for ($i = 0; $i < count($areas); $i++)
840                {
841                        $areas[$i]['children'] = false;
842                        $areas[$i]['depth'] = 1;
843                }
844
845                return $areas;
846        }
847
848        /**
849         * Retorna a lista de categorias
850         * @return array lista de categorias
851         * @access public
852         */
853        function getCategoriesList()
854        {
855                /* check for access */
856                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
857                        return $checkWarnings;
858
859                return $this->so->getCategoriesList($this->organizationInfo['organizacao_id']);
860        }
861
862
863        /**
864         * Return the area of employee
865         * @param $params parameters
866         * @access public
867         * @return array array of employees
868         */
869        function getAreaEmployees($params)
870        {
871                /* check for access */
872                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
873                        return $checkWarnings;
874
875                $employees = $this->so->getAreaEmployees((int) $params['areaID'], $this->organizationInfo['organizacao_id']);
876
877                if ($employees === false)
878                        return array('error' => 'Área não encontrada.');
879
880                return $employees;
881        }
882
883        /**
884         * Return the area of employee
885         * @param $params parameters
886         * @access public
887         * @return array array of employees
888         */
889        function getCategoryEmployees($params)
890        {
891                /* check for access */
892                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
893                        return $checkWarnings;
894
895                $employees = $this->so->getCategoryEmployees((int) $params['categoryID'], $this->organizationInfo['organizacao_id']);
896
897                if ($employees === false)
898                        return array('error' => 'Categoria não encontrada.');
899
900                usort($employees['employees'], create_function('$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);'));
901
902                return $employees;
903        }
904
905        /**
906         * Search Employee
907         * @param $params
908         * @access public
909         * @return array search result
910         */
911        function searchEmployee($params)
912        {
913                if (!ereg('^([[:alpha:] ]+)$', $params['searchTerm']))
914                        return array('error' => 'Parâmetro de busca inválido');
915
916                if (strlen(str_replace(' ', '', $params['searchTerm'])) < 2)
917                        return array('error' => 'Utilize ao menos duas letras em sua busca');
918
919                /* check for access */
920                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
921                        return $checkWarnings;
922
923                $result = $this->so->searchEmployee($params['searchTerm'], $this->organizationInfo['organizacao_id']);
924                $this->disconnect_all();
925
926                if ($result === false)
927                        return array('error' => 'O sistema de busca não pode ser utilizado para sua organização');
928
929                usort($result['employees'], create_function('$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);'));
930                return $result;
931        }
932
933        /**
934         * Busca informações sobre um funcionário.
935         * @param array $params Uma array contendo o ID do funcionário cujas informações serão extraídas.
936         * @return array Informações sobre o funcionário.
937         * @access public
938         */
939        function getEmployeeInfo($params)
940        {
941                /* check for access */
942                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
943                        return $checkWarnings;
944
945                $result = $this->so->getEmployeeInfo((int) $params['funcionario_id'], $this->organizationInfo['organizacao_id']);
946                if (is_array($result['info']))
947                {
948                        foreach ($result['info'] as $key => $value)
949                        {
950                                if (($value['name'] == 'Cargo') || ($value['name'] == 'UIDNumber'))
951                                {
952                                        unset($result['info'][$key]);
953                                }
954                        }
955                        $result['info'] = array_values($result['info']);
956                }
957                return $result;
958        }
959
960        /**
961         * Busca informações sobre uma área.
962         * @param array $params Uma array contendo o ID da área cujas informações serão extraídas.
963         * @return array Informações sobre a área.
964         * @access public
965         */
966        function getAreaInfo($params)
967        {
968                /* check for access */
969                if (($checkWarnings = $this->checkOrgchartAccess()) !== true)
970                        return $checkWarnings;
971
972                return $this->so->getAreaInfo((int) $params['area_id'], $this->organizationInfo['organizacao_id']);
973        }
974}
975?>
Note: See TracBrowser for help on using the repository browser.