source: trunk/workflow/inc/class.so_userinterface.inc.php @ 6478

Revision 6478, 31.4 KB checked in by leticiabohnert, 12 years ago (diff)

Ticket #2851 - Corrigido erro na função que verifica a permissão do usuário.

  • Property svn:executable set to *
Line 
1<?php
2
3/**
4 * @package Workflow
5 * @license http://www.gnu.org/copyleft/gpl.html GPL
6 * @author Sidnei Augusto Drovetto Jr. - drovetto@gmail.com
7 */
8class so_userinterface
9{
10        /**
11         * @var object database object
12         * @access public
13         */
14        var $db;
15        /**
16         * @var bool True se o usuário for administrador do expresso.
17         * @access private
18         */
19        private $isAdmin;
20
21        /**
22         * @var int ID do usuário logado no Expresso
23         * @access private
24         */
25        private $userID;
26
27        /**
28         * @var object Link para a ACL do Workflow.
29         * @access private
30         */
31        private $acl;
32       
33        /**
34         * @var bool indicando se o usuário possui ou não acesso aos dados restritos.
35         * @access private
36         */
37        private $authorized;
38       
39        /**
40         * Constructor
41         * @access public
42         * @return object
43         */
44        function so_userinterface()
45        {
46                $this->authorized= false;
47                $this->userID = $_SESSION['phpgw_info']['workflow']['account_id'];
48                $this->isAdmin = $_SESSION['phpgw_info']['workflow']['user_is_admin'];
49                $this->acl = Factory::getInstance('workflow_acl');
50                $this->db =& Factory::getInstance('WorkflowObjects')->getDBWorkflow()->Link_ID;
51                $this->db->SetFetchMode(ADODB_FETCH_ASSOC);
52        }
53
54        /**
55         * Obtain the subnet of an IP Address based on the numer of bits of the subnet
56         * @param string $ip The IP Address
57         * @param int $bits Number of bits of the subnet
58         * @return string The subnet of the IP
59         * @access private
60         */
61        private function getSubnet($ip, $bits)
62        {
63                $octets = explode('.', $ip);
64                $output = array();
65                for ($i = 0; $i < 4; $i++)
66                {
67                        if ($bits >= 8)
68                        {
69                                $output[] = $octets[$i];
70                                $bits -= 8;
71                                continue;
72                        }
73                        $output[] = $octets[$i] & bindec(str_repeat('1', $bits) . str_repeat('0',8 - $bits));
74                        $bits = 0;
75                }
76                return implode('.', $output);
77        }
78
79        /**
80         * Get External Applications
81         * @access public
82         * @return array list of external applications
83         */
84        function getExternalApplications()
85        {
86                /* load the intranet subnetworks */
87                $oldDB = $GLOBALS['phpgw']->db;
88                $GLOBALS['phpgw']->db = $GLOBALS['ajax']->db;
89                $config = &Factory::getInstance('config', 'workflow');
90                $configValues = $config->read_repository();
91                $submasksString = $configValues['intranet_subnetworks'];
92                $GLOBALS['phpgw']->db = $oldDB;
93
94                $userIP = getenv('REMOTE_ADDR');
95                if (getenv('HTTP_X_FORWARDED_FOR'))
96                {
97                        $tmpIP = explode(',', getenv('HTTP_X_FORWARDED_FOR'));
98                        $userIP = $tmpIP[0];
99                }
100
101                /* check if the user has access to intranet applications, i.e., is in the intranet */
102                $showIntranetApplications = false;
103                $submasks = explode(';', $submasksString);
104                foreach ($submasks as $submask)
105                {
106                        list($ip,$bits) = explode('/', trim($submask) . '/32', 2);
107                        if ($this->getSubnet($ip, $bits) == $this->getSubnet($userIP, $bits))
108                        {
109                                $showIntranetApplications = true;
110                                break;
111                        }
112                }
113
114                $preOutput = array();
115                $output = array();
116
117                /* select the sites that the user can access */
118                $externalApplicationsID = $GLOBALS['ajax']->acl->getUserGroupPermissions('APX', $_SESSION['phpgw_info']['workflow']['account_id']);
119                if (!empty($externalApplicationsID))
120                {
121                        $result = Factory::getInstance('WorkflowObjects')->getDBGalaxia()->Link_ID->query("SELECT DISTINCT external_application_id, name, address, image, authentication, intranet_only FROM egw_wf_external_application WHERE (external_application_id IN (" . implode(', ', $externalApplicationsID)  . ")) ORDER BY name");
122                        $preOutput = $result->GetArray(-1);
123
124                        /* keep only associative elments and check if the user can access an intranet application */
125                        for ($i = 0; $i < count($preOutput); $i++)
126                        {
127                                if (($preOutput[$i]['intranet_only'] == '1') && (!$showIntranetApplications))
128                                        continue;
129
130                                for ($j = 0; $j < $result->_numOfFields; $j++)
131                                        unset($preOutput[$i][$j]);
132                                $output[] = $preOutput[$i];
133                        }
134                }
135
136                return $output;
137        }
138
139        /**
140         * Get User Organization ID
141         * @param int $userID User identifier
142         * @return mixed Informações sobre a organização ou false em caso de erro.
143         * @access public
144         */
145        function getUserOrganization($userID)
146        {
147                $query = "SELECT o.organizacao_id, o.nome, o.descricao, o.url_imagem, o.ativa FROM funcionario f, organizacao o WHERE (o.organizacao_id = f.organizacao_id) AND (f.funcionario_id = ?)";
148                $result = $this->db->query($query, array((int) $userID));
149
150                $output = $result->fetchRow(DB_FETCHMODE_ASSOC);
151                if (!$output)
152                        return false;
153
154                for ($i = 0; $i < $result->_numOfFields; $i++)
155                        unset($output[$i]);
156
157                return $output;
158        }
159
160        /**
161         * Get cost center list
162         * @param int $organizationID The organization ID
163         * @return array Lista de centros de custo
164         * @access public
165         */
166        function getCostCenters($organizationID)
167        {
168                $result = $this->db->query("SELECT nm_centro_custo, grupo, descricao FROM centro_custo WHERE (organizacao_id = ?) ORDER BY descricao", array($organizationID));
169
170                $output = $result->GetArray(-1);
171                for ($i = 0; $i < count($output); $i++)
172                        for ($j = 0; $j < $result->_numOfFields; $j++)
173                                unset($output[$i][$j]);
174
175                return $output;
176        }
177
178        /**
179         * Get hierarchical Area
180         * @return array
181         * @access public
182         */
183        function getHierarchicalArea($organizationID, $parent = null, $depth = 0)
184        {
185                if (is_null($parent)){
186                        $query = "SELECT a.area_id, a.sigla, a.titular_funcionario_id FROM area a";
187                        $query .=" INNER JOIN area_status a_s ON (a_s.area_status_id = a.area_status_id)";
188                        $query .=" WHERE (a.superior_area_id IS NULL) AND (a.organizacao_id = ?) AND (a.ativa = 'S') ORDER BY a_s.nivel, a.sigla";
189                        $result = $this->db->query($query, array($organizationID));
190                } else {
191                        $query = "SELECT a.area_id, a.sigla, a.titular_funcionario_id FROM area a";
192                        $query .=" INNER JOIN area_status a_s ON (a_s.area_status_id = a.area_status_id)";
193                        $query .=" WHERE (a.superior_area_id = ?) AND (a.ativa = 'S') ORDER BY a_s.nivel, a.sigla";
194                        $result = $this->db->query($query, array($parent));
195                }
196
197                $output = $result->GetArray(-1);
198                for ($i = 0; $i < count($output); $i++)
199                {
200                        for ($j = 0; $j < $result->_numOfFields; $j++)
201                                unset($output[$i][$j]);
202
203                        $output[$i]['children'] = $this->getHierarchicalArea($organizationID, $output[$i]['area_id'], $depth + 1);
204                        $output[$i]['depth'] = $depth;
205                }
206
207                return $output;
208        }
209
210        /**
211         * Get organization area list
212         * @return array
213         * @access public
214         */
215        function getAreaList($organizationID)
216        {
217                $result = $this->db->query("SELECT area_id, sigla FROM area WHERE (organizacao_id = ?) AND (ativa = 'S') ORDER BY sigla", array($organizationID));
218
219                $output = $result->GetArray(-1);
220                for ($i = 0; $i < count($output); $i++)
221                        for ($j = 0; $j < $result->_numOfFields; $j++)
222                                unset($output[$i][$j]);
223
224                return $output;
225        }
226
227        /**
228         * Get organization categories list
229         * @param int $organizationID The organization ID
230         * @return array The categories list
231         * @access public
232         */
233        function getCategoriesList($organizationID)
234        {
235                $output = $this->db->query('SELECT funcionario_categoria_id, descricao FROM funcionario_categoria WHERE (organizacao_id = ?)', array($organizationID))->GetArray();
236                $numerOfEmployees = $this->db->GetAssoc('SELECT COALESCE(f.funcionario_categoria_id, 0) AS funcionario_categoria_id, COUNT(*) FROM funcionario f, funcionario_status fs WHERE (f.organizacao_id = ?) AND (f.funcionario_status_id = fs.funcionario_status_id) AND (fs.exibir = \'S\') GROUP BY funcionario_categoria_id', array($organizationID));
237
238                $output[] = array(
239                        'funcionario_categoria_id' => 0,
240                        'descricao' => 'Sem Vínculo'
241                );
242
243                foreach ($output as &$row)
244                        $row['contagem'] .= (isset($numerOfEmployees[$row['funcionario_categoria_id']]) ? $numerOfEmployees[$row['funcionario_categoria_id']] : 0);
245
246                return $output;
247        }       
248
249        /**
250         * Checa se o usuário possui permissão para visualizar informações restritas.
251         * @param int $organizationID O ID da organização do Orgranograma.
252         * @return void
253         * @access public
254         */
255        public function _checkAccess($organizationID = null)
256        {
257                /* the user is an administrator */
258                if ($this->isAdmin)
259                        $this->authorized=true;
260
261                if (!is_numeric($organizationID))
262                        $this->authorized = false;
263                else
264                        $this->authorized = $this->acl->checkUserAccessToResource('ORG', $this->userID, (int) $organizationID, 1);
265               
266        }
267
268        /**
269         * Get Area Employees
270         * @param int $areaID
271         * @param int $organizationID
272         * @return array
273         * @access public
274         */
275        function getAreaEmployees($areaID, $organizationID)
276        {
277                $organizationID = (int) $organizationID;
278                $areaID = (int) $areaID;
279
280                require_once dirname(__FILE__) . '/local/classes/class.wf_orgchart.php';
281                $orgchart = new wf_orgchart();
282               
283                /* gather some info from the area */
284                $areaInfo = $this->db->query('SELECT COALESCE(a.titular_funcionario_id, -1) AS titular_funcionario_id, COALESCE(s.funcionario_id, -1) AS substituto_funcionario_id FROM area a LEFT OUTER JOIN substituicao s ON ((a.area_id = s.area_id) AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) WHERE (a.organizacao_id = ?) AND (a.area_id = ?)', array($organizationID, $areaID))->GetArray(-1);
285                if (empty($areaInfo))
286                        return false;
287                $areaInfo = $areaInfo[0];
288                $supervisors = '{' . implode(', ', $areaInfo) . '}';
289
290                /* load the employees from the area */
291                $query = "SELECT f.funcionario_id, f.organizacao_id, f.area_id, COALESCE(f.funcionario_categoria_id, 0) AS funcionario_categoria_id FROM funcionario f, funcionario_status s WHERE ((f.area_id = ?) OR (f.funcionario_id = ANY (?))) AND (f.funcionario_status_id = s.funcionario_status_id) AND (s.exibir = ?)";
292                $result = $this->db->query($query, array($areaID, $supervisors, 'S'));
293
294                $employees = $result->GetArray(-1);
295                $cachedLDAP = Factory::newInstance('CachedLDAP');
296                $cachedLDAP->setOperationMode($cachedLDAP->OPERATION_MODE_NORMAL);
297                $categoriesCount = array();
298                for ($i = 0; $i < count($employees); $i++)
299                {
300                        /* remove numeric fields */
301                        for ($j = 0; $j < $result->_numOfFields; $j++)
302                                unset($employees[$i][$j]);
303                       
304                        $employees[$i]['cn'] = '';
305                        $employees[$i]['telephoneNumber'] = '';
306                        if (in_array($employees[$i]['funcionario_id'], $areaInfo))
307                                $employees[$i]['chief'] = ($employees[$i]['funcionario_id'] == $areaInfo['titular_funcionario_id']) ? 1 : 2;
308
309                        /* try to find the telephone number */
310                        $entry = $cachedLDAP->getEntryByID($employees[$i]['funcionario_id']);
311                        if ($entry)
312                        {
313                                $employees[$i]['telephoneNumber'] = is_null($entry['telephonenumber']) ? '' : $entry['telephonenumber'];
314                                $employees[$i]['cn'] = is_null($entry['cn']) ? '' : $entry['cn'];
315                                $employees[$i]['uid'] = is_null($entry['uid']) ? '' : $entry['uid'];
316                                $employees[$i]['uidnumber'] = is_null($entry['uidnumber']) ? '' : $entry['uidnumber'];
317                                $employees[$i]['removed'] = is_null($entry['last_update']);
318                        }
319                       
320                        /*busca o cargo do funcionario*/
321                        $employeeInfo = $orgchart->getEmployee($employees[$i]['funcionario_id']);
322
323                        $cargo = '';
324
325                        if ($this->authorized && !empty($employeeInfo['cargo_id']))
326                        {
327                                $jobTitleInfo = $orgchart->getJobTitle($employeeInfo['cargo_id']);
328                                $cargo = $jobTitleInfo['descricao'];
329                        }
330                        $employees[$i]['cargo'] = utf8_encode($cargo); 
331                       
332                        /*busca o vínculo do funcionario*/
333                        $vinculo = '';
334                        if ($this->authorized && !empty($employeeInfo['funcionario_categoria_id']))
335                        {
336                                $categoryInfo = $orgchart->getEmployeeCategory($employeeInfo['funcionario_categoria_id']);
337                                $vinculo=$categoryInfo['descricao'];
338                        }                       
339                        $employees[$i]['vinculo'] = utf8_encode($vinculo);
340
341                        /* count the number of employees in each category */
342                        $categoryID = $employees[$i]['funcionario_categoria_id'];
343                        if (isset($categoriesCount[$categoryID]))
344                                $categoriesCount[$categoryID]++;
345                        else
346                                $categoriesCount[$categoryID] = 1;                                     
347                }
348                $usedCategories = array_keys($categoriesCount);
349                $availableCategories = $this->getCategoriesList($organizationID);
350                $output = array();
351                $output['employees'] = $employees;
352                $output['categories'] = array();
353                foreach ($availableCategories as $category)
354                {
355                        if (!in_array($category['funcionario_categoria_id'], $usedCategories))
356                                continue;
357
358                        $category['contagem'] = $categoriesCount[$category['funcionario_categoria_id']];
359                        $output['categories'][] = $category;
360                }
361
362                usort($output['employees'], create_function('$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);'));
363
364                return $output;
365        }
366
367        /**
368         * Get employees from a specific category
369         * @param int $categoryID The category ID
370         * @param int $organizationID The organization ID
371         * @return array The list o employees of that category
372         * @access public
373         */
374        function getCategoryEmployees($categoryID, $organizationID)
375        {
376                $organizationID = (int) $organizationID;
377
378                /* load the employees from the area */
379                if ($categoryID == 0)
380                {
381                        $query = "SELECT f.funcionario_id, f.organizacao_id, a.area_id, a.sigla AS area FROM funcionario f, funcionario_status s, area a WHERE (f.funcionario_status_id = s.funcionario_status_id) AND (f.area_id = a.area_id) AND (f.funcionario_categoria_id IS NULL) AND (s.exibir = ?) AND (f.organizacao_id = ?)";
382                        $result = $this->db->query($query, array('S', $organizationID));
383                }
384                else
385                {
386                        $query = "SELECT f.funcionario_id, f.organizacao_id, a.area_id, a.sigla AS area FROM funcionario f, funcionario_status s, area a WHERE (f.funcionario_status_id = s.funcionario_status_id) AND (f.area_id = a.area_id) AND (f.funcionario_categoria_id = ?) AND (s.exibir = ?) AND (f.organizacao_id = ?)";
387                        $result = $this->db->query($query, array((int)$categoryID, 'S', $organizationID));
388                }
389
390                $employees = $result->GetArray(-1);
391                $cachedLDAP = Factory::newInstance('CachedLDAP');
392                $cachedLDAP->setOperationMode($cachedLDAP->OPERATION_MODE_NORMAL);
393                for ($i = 0; $i < count($employees); $i++)
394                {
395                        /* remove numeric fields */
396                        for ($j = 0; $j < $result->_numOfFields; $j++)
397                                unset($employees[$i][$j]);
398
399                        $employees[$i]['cn'] = '';
400                        $employees[$i]['telephoneNumber'] = '';
401
402                        /* try to find the telephone number */
403                        $entry = $cachedLDAP->getEntryByID($employees[$i]['funcionario_id']);
404                        if ($entry)
405                        {
406                                $employees[$i]['telephoneNumber'] = is_null($entry['telephonenumber']) ? '' : $entry['telephonenumber'];
407                                $employees[$i]['cn'] = is_null($entry['cn']) ? '' : $entry['cn'] . (is_null($entry['last_update']) ? ' <font color="red">(inativo)</font>' : '');
408                        }
409                }
410
411                $output = array('employees' => $employees);
412                return $output;
413        }
414
415        /**
416         * Search Employee by Name
417         * @param int $searchTerm term to search
418         * @param int $organizationID  Id of organization
419         * @return array employee data information
420         * @access public
421         */
422        function searchEmployeeByName($searchTerm, $organizationID)
423        {
424                /* get ldap connection */
425                $ldap = &Factory::getInstance('WorkflowObjects')->getLDAP();
426
427                $searchTermExploded = explode(" ", $searchTerm);
428                $fullSearch = false;
429
430                if (count($searchTermExploded) > 0){
431                        for ($i=1; $i<count($searchTermExploded); $i++) {
432                                if (strlen($searchTermExploded[$i]) > 2) {
433                                        $fullSearch = true;
434                                }
435                        }
436
437                        if ($fullSearch){
438                                $searchTerm = implode("*", $searchTermExploded);
439                        }
440                }
441
442                /* searching employees by name in the ldap server */
443                $list = @ldap_search($ldap, Factory::getInstance('WorkflowLDAP')->getLDAPContext(), ('(&(cn=*' . $searchTerm . '*)(phpgwaccounttype=u))'), array('uidNumber', 'cn', 'telephoneNumber'));
444                if ($list === false)
445                        return false;
446
447                /* parsing ldap result */
448                $entries = ldap_get_entries($ldap, $list);
449                $ldapResult = array();
450
451                for ($i = 0; $i < $entries['count']; $i++)
452                        $ldapResult[$entries[$i]['uidnumber'][0]] = array('cn' => $entries[$i]['cn'][0], 'telephoneNumber' => $entries[$i]['telephonenumber'][0]);
453
454                /* no records found. bye. */
455                if (count($ldapResult) == 0)
456                        return array();
457
458                $uids = implode( ',', array_keys( $ldapResult ) );
459
460                /* searching for aditional employee information */
461                $query  = "SELECT ";
462                $query .= "             f.funcionario_id AS funcionario_id, f.area_id AS area_id, a.sigla AS area ";
463                $query .= " FROM ";
464                $query .= "                     funcionario f ";
465                $query .= "             INNER JOIN ";
466                $query .= "                     area a USING (area_id) ";
467                $query .= "             INNER JOIN ";
468                $query .= "                     funcionario_status s ON ((f.funcionario_status_id = s.funcionario_status_id) AND (s.exibir = 'S')) ";
469                $query .= " WHERE ";
470                $query .= "             (f.organizacao_id = ?) ";
471                $query .= "     AND ";
472                $query .= "             (f.funcionario_id IN ({$uids})) ";
473
474                $result = $this->db->query($query, array($organizationID))->GetArray(-1);
475                $employees = array();
476
477                /* filling return array with employee's information */
478                for ($i = 0; $i < count($result); $i++) {
479                        $employees []= array(
480                                        'area'                          => $result[$i]['area'],
481                                        'area_id'                       => $result[$i]['area_id'],
482                                        'funcionario_id'        => $result[$i]['funcionario_id'],
483                                        'cn'                            => $ldapResult[$result[$i]['funcionario_id']]['cn'],
484                                        'telephoneNumber'       => empty($ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']) ? '': $ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']
485                        );
486                }
487
488                /* sorting by name (cn) */
489        $sort_function = create_function('$a, $b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);');
490        usort($employees, $sort_function );
491
492                return $employees;
493        }
494
495        /**
496         * Search Employee by Area
497         * @param int $searchTerm term to search
498         * @param int $organizationID  Id of organization
499         * @return array employee data information
500         * @access public
501         */
502        function searchEmployeeByArea($searchTerm, $organizationID)
503        {
504                /* get ldap connection */
505                $ldap = &Factory::getInstance('WorkflowObjects')->getLDAP();
506
507                /* makes no sense search for an area if the string has more than one word */
508                if (count(explode(" ", $searchTerm)) > 1)
509                        return array();
510
511                /* searching for employees in areas that match 'searchTerm' */
512                $query  = "SELECT ";
513                $query .= "             f.funcionario_id AS funcionario_id, f.area_id AS area_id, a.sigla AS area ";
514                $query .= " FROM ";
515                $query .= "                     funcionario f ";
516                $query .= "             INNER JOIN ";
517                $query .= "                     area a USING (area_id) ";
518                $query .= "             INNER JOIN ";
519                $query .= "                     funcionario_status s ON ((f.funcionario_status_id = s.funcionario_status_id) AND (s.exibir = 'S')) ";
520                $query .= " WHERE ";
521                $query .= "             (f.organizacao_id = ?) ";
522                $query .= "     AND ";
523                $query .= "             (UPPER(a.sigla) LIKE UPPER(?)) ";
524
525                $result = $this->db->query($query, array($organizationID, '%'.$searchTerm.'%'))->GetArray(-1);
526       
527                /* no records found. bye */
528                if (count($result) == 0)
529                        return array();
530
531                /* creating the ldap query */
532                $ldap_query = '(&(|';
533                for ($i = 0; $i < count($result); $i++) {
534                        $ldap_query .= '(uidNumber=' . $result[$i]['funcionario_id'] . ')';
535                }
536                $ldap_query .= ')(phpgwAccountType=u))';
537
538                /* executing it */
539                $list = @ldap_search($ldap, Factory::getInstance('WorkflowLDAP')->getLDAPContext(), $ldap_query, array('uidNumber', 'cn', 'telephoneNumber'));
540                $entries = ldap_get_entries($ldap, $list);
541
542                /* parsing result */
543                $ldapResult = array();
544                for ($i = 0; $i < $entries['count']; $i++)
545                        $ldapResult[$entries[$i]['uidnumber'][0]] = array('cn' => $entries[$i]['cn'][0], 'telephoneNumber' => $entries[$i]['telephonenumber'][0]);
546
547                /* we will need to search into database 'cache' for users deleted in ldap */
548                $cachedLDAP = Factory::newInstance( 'CachedLDAP' );
549                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_DATABASE );
550
551                /* filling return array with employee's information */
552                $employees = array();
553                for ($i = 0; $i < count($result); $i++) {
554
555                        $employee = array();
556
557                        /* user deleted in ldap. Let's try to find him into database 'cache' */
558                        if (empty($ldapResult[$result[$i]['funcionario_id']]['cn'])) {
559                                $entry = $cachedLDAP->getEntryByID($result[$i]['funcionario_id']);
560
561                                $employee['removed'] = is_null($entry['last_update']);
562
563                                if ($entry && !empty($entry['cn']))
564                                        $employee['cn'] = $entry['cn'];
565                                /* we cant find it anywhere */
566                                else
567                                        $employee['cn'] = $result[$i]['funcionario_id'];
568                        }
569                        else
570                                $employee['cn'] = $ldapResult[$result[$i]['funcionario_id']]['cn'];
571
572                        $employee['area']                               = $result[$i]['area'];
573                        $employee['area_id']                    = $result[$i]['area_id'];
574                        $employee['funcionario_id']     = $result[$i]['funcionario_id'];
575                        $employee['telephoneNumber']    = empty($ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']) ? '': $ldapResult[$result[$i]['funcionario_id']]['telephoneNumber'];
576
577                        $employees []= $employee;
578                }
579
580                /* sorting by name (cn) */
581        $sort_function = create_function('$a, $b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);');
582        usort($employees, $sort_function );
583
584                return $employees;
585        }
586
587        /**
588         * Search Employee by Telephone
589         * @param int $searchTerm term to search
590         * @param int $organizationID  Id of organization
591         * @return array employee data information
592         * @access public
593         */
594        function searchEmployeeByTelephone($searchTerm, $organizationID)
595        {
596                /* we will just excute it if we just get numbers and '-' */
597                if (!preg_match('/^[0-9-]+$/', $searchTerm))
598                        return array();
599
600                /* get ldap connection */
601                $ldap = &Factory::getInstance('WorkflowObjects')->getLDAP();
602
603                /* searching employees by telephoneNumber in the ldap server */
604                $list = @ldap_search($ldap, Factory::getInstance('WorkflowLDAP')->getLDAPContext(), ('(&(telephoneNumber=*' . $searchTerm . '*)(phpgwaccounttype=u))'), array('uidNumber', 'cn', 'telephoneNumber'));
605
606                if (!$list) return false;
607
608                /* parsing ldap result */
609                $entries = ldap_get_entries($ldap, $list);
610                $ldapResult = array();
611
612                for ($i = 0; $i < $entries['count']; $i++)
613                        $ldapResult[$entries[$i]['uidnumber'][0]] = array('cn' => $entries[$i]['cn'][0], 'telephoneNumber' => $entries[$i]['telephonenumber'][0]);
614
615                /* no records found. bye. */
616                if (count($ldapResult) == 0)
617                        return array();
618
619                $uids = implode( ',', array_keys( $ldapResult ) );
620
621                /* searching for aditional employee information */
622                $query  = "SELECT ";
623                $query .= "             f.funcionario_id AS funcionario_id, f.area_id AS area_id, a.sigla AS area ";
624                $query .= " FROM ";
625                $query .= "                     funcionario f ";
626                $query .= "             INNER JOIN ";
627                $query .= "                     area a USING (area_id) ";
628                $query .= "             INNER JOIN ";
629                $query .= "                     funcionario_status s ON ((f.funcionario_status_id = s.funcionario_status_id) AND (s.exibir = 'S')) ";
630                $query .= " WHERE ";
631                $query .= "             (f.organizacao_id = ?) ";
632                $query .= "     AND ";
633                $query .= "             (f.funcionario_id IN ({$uids})) ";
634
635                $result = $this->db->query($query, array($organizationID))->GetArray(-1);
636                $employees = array();
637
638                /* filling return array with employee's information */
639                for ($i = 0; $i < count($result); $i++) {
640                        $employees []= array(
641                                        'area'                          => $result[$i]['area'],
642                                        'area_id'                       => $result[$i]['area_id'],
643                                        'funcionario_id'        => $result[$i]['funcionario_id'],
644                                        'cn'                            => $ldapResult[$result[$i]['funcionario_id']]['cn'],
645                                        'telephoneNumber'       => empty($ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']) ? '': $ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']
646                        );
647                }
648
649                /* sorting by name (cn) */
650        $sort_function = create_function('$a, $b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);');
651        usort($employees, $sort_function );
652
653                return $employees;
654        }
655
656
657        /**
658         * Busca informações sobre um funcionário.
659         * @param array $params Uma array contendo o ID do funcionário cujas informações serão extraídas e de sua organização (Ajax).
660         * @param int $employeeID O ID do funcionário.
661         * @param int $organizationID O ID da organização.
662         * @return array Informações sobre o funcionário.
663         * @access public
664         */
665        function getEmployeeInfo($employeeID, $organizationID)
666        {
667                $SOOrgchart = &Factory::getInstance('so_orgchart');
668                $SOOrgchart->setExternalCalls(true);
669                $output = $SOOrgchart->getEmployeeInfo($employeeID, $organizationID);
670                $SOOrgchart->setExternalCalls(false);
671
672                return $output;
673        }
674
675        /**
676         * Busca informações sobre uma área.
677         * @param array $params Uma array contendo o ID da área cujas informações serão extraídas e de sua organização (Ajax).
678         * @param int $areaID O ID da área.
679         * @param int $organizationID O ID da organização.
680         * @return array Informações sobre a área.
681         * @access public
682         */
683        function getAreaInfo($areaID, $organizationID)
684        {
685                $SOOrgchart = &Factory::getInstance('so_orgchart');
686                $SOOrgchart->setExternalCalls(true);
687                $output = $SOOrgchart->getAreaInfo($areaID, $organizationID);
688                $SOOrgchart->setExternalCalls(false);
689
690                return $output;
691        }
692
693        /**
694         * Get useful phones list
695         * @param int $organizationID The organization ID
696         * @return array Useful phones list
697         * @access public
698         */
699        function getUsefulPhones( $organizationID )
700        {
701                $result = $this -> db -> query( "SELECT descricao, numero FROM telefone WHERE (organizacao_id = ?) ORDER BY descricao", array( $organizationID ) );
702
703                $output = $result->GetArray(-1);
704                for ($i = 0; $i < count($output); $i++)
705                        for ($j = 0; $j < $result->_numOfFields; $j++)
706                                unset($output[$i][$j]);
707
708                return $output;
709        }
710
711        /**
712         * Get areas with substitute boss
713         * @param int $organizationID The organization ID
714         * @return array areas with substitute boss
715         * @access public
716         */
717        function getAreaWithSubtituteBoss( $organizationID )
718        {
719                $result = $this -> db -> query( "SELECT a.sigla as area, a.titular_funcionario_id as titular, s.funcionario_id as substituto, s.data_inicio, s.data_fim FROM area a INNER JOIN substituicao s ON ((a.area_id = s.area_id) AND (CURRENT_DATE BETWEEN s.data_inicio AND s.data_fim)) WHERE (organizacao_id = ?) ORDER BY area", array( $organizationID ) );
720
721                $cachedLDAP = Factory::newInstance( 'CachedLDAP' );
722                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_LDAP_DATABASE );
723
724                $output = $result->GetArray(-1);
725                for ( $i = 0; $i < count($output); $i++ )
726                {
727                        for ($j = 0; $j < $result->_numOfFields; $j++)
728                                unset($output[$i][$j]);
729
730                        $entry = $cachedLDAP -> getEntryByID( $output[ $i ][ 'titular' ] );
731                        if ( $entry && ( ! is_null( $entry[ 'cn' ] ) ) )
732                                $output[ $i ][ 'titular' ] = $entry[ 'cn' ];
733
734                        $entry = $cachedLDAP -> getEntryByID( $output[ $i ][ 'substituto' ] );
735                        if ( $entry && ( ! is_null( $entry[ 'cn' ] ) ) )
736                                $output[ $i ][ 'substituto' ] = $entry[ 'cn' ];
737
738                        $output[$i]['data_inicio'] = implode('/', array_reverse(explode('-', $output[$i]['data_inicio'])));
739                        $output[$i]['data_fim'] = implode('/', array_reverse(explode('-', $output[$i]['data_fim'])));
740                }
741
742                return $output;
743        }
744
745        /**
746         * Get manning list
747         * @param int $organizationID The organization ID
748         * @return array The manning list
749         * @access public
750         */
751        function getManning( $organizationID )
752        {
753                $result = $this -> db -> query( 'SELECT localidade_id, descricao FROM localidade WHERE (organizacao_id = ?) ORDER BY descricao', array( $organizationID ) );
754
755                $output = $result->GetArray( -1 );
756                for ( $i = 0; $i < count($output); $i++ )
757                        for ($j = 0; $j < $result->_numOfFields; $j++)
758                                unset($output[$i][$j]);
759
760                return $output;
761        }
762
763        /**
764         * Get employees from a specific location
765         * @param int $categoryID The category ID
766         * @param int $organizationID The organization ID
767         * @return array The list o employees of that location
768         * @access public
769         */
770        function getManningEmployees( $locationID, $organizationID )
771        {
772                $organizationID = ( int ) $organizationID;
773                $locationID = ( int ) $locationID;
774
775                // load the employees from the location
776                $query = "SELECT f.funcionario_id, f.organizacao_id, f.area_id, a.sigla AS area,"
777                        . " COALESCE(f.funcionario_categoria_id, 0) AS funcionario_categoria_id"
778                        . " FROM funcionario f, funcionario_status s, area a"
779                        . " WHERE (f.area_id = a.area_id)"
780                        . " AND (f.funcionario_status_id = s.funcionario_status_id)"
781                        . " AND (f.organizacao_id = ?)"
782                        . " AND (f.localidade_id = ?)"
783                        . " AND (s.exibir = ?)";
784
785                $result = $this -> db -> query( $query, array( $organizationID, $locationID, 'S' ) );
786
787                $employees = $result -> GetArray( -1 );
788                $cachedLDAP = Factory::newInstance( 'CachedLDAP' );
789                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_NORMAL );
790
791                $categoriesCount = array( );
792                for ( $i = 0; $i < count( $employees ); $i++ )
793                {
794                        // remove numeric fields
795                        for ( $j = 0; $j < $result -> _numOfFields; $j++ )
796                                unset( $employees[ $i ][ $j ] );
797
798                        $employees[ $i ][ 'cn' ] = '';
799                        $employees[ $i ][ 'telephoneNumber' ] = '';
800
801                        // try to find the telephone number
802                        $entry = $cachedLDAP -> getEntryByID( $employees[ $i ][ 'funcionario_id' ] );
803                        if ( $entry )
804                        {
805                                $employees[ $i ][ 'telephoneNumber' ] = is_null( $entry[ 'telephonenumber' ] ) ? '' : $entry[ 'telephonenumber' ];
806                                $employees[ $i ][ 'cn' ] = is_null( $entry[ 'cn' ] ) ? '' : $entry[ 'cn' ];
807                                $employees[ $i ][ 'removed' ] = is_null( $entry[ 'last_update' ] );
808                        }
809
810                        // count the number of employees in each category
811                        $categoryID = $employees[ $i ][ 'funcionario_categoria_id' ];
812                        if ( isset( $categoriesCount[ $categoryID ] ) )
813                                $categoriesCount[ $categoryID ]++;
814                        else
815                                $categoriesCount[ $categoryID ] = 1;
816                }
817
818                $usedCategories = array_keys( $categoriesCount );
819                $availableCategories = $this -> getCategoriesList( $organizationID );
820                $output = array( );
821                $output[ 'employees' ] = $employees;
822                $output[ 'categories' ] = array( );
823                foreach ( $availableCategories as $category )
824                {
825                        if ( ! in_array( $category[ 'funcionario_categoria_id' ], $usedCategories ) )
826                                continue;
827
828                        $category[ 'contagem' ] = $categoriesCount[ $category[ 'funcionario_categoria_id' ] ];
829                        $output[ 'categories' ][ ] = $category;
830                }
831
832                usort( $output[ 'employees' ], create_function( '$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);' ) );
833
834                return $output;
835        }
836
837        /**
838         * Return the list of employees in alphabetical order
839         * @param int $organizationID The organization ID
840         * @return array The list o employees
841         * @access public
842         */
843        function getAlphabeticalEmployees( $organizationID )
844        {
845                $organizationID = ( int ) $organizationID;
846
847                // load the employees from the location
848                $query = "SELECT f.funcionario_id, f.organizacao_id, f.area_id, a.sigla AS area,"
849                        . " COALESCE(f.funcionario_categoria_id, 0) AS funcionario_categoria_id"
850                        . " FROM funcionario f, funcionario_status s, area a"
851                        . " WHERE (f.area_id = a.area_id)"
852                        . " AND (f.funcionario_status_id = s.funcionario_status_id)"
853                        . " AND (f.organizacao_id = ?)"
854                        . " AND (s.exibir = ?)";
855
856                $result = $this -> db -> query( $query, array( $organizationID, 'S' ) );
857
858                $employees = $result -> GetArray( -1 );
859
860                $cachedLDAP = Factory::newInstance( 'CachedLDAP' );
861                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_NORMAL );
862
863                $categoriesCount = array( );
864                for ( $i = 0; $i < count( $employees ); $i++ )
865                {
866                        // remove numeric fields
867                        for ( $j = 0; $j < $result -> _numOfFields; $j++ )
868                                unset( $employees[ $i ][ $j ] );
869
870                        $employees[ $i ][ 'cn' ] = '';
871                        $employees[ $i ][ 'telephoneNumber' ] = '';
872
873                        // try to find the telephone number
874                        $entry = $cachedLDAP -> getEntryByID( $employees[ $i ][ 'funcionario_id' ] );
875                        if ( $entry )
876                        {
877                                $employees[ $i ][ 'telephoneNumber' ] = is_null( $entry[ 'telephonenumber' ] ) ? '' : $entry[ 'telephonenumber' ];
878                                $employees[ $i ][ 'cn' ] = is_null( $entry[ 'cn' ] ) ? '' : $entry[ 'cn' ];
879                                $employees[ $i ][ 'removed' ] = is_null( $entry[ 'last_update' ] );
880                        }
881
882                }
883
884                usort( $employees, create_function( '$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);' ) );
885
886                $paging = Factory::newInstance('Paging', 50, $_POST);
887                $employees = $paging->restrictItems( $employees );
888
889                // count the number of employees in each category
890                for ( $i = 0; $i < count( $employees ); $i++ )
891                {
892                        $categoryID = $employees[ $i ][ 'funcionario_categoria_id' ];
893                        if ( isset( $categoriesCount[ $categoryID ] ) )
894                                $categoriesCount[ $categoryID ]++;
895                        else
896                                $categoriesCount[ $categoryID ] = 1;
897                }
898
899                $usedCategories = array_keys( $categoriesCount );
900                $availableCategories = $this -> getCategoriesList( $organizationID );
901                $output = array( );
902
903                $output['employees'] = $employees;
904                $output['categories'] = array( );
905                $output['paging_links'] = $paging -> commonLinks();
906
907                foreach ( $availableCategories as $category )
908                {
909                        if ( ! in_array( $category[ 'funcionario_categoria_id' ], $usedCategories ) )
910                                continue;
911
912                        $category[ 'contagem' ] = $categoriesCount[ $category[ 'funcionario_categoria_id' ] ];
913                        $output[ 'categories' ][ ] = $category;
914                }
915
916                return $output;
917        }
918}
919?>
Note: See TracBrowser for help on using the repository browser.