source: sandbox/workflow/trunk/inc/class.bo_userinterface.inc.php @ 2372

Revision 2372, 37.6 KB checked in by pedroerp, 14 years ago (diff)

Ticket #609 - Merged 2197:2356 /sandbox/workflow/branches/609/ em /sandbox/workflow/trunk.

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