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

Revision 6535, 31.8 KB checked in by leticiabohnert, 12 years ago (diff)

Ticket #2851 - Inclusão da função, data de admissão e apelido no organograma.

  • 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, f.funcao, to_char(f.data_admissao,'DD/MM/YYYY') as data_admissao, 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                        if (!$this->authorized || !isset($employees[$i]['funcao']))
304                                $employees[$i]['funcao'] = '';
305                        else
306                                $employees[$i]['funcao'] = utf8_encode($employees[$i]['funcao']);       
307                        if (!$this->authorized || !isset($employees[$i]['data_admissao']))
308                                $employees[$i]['data_admissao'] = '';
309                        $employees[$i]['cn'] = '';
310                        $employees[$i]['telephoneNumber'] = '';
311                        if (in_array($employees[$i]['funcionario_id'], $areaInfo))
312                                $employees[$i]['chief'] = ($employees[$i]['funcionario_id'] == $areaInfo['titular_funcionario_id']) ? 1 : 2;
313
314                        /* try to find the telephone number */
315                        $entry = $cachedLDAP->getEntryByID($employees[$i]['funcionario_id']);
316                        if ($entry)
317                        {
318                                $employees[$i]['telephoneNumber'] = is_null($entry['telephonenumber']) ? '' : $entry['telephonenumber'];
319                                $employees[$i]['cn'] = is_null($entry['cn']) ? '' : $entry['cn'];
320                                $employees[$i]['uid'] = is_null($entry['uid']) ? '' : $entry['uid'];
321                                $employees[$i]['uidnumber'] = is_null($entry['uidnumber']) ? '' : $entry['uidnumber'];
322                                $employees[$i]['removed'] = is_null($entry['last_update']);
323                        }
324                       
325                        /*busca o cargo do funcionario*/
326                        $employeeInfo = $orgchart->getEmployee($employees[$i]['funcionario_id']);
327
328                        $cargo = '';
329
330                        if ($this->authorized && !empty($employeeInfo['cargo_id']))
331                        {
332                                $jobTitleInfo = $orgchart->getJobTitle($employeeInfo['cargo_id']);
333                                $cargo = $jobTitleInfo['descricao'];
334                        }
335                        $employees[$i]['cargo'] = utf8_encode($cargo); 
336                       
337                        /*busca o vínculo do funcionario*/
338                        $vinculo = '';
339                        if ($this->authorized && !empty($employeeInfo['funcionario_categoria_id']))
340                        {
341                                $categoryInfo = $orgchart->getEmployeeCategory($employeeInfo['funcionario_categoria_id']);
342                                $vinculo=$categoryInfo['descricao'];
343                        }                       
344                        $employees[$i]['vinculo'] = utf8_encode($vinculo);
345
346                        /* count the number of employees in each category */
347                        $categoryID = $employees[$i]['funcionario_categoria_id'];
348                        if (isset($categoriesCount[$categoryID]))
349                                $categoriesCount[$categoryID]++;
350                        else
351                                $categoriesCount[$categoryID] = 1;                                     
352                }
353                $usedCategories = array_keys($categoriesCount);
354                $availableCategories = $this->getCategoriesList($organizationID);
355                $output = array();
356                $output['employees'] = $employees;
357                $output['categories'] = array();
358                foreach ($availableCategories as $category)
359                {
360                        if (!in_array($category['funcionario_categoria_id'], $usedCategories))
361                                continue;
362
363                        $category['contagem'] = $categoriesCount[$category['funcionario_categoria_id']];
364                        $output['categories'][] = $category;
365                }
366
367                usort($output['employees'], create_function('$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);'));
368
369                return $output;
370        }
371
372        /**
373         * Get employees from a specific category
374         * @param int $categoryID The category ID
375         * @param int $organizationID The organization ID
376         * @return array The list o employees of that category
377         * @access public
378         */
379        function getCategoryEmployees($categoryID, $organizationID)
380        {
381                $organizationID = (int) $organizationID;
382
383                /* load the employees from the area */
384                if ($categoryID == 0)
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 IS NULL) AND (s.exibir = ?) AND (f.organizacao_id = ?)";
387                        $result = $this->db->query($query, array('S', $organizationID));
388                }
389                else
390                {
391                        $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 = ?)";
392                        $result = $this->db->query($query, array((int)$categoryID, 'S', $organizationID));
393                }
394
395                $employees = $result->GetArray(-1);
396                $cachedLDAP = Factory::newInstance('CachedLDAP');
397                $cachedLDAP->setOperationMode($cachedLDAP->OPERATION_MODE_NORMAL);
398                for ($i = 0; $i < count($employees); $i++)
399                {
400                        /* remove numeric fields */
401                        for ($j = 0; $j < $result->_numOfFields; $j++)
402                                unset($employees[$i][$j]);
403
404                        $employees[$i]['cn'] = '';
405                        $employees[$i]['telephoneNumber'] = '';
406
407                        /* try to find the telephone number */
408                        $entry = $cachedLDAP->getEntryByID($employees[$i]['funcionario_id']);
409                        if ($entry)
410                        {
411                                $employees[$i]['telephoneNumber'] = is_null($entry['telephonenumber']) ? '' : $entry['telephonenumber'];
412                                $employees[$i]['cn'] = is_null($entry['cn']) ? '' : $entry['cn'] . (is_null($entry['last_update']) ? ' <font color="red">(inativo)</font>' : '');
413                        }
414                }
415
416                $output = array('employees' => $employees);
417                return $output;
418        }
419
420        /**
421         * Search Employee by Name
422         * @param int $searchTerm term to search
423         * @param int $organizationID  Id of organization
424         * @return array employee data information
425         * @access public
426         */
427        function searchEmployeeByName($searchTerm, $organizationID)
428        {
429                /* get ldap connection */
430                $ldap = &Factory::getInstance('WorkflowObjects')->getLDAP();
431
432                $searchTermExploded = explode(" ", $searchTerm);
433                $fullSearch = false;
434
435                if (count($searchTermExploded) > 0){
436                        for ($i=1; $i<count($searchTermExploded); $i++) {
437                                if (strlen($searchTermExploded[$i]) > 2) {
438                                        $fullSearch = true;
439                                }
440                        }
441
442                        if ($fullSearch){
443                                $searchTerm = implode("*", $searchTermExploded);
444                        }
445                }
446
447                /* searching employees by name in the ldap server */
448                $list = @ldap_search($ldap, Factory::getInstance('WorkflowLDAP')->getLDAPContext(), ('(&(cn=*' . $searchTerm . '*)(phpgwaccounttype=u))'), array('uidNumber', 'cn', 'telephoneNumber'));
449                if ($list === false)
450                        return false;
451
452                /* parsing ldap result */
453                $entries = ldap_get_entries($ldap, $list);
454                $ldapResult = array();
455
456                for ($i = 0; $i < $entries['count']; $i++)
457                        $ldapResult[$entries[$i]['uidnumber'][0]] = array('cn' => $entries[$i]['cn'][0], 'telephoneNumber' => $entries[$i]['telephonenumber'][0]);
458
459                /* no records found. bye. */
460                if (count($ldapResult) == 0)
461                        return array();
462
463                $uids = implode( ',', array_keys( $ldapResult ) );
464
465                /* searching for aditional employee information */
466                $query  = "SELECT ";
467                $query .= "             f.funcionario_id AS funcionario_id, f.area_id AS area_id, a.sigla AS area ";
468                $query .= " FROM ";
469                $query .= "                     funcionario f ";
470                $query .= "             INNER JOIN ";
471                $query .= "                     area a USING (area_id) ";
472                $query .= "             INNER JOIN ";
473                $query .= "                     funcionario_status s ON ((f.funcionario_status_id = s.funcionario_status_id) AND (s.exibir = 'S')) ";
474                $query .= " WHERE ";
475                $query .= "             (f.organizacao_id = ?) ";
476                $query .= "     AND ";
477                $query .= "             (f.funcionario_id IN ({$uids})) ";
478
479                $result = $this->db->query($query, array($organizationID))->GetArray(-1);
480                $employees = array();
481
482                /* filling return array with employee's information */
483                for ($i = 0; $i < count($result); $i++) {
484                        $employees []= array(
485                                        'area'                          => $result[$i]['area'],
486                                        'area_id'                       => $result[$i]['area_id'],
487                                        'funcionario_id'        => $result[$i]['funcionario_id'],
488                                        'cn'                            => $ldapResult[$result[$i]['funcionario_id']]['cn'],
489                                        'telephoneNumber'       => empty($ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']) ? '': $ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']
490                        );
491                }
492
493                /* sorting by name (cn) */
494        $sort_function = create_function('$a, $b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);');
495        usort($employees, $sort_function );
496
497                return $employees;
498        }
499
500        /**
501         * Search Employee by Area
502         * @param int $searchTerm term to search
503         * @param int $organizationID  Id of organization
504         * @return array employee data information
505         * @access public
506         */
507        function searchEmployeeByArea($searchTerm, $organizationID)
508        {
509                /* get ldap connection */
510                $ldap = &Factory::getInstance('WorkflowObjects')->getLDAP();
511
512                /* makes no sense search for an area if the string has more than one word */
513                if (count(explode(" ", $searchTerm)) > 1)
514                        return array();
515
516                /* searching for employees in areas that match 'searchTerm' */
517                $query  = "SELECT ";
518                $query .= "             f.funcionario_id AS funcionario_id, f.area_id AS area_id, a.sigla AS area ";
519                $query .= " FROM ";
520                $query .= "                     funcionario f ";
521                $query .= "             INNER JOIN ";
522                $query .= "                     area a USING (area_id) ";
523                $query .= "             INNER JOIN ";
524                $query .= "                     funcionario_status s ON ((f.funcionario_status_id = s.funcionario_status_id) AND (s.exibir = 'S')) ";
525                $query .= " WHERE ";
526                $query .= "             (f.organizacao_id = ?) ";
527                $query .= "     AND ";
528                $query .= "             (UPPER(a.sigla) LIKE UPPER(?)) ";
529
530                $result = $this->db->query($query, array($organizationID, '%'.$searchTerm.'%'))->GetArray(-1);
531       
532                /* no records found. bye */
533                if (count($result) == 0)
534                        return array();
535
536                /* creating the ldap query */
537                $ldap_query = '(&(|';
538                for ($i = 0; $i < count($result); $i++) {
539                        $ldap_query .= '(uidNumber=' . $result[$i]['funcionario_id'] . ')';
540                }
541                $ldap_query .= ')(phpgwAccountType=u))';
542
543                /* executing it */
544                $list = @ldap_search($ldap, Factory::getInstance('WorkflowLDAP')->getLDAPContext(), $ldap_query, array('uidNumber', 'cn', 'telephoneNumber'));
545                $entries = ldap_get_entries($ldap, $list);
546
547                /* parsing result */
548                $ldapResult = array();
549                for ($i = 0; $i < $entries['count']; $i++)
550                        $ldapResult[$entries[$i]['uidnumber'][0]] = array('cn' => $entries[$i]['cn'][0], 'telephoneNumber' => $entries[$i]['telephonenumber'][0]);
551
552                /* we will need to search into database 'cache' for users deleted in ldap */
553                $cachedLDAP = Factory::newInstance( 'CachedLDAP' );
554                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_DATABASE );
555
556                /* filling return array with employee's information */
557                $employees = array();
558                for ($i = 0; $i < count($result); $i++) {
559
560                        $employee = array();
561
562                        /* user deleted in ldap. Let's try to find him into database 'cache' */
563                        if (empty($ldapResult[$result[$i]['funcionario_id']]['cn'])) {
564                                $entry = $cachedLDAP->getEntryByID($result[$i]['funcionario_id']);
565
566                                $employee['removed'] = is_null($entry['last_update']);
567
568                                if ($entry && !empty($entry['cn']))
569                                        $employee['cn'] = $entry['cn'];
570                                /* we cant find it anywhere */
571                                else
572                                        $employee['cn'] = $result[$i]['funcionario_id'];
573                        }
574                        else
575                                $employee['cn'] = $ldapResult[$result[$i]['funcionario_id']]['cn'];
576
577                        $employee['area']                               = $result[$i]['area'];
578                        $employee['area_id']                    = $result[$i]['area_id'];
579                        $employee['funcionario_id']     = $result[$i]['funcionario_id'];
580                        $employee['telephoneNumber']    = empty($ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']) ? '': $ldapResult[$result[$i]['funcionario_id']]['telephoneNumber'];
581
582                        $employees []= $employee;
583                }
584
585                /* sorting by name (cn) */
586        $sort_function = create_function('$a, $b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);');
587        usort($employees, $sort_function );
588
589                return $employees;
590        }
591
592        /**
593         * Search Employee by Telephone
594         * @param int $searchTerm term to search
595         * @param int $organizationID  Id of organization
596         * @return array employee data information
597         * @access public
598         */
599        function searchEmployeeByTelephone($searchTerm, $organizationID)
600        {
601                /* we will just excute it if we just get numbers and '-' */
602                if (!preg_match('/^[0-9-]+$/', $searchTerm))
603                        return array();
604
605                /* get ldap connection */
606                $ldap = &Factory::getInstance('WorkflowObjects')->getLDAP();
607
608                /* searching employees by telephoneNumber in the ldap server */
609                $list = @ldap_search($ldap, Factory::getInstance('WorkflowLDAP')->getLDAPContext(), ('(&(telephoneNumber=*' . $searchTerm . '*)(phpgwaccounttype=u))'), array('uidNumber', 'cn', 'telephoneNumber'));
610
611                if (!$list) return false;
612
613                /* parsing ldap result */
614                $entries = ldap_get_entries($ldap, $list);
615                $ldapResult = array();
616
617                for ($i = 0; $i < $entries['count']; $i++)
618                        $ldapResult[$entries[$i]['uidnumber'][0]] = array('cn' => $entries[$i]['cn'][0], 'telephoneNumber' => $entries[$i]['telephonenumber'][0]);
619
620                /* no records found. bye. */
621                if (count($ldapResult) == 0)
622                        return array();
623
624                $uids = implode( ',', array_keys( $ldapResult ) );
625
626                /* searching for aditional employee information */
627                $query  = "SELECT ";
628                $query .= "             f.funcionario_id AS funcionario_id, f.area_id AS area_id, a.sigla AS area ";
629                $query .= " FROM ";
630                $query .= "                     funcionario f ";
631                $query .= "             INNER JOIN ";
632                $query .= "                     area a USING (area_id) ";
633                $query .= "             INNER JOIN ";
634                $query .= "                     funcionario_status s ON ((f.funcionario_status_id = s.funcionario_status_id) AND (s.exibir = 'S')) ";
635                $query .= " WHERE ";
636                $query .= "             (f.organizacao_id = ?) ";
637                $query .= "     AND ";
638                $query .= "             (f.funcionario_id IN ({$uids})) ";
639
640                $result = $this->db->query($query, array($organizationID))->GetArray(-1);
641                $employees = array();
642
643                /* filling return array with employee's information */
644                for ($i = 0; $i < count($result); $i++) {
645                        $employees []= array(
646                                        'area'                          => $result[$i]['area'],
647                                        'area_id'                       => $result[$i]['area_id'],
648                                        'funcionario_id'        => $result[$i]['funcionario_id'],
649                                        'cn'                            => $ldapResult[$result[$i]['funcionario_id']]['cn'],
650                                        'telephoneNumber'       => empty($ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']) ? '': $ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']
651                        );
652                }
653
654                /* sorting by name (cn) */
655        $sort_function = create_function('$a, $b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);');
656        usort($employees, $sort_function );
657
658                return $employees;
659        }
660
661
662        /**
663         * Busca informações sobre um funcionário.
664         * @param array $params Uma array contendo o ID do funcionário cujas informações serão extraídas e de sua organização (Ajax).
665         * @param int $employeeID O ID do funcionário.
666         * @param int $organizationID O ID da organização.
667         * @return array Informações sobre o funcionário.
668         * @access public
669         */
670        function getEmployeeInfo($employeeID, $organizationID)
671        {
672                $SOOrgchart = &Factory::getInstance('so_orgchart');
673                $SOOrgchart->setExternalCalls(true);
674                $output = $SOOrgchart->getEmployeeInfo($employeeID, $organizationID);
675                $SOOrgchart->setExternalCalls(false);
676
677                return $output;
678        }
679
680        /**
681         * Busca informações sobre uma área.
682         * @param array $params Uma array contendo o ID da área cujas informações serão extraídas e de sua organização (Ajax).
683         * @param int $areaID O ID da área.
684         * @param int $organizationID O ID da organização.
685         * @return array Informações sobre a área.
686         * @access public
687         */
688        function getAreaInfo($areaID, $organizationID)
689        {
690                $SOOrgchart = &Factory::getInstance('so_orgchart');
691                $SOOrgchart->setExternalCalls(true);
692                $output = $SOOrgchart->getAreaInfo($areaID, $organizationID);
693                $SOOrgchart->setExternalCalls(false);
694
695                return $output;
696        }
697
698        /**
699         * Get useful phones list
700         * @param int $organizationID The organization ID
701         * @return array Useful phones list
702         * @access public
703         */
704        function getUsefulPhones( $organizationID )
705        {
706                $result = $this -> db -> query( "SELECT descricao, numero FROM telefone WHERE (organizacao_id = ?) ORDER BY descricao", array( $organizationID ) );
707
708                $output = $result->GetArray(-1);
709                for ($i = 0; $i < count($output); $i++)
710                        for ($j = 0; $j < $result->_numOfFields; $j++)
711                                unset($output[$i][$j]);
712
713                return $output;
714        }
715
716        /**
717         * Get areas with substitute boss
718         * @param int $organizationID The organization ID
719         * @return array areas with substitute boss
720         * @access public
721         */
722        function getAreaWithSubtituteBoss( $organizationID )
723        {
724                $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 ) );
725
726                $cachedLDAP = Factory::newInstance( 'CachedLDAP' );
727                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_LDAP_DATABASE );
728
729                $output = $result->GetArray(-1);
730                for ( $i = 0; $i < count($output); $i++ )
731                {
732                        for ($j = 0; $j < $result->_numOfFields; $j++)
733                                unset($output[$i][$j]);
734
735                        $entry = $cachedLDAP -> getEntryByID( $output[ $i ][ 'titular' ] );
736                        if ( $entry && ( ! is_null( $entry[ 'cn' ] ) ) )
737                                $output[ $i ][ 'titular' ] = $entry[ 'cn' ];
738
739                        $entry = $cachedLDAP -> getEntryByID( $output[ $i ][ 'substituto' ] );
740                        if ( $entry && ( ! is_null( $entry[ 'cn' ] ) ) )
741                                $output[ $i ][ 'substituto' ] = $entry[ 'cn' ];
742
743                        $output[$i]['data_inicio'] = implode('/', array_reverse(explode('-', $output[$i]['data_inicio'])));
744                        $output[$i]['data_fim'] = implode('/', array_reverse(explode('-', $output[$i]['data_fim'])));
745                }
746
747                return $output;
748        }
749
750        /**
751         * Get manning list
752         * @param int $organizationID The organization ID
753         * @return array The manning list
754         * @access public
755         */
756        function getManning( $organizationID )
757        {
758                $result = $this -> db -> query( 'SELECT localidade_id, descricao FROM localidade WHERE (organizacao_id = ?) ORDER BY descricao', array( $organizationID ) );
759
760                $output = $result->GetArray( -1 );
761                for ( $i = 0; $i < count($output); $i++ )
762                        for ($j = 0; $j < $result->_numOfFields; $j++)
763                                unset($output[$i][$j]);
764
765                return $output;
766        }
767
768        /**
769         * Get employees from a specific location
770         * @param int $categoryID The category ID
771         * @param int $organizationID The organization ID
772         * @return array The list o employees of that location
773         * @access public
774         */
775        function getManningEmployees( $locationID, $organizationID )
776        {
777                $organizationID = ( int ) $organizationID;
778                $locationID = ( int ) $locationID;
779
780                // load the employees from the location
781                $query = "SELECT f.funcionario_id, f.organizacao_id, f.area_id, a.sigla AS area,"
782                        . " COALESCE(f.funcionario_categoria_id, 0) AS funcionario_categoria_id"
783                        . " FROM funcionario f, funcionario_status s, area a"
784                        . " WHERE (f.area_id = a.area_id)"
785                        . " AND (f.funcionario_status_id = s.funcionario_status_id)"
786                        . " AND (f.organizacao_id = ?)"
787                        . " AND (f.localidade_id = ?)"
788                        . " AND (s.exibir = ?)";
789
790                $result = $this -> db -> query( $query, array( $organizationID, $locationID, 'S' ) );
791
792                $employees = $result -> GetArray( -1 );
793                $cachedLDAP = Factory::newInstance( 'CachedLDAP' );
794                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_NORMAL );
795
796                $categoriesCount = array( );
797                for ( $i = 0; $i < count( $employees ); $i++ )
798                {
799                        // remove numeric fields
800                        for ( $j = 0; $j < $result -> _numOfFields; $j++ )
801                                unset( $employees[ $i ][ $j ] );
802
803                        $employees[ $i ][ 'cn' ] = '';
804                        $employees[ $i ][ 'telephoneNumber' ] = '';
805
806                        // try to find the telephone number
807                        $entry = $cachedLDAP -> getEntryByID( $employees[ $i ][ 'funcionario_id' ] );
808                        if ( $entry )
809                        {
810                                $employees[ $i ][ 'telephoneNumber' ] = is_null( $entry[ 'telephonenumber' ] ) ? '' : $entry[ 'telephonenumber' ];
811                                $employees[ $i ][ 'cn' ] = is_null( $entry[ 'cn' ] ) ? '' : $entry[ 'cn' ];
812                                $employees[ $i ][ 'removed' ] = is_null( $entry[ 'last_update' ] );
813                        }
814
815                        // count the number of employees in each category
816                        $categoryID = $employees[ $i ][ 'funcionario_categoria_id' ];
817                        if ( isset( $categoriesCount[ $categoryID ] ) )
818                                $categoriesCount[ $categoryID ]++;
819                        else
820                                $categoriesCount[ $categoryID ] = 1;
821                }
822
823                $usedCategories = array_keys( $categoriesCount );
824                $availableCategories = $this -> getCategoriesList( $organizationID );
825                $output = array( );
826                $output[ 'employees' ] = $employees;
827                $output[ 'categories' ] = array( );
828                foreach ( $availableCategories as $category )
829                {
830                        if ( ! in_array( $category[ 'funcionario_categoria_id' ], $usedCategories ) )
831                                continue;
832
833                        $category[ 'contagem' ] = $categoriesCount[ $category[ 'funcionario_categoria_id' ] ];
834                        $output[ 'categories' ][ ] = $category;
835                }
836
837                usort( $output[ 'employees' ], create_function( '$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);' ) );
838
839                return $output;
840        }
841
842        /**
843         * Return the list of employees in alphabetical order
844         * @param int $organizationID The organization ID
845         * @return array The list o employees
846         * @access public
847         */
848        function getAlphabeticalEmployees( $organizationID )
849        {
850                $organizationID = ( int ) $organizationID;
851
852                // load the employees from the location
853                $query = "SELECT f.funcionario_id, f.organizacao_id, f.area_id, a.sigla AS area,"
854                        . " COALESCE(f.funcionario_categoria_id, 0) AS funcionario_categoria_id"
855                        . " FROM funcionario f, funcionario_status s, area a"
856                        . " WHERE (f.area_id = a.area_id)"
857                        . " AND (f.funcionario_status_id = s.funcionario_status_id)"
858                        . " AND (f.organizacao_id = ?)"
859                        . " AND (s.exibir = ?)";
860
861                $result = $this -> db -> query( $query, array( $organizationID, 'S' ) );
862
863                $employees = $result -> GetArray( -1 );
864
865                $cachedLDAP = Factory::newInstance( 'CachedLDAP' );
866                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_NORMAL );
867
868                $categoriesCount = array( );
869                for ( $i = 0; $i < count( $employees ); $i++ )
870                {
871                        // remove numeric fields
872                        for ( $j = 0; $j < $result -> _numOfFields; $j++ )
873                                unset( $employees[ $i ][ $j ] );
874
875                        $employees[ $i ][ 'cn' ] = '';
876                        $employees[ $i ][ 'telephoneNumber' ] = '';
877
878                        // try to find the telephone number
879                        $entry = $cachedLDAP -> getEntryByID( $employees[ $i ][ 'funcionario_id' ] );
880                        if ( $entry )
881                        {
882                                $employees[ $i ][ 'telephoneNumber' ] = is_null( $entry[ 'telephonenumber' ] ) ? '' : $entry[ 'telephonenumber' ];
883                                $employees[ $i ][ 'cn' ] = is_null( $entry[ 'cn' ] ) ? '' : $entry[ 'cn' ];
884                                $employees[ $i ][ 'removed' ] = is_null( $entry[ 'last_update' ] );
885                        }
886
887                }
888
889                usort( $employees, create_function( '$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);' ) );
890
891                $paging = Factory::newInstance('Paging', 50, $_POST);
892                $employees = $paging->restrictItems( $employees );
893
894                // count the number of employees in each category
895                for ( $i = 0; $i < count( $employees ); $i++ )
896                {
897                        $categoryID = $employees[ $i ][ 'funcionario_categoria_id' ];
898                        if ( isset( $categoriesCount[ $categoryID ] ) )
899                                $categoriesCount[ $categoryID ]++;
900                        else
901                                $categoriesCount[ $categoryID ] = 1;
902                }
903
904                $usedCategories = array_keys( $categoriesCount );
905                $availableCategories = $this -> getCategoriesList( $organizationID );
906                $output = array( );
907
908                $output['employees'] = $employees;
909                $output['categories'] = array( );
910                $output['paging_links'] = $paging -> commonLinks();
911
912                foreach ( $availableCategories as $category )
913                {
914                        if ( ! in_array( $category[ 'funcionario_categoria_id' ], $usedCategories ) )
915                                continue;
916
917                        $category[ 'contagem' ] = $categoriesCount[ $category[ 'funcionario_categoria_id' ] ];
918                        $output[ 'categories' ][ ] = $category;
919                }
920
921                return $output;
922        }
923}
924?>
Note: See TracBrowser for help on using the repository browser.