source: sandbox/workflow/branches/609/inc/class.bo_userinterface.inc.php @ 2292

Revision 2292, 38.0 KB checked in by pedroerp, 14 years ago (diff)

Ticket #609 - Substituindo instanciações diretas (new) pela nova factory.

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