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

Revision 2094, 29.7 KB checked in by pedroerp, 14 years ago (diff)

Ticket #928 - Utilizando CachedLDAP para encontrar usuários excluídos na busca do organograma.

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