source: branches/1.2/workflow/inc/class.bo_userinterface.inc.php @ 1349

Revision 1349, 33.5 KB checked in by niltonneto, 15 years ago (diff)

Ticket #561 - Inclusão do módulo Workflow faltante nessa versão.

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