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

Revision 2085, 29.1 KB checked in by pedroerp, 14 years ago (diff)

Ticket #928 - Adicionando suporte a buscas por telefone no 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                /* filling return array with employee's information */
477                $employees = array();
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'                            => empty($ldapResult[$result[$i]['funcionario_id']]['cn']) ? $result[$i]['funcionario_id'] : $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 Telephone
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 searchEmployeeByTelephone($searchTerm, $organizationID)
503        {
504                /* we will just excute it if we just get numbers and '-' */
505                if (!preg_match('/^[0-9-]+$/', $searchTerm))
506                        return array();
507
508                /* get ldap connection */
509                $ldap = &$GLOBALS['workflow']['workflowObjects']->getLDAP();
510
511                /* searching employees by telephoneNumber in the ldap server */
512                $list = @ldap_search($ldap, $GLOBALS['workflow']['factory']->getInstance('WorkflowLDAP')->getLDAPContext(), ('(&(telephoneNumber=*' . $searchTerm . '*)(phpgwaccounttype=u))'), array('uidNumber', 'cn', 'telephoneNumber'));
513
514                if (!$list) return false;
515
516                /* parsing ldap result */
517                $entries = ldap_get_entries($ldap, $list);
518                $ldapResult = array();
519
520                for ($i = 0; $i < $entries['count']; $i++)
521                        $ldapResult[$entries[$i]['uidnumber'][0]] = array('cn' => $entries[$i]['cn'][0], 'telephoneNumber' => $entries[$i]['telephonenumber'][0]);
522
523                /* no records found. bye. */
524                if (count($ldapResult) == 0)
525                        return array();
526
527                $uids = implode( ',', array_keys( $ldapResult ) );
528
529                /* searching for aditional employee information */
530                $query  = "SELECT ";
531                $query .= "             f.funcionario_id AS funcionario_id, f.area_id AS area_id, a.sigla AS area ";
532                $query .= " FROM ";
533                $query .= "                     funcionario f ";
534                $query .= "             INNER JOIN ";
535                $query .= "                     area a USING (area_id) ";
536                $query .= "             INNER JOIN ";
537                $query .= "                     funcionario_status s ON ((f.funcionario_status_id = s.funcionario_status_id) AND (s.exibir = 'S')) ";
538                $query .= " WHERE ";
539                $query .= "             (f.organizacao_id = ?) ";
540                $query .= "     AND ";
541                $query .= "             (f.funcionario_id IN ({$uids})) ";
542
543                $result = $this->db->query($query, array($organizationID))->GetArray(-1);
544                $employees = array();
545
546                /* filling return array with employee's information */
547                for ($i = 0; $i < count($result); $i++) {
548                        $employees []= array(
549                                        'area'                          => $result[$i]['area'],
550                                        'area_id'                       => $result[$i]['area_id'],
551                                        'funcionario_id'        => $result[$i]['funcionario_id'],
552                                        'cn'                            => $ldapResult[$result[$i]['funcionario_id']]['cn'],
553                                        'telephoneNumber'       => empty($ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']) ? '': $ldapResult[$result[$i]['funcionario_id']]['telephoneNumber']
554                        );
555                }
556
557                /* sorting by name (cn) */
558        $sort_function = create_function('$a, $b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);');
559        usort($employees, $sort_function );
560
561                return $employees;
562        }
563
564
565        /**
566         * Busca informações sobre um funcionário.
567         * @param array $params Uma array contendo o ID do funcionário cujas informações serão extraídas e de sua organização (Ajax).
568         * @param int $employeeID O ID do funcionário.
569         * @param int $organizationID O ID da organização.
570         * @return array Informações sobre o funcionário.
571         * @access public
572         */
573        function getEmployeeInfo($employeeID, $organizationID)
574        {
575                require_once dirname(__FILE__) . '/class.so_orgchart.inc.php';
576
577                $SOOrgchart = new so_orgchart();
578                $SOOrgchart->setExternalCalls(true);
579                $output = $SOOrgchart->getEmployeeInfo($employeeID, $organizationID);
580                $SOOrgchart->setExternalCalls(false);
581
582                return $output;
583        }
584
585        /**
586         * Busca informações sobre uma área.
587         * @param array $params Uma array contendo o ID da área cujas informações serão extraídas e de sua organização (Ajax).
588         * @param int $areaID O ID da área.
589         * @param int $organizationID O ID da organização.
590         * @return array Informações sobre a área.
591         * @access public
592         */
593        function getAreaInfo($areaID, $organizationID)
594        {
595                require_once dirname(__FILE__) . '/class.so_orgchart.inc.php';
596
597                $SOOrgchart = new so_orgchart();
598                $SOOrgchart->setExternalCalls(true);
599                $output = $SOOrgchart->getAreaInfo($areaID, $organizationID);
600                $SOOrgchart->setExternalCalls(false);
601
602                return $output;
603        }
604
605        /**
606         * Get useful phones list
607         * @param int $organizationID The organization ID
608         * @return array Useful phones list
609         * @access public
610         */
611        function getUsefulPhones( $organizationID )
612        {
613                $result = $this -> db -> query( "SELECT descricao, numero FROM telefone WHERE (organizacao_id = ?) ORDER BY descricao", array( $organizationID ) );
614
615                $output = $result->GetArray(-1);
616                for ($i = 0; $i < count($output); $i++)
617                        for ($j = 0; $j < $result->_numOfFields; $j++)
618                                unset($output[$i][$j]);
619
620                return $output;
621        }
622
623        /**
624         * Get areas with substitute boss
625         * @param int $organizationID The organization ID
626         * @return array areas with substitute boss
627         * @access public
628         */
629        function getAreaWithSubtituteBoss( $organizationID )
630        {
631                $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 ) );
632
633                $cachedLDAP = $GLOBALS[ 'workflow' ][ 'factory' ] -> newInstance( 'CachedLDAP' );
634                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_LDAP_DATABASE );
635
636                $output = $result->GetArray(-1);
637                for ( $i = 0; $i < count($output); $i++ )
638                {
639                        for ($j = 0; $j < $result->_numOfFields; $j++)
640                                unset($output[$i][$j]);
641
642                        $entry = $cachedLDAP -> getEntryByID( $output[ $i ][ 'titular' ] );
643                        if ( $entry && ( ! is_null( $entry[ 'cn' ] ) ) )
644                                $output[ $i ][ 'titular' ] = $entry[ 'cn' ];
645
646                        $entry = $cachedLDAP -> getEntryByID( $output[ $i ][ 'substituto' ] );
647                        if ( $entry && ( ! is_null( $entry[ 'cn' ] ) ) )
648                                $output[ $i ][ 'substituto' ] = $entry[ 'cn' ];
649
650                        $output[$i]['data_inicio'] = implode('/', array_reverse(explode('-', $output[$i]['data_inicio'])));
651                        $output[$i]['data_fim'] = implode('/', array_reverse(explode('-', $output[$i]['data_fim'])));
652                }
653
654                return $output;
655        }
656
657        /**
658         * Get manning list
659         * @param int $organizationID The organization ID
660         * @return array The manning list
661         * @access public
662         */
663        function getManning( $organizationID )
664        {
665                $result = $this -> db -> query( 'SELECT localidade_id, descricao FROM localidade WHERE (organizacao_id = ?) ORDER BY descricao', array( $organizationID ) );
666
667                $output = $result->GetArray( -1 );
668                for ( $i = 0; $i < count($output); $i++ )
669                        for ($j = 0; $j < $result->_numOfFields; $j++)
670                                unset($output[$i][$j]);
671
672                return $output;
673        }
674
675        /**
676         * Get employees from a specific location
677         * @param int $categoryID The category ID
678         * @param int $organizationID The organization ID
679         * @return array The list o employees of that location
680         * @access public
681         */
682        function getManningEmployees( $locationID, $organizationID )
683        {
684                $organizationID = ( int ) $organizationID;
685                $locationID = ( int ) $locationID;
686
687                // load the employees from the location
688                $query = "SELECT f.funcionario_id, f.organizacao_id, f.area_id, a.sigla AS area,"
689                        . " COALESCE(f.funcionario_categoria_id, 0) AS funcionario_categoria_id"
690                        . " FROM funcionario f, funcionario_status s, area a"
691                        . " WHERE (f.area_id = a.area_id)"
692                        . " AND (f.funcionario_status_id = s.funcionario_status_id)"
693                        . " AND (f.organizacao_id = ?)"
694                        . " AND (f.localidade_id = ?)"
695                        . " AND (s.exibir = ?)";
696
697                $result = $this -> db -> query( $query, array( $organizationID, $locationID, 'S' ) );
698
699                $employees = $result -> GetArray( -1 );
700                $cachedLDAP = $GLOBALS[ 'workflow' ][ 'factory' ] -> newInstance( 'CachedLDAP' );
701                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_NORMAL );
702
703                $categoriesCount = array( );
704                for ( $i = 0; $i < count( $employees ); $i++ )
705                {
706                        // remove numeric fields
707                        for ( $j = 0; $j < $result -> _numOfFields; $j++ )
708                                unset( $employees[ $i ][ $j ] );
709
710                        $employees[ $i ][ 'cn' ] = '';
711                        $employees[ $i ][ 'telephoneNumber' ] = '';
712
713                        // try to find the telephone number
714                        $entry = $cachedLDAP -> getEntryByID( $employees[ $i ][ 'funcionario_id' ] );
715                        if ( $entry )
716                        {
717                                $employees[ $i ][ 'telephoneNumber' ] = is_null( $entry[ 'telephonenumber' ] ) ? '' : $entry[ 'telephonenumber' ];
718                                $employees[ $i ][ 'cn' ] = is_null( $entry[ 'cn' ] ) ? '' : $entry[ 'cn' ];
719                                $employees[ $i ][ 'removed' ] = is_null( $entry[ 'last_update' ] );
720                        }
721
722                        // count the number of employees in each category
723                        $categoryID = $employees[ $i ][ 'funcionario_categoria_id' ];
724                        if ( isset( $categoriesCount[ $categoryID ] ) )
725                                $categoriesCount[ $categoryID ]++;
726                        else
727                                $categoriesCount[ $categoryID ] = 1;
728                }
729
730                $usedCategories = array_keys( $categoriesCount );
731                $availableCategories = $this -> getCategoriesList( $organizationID );
732                $output = array( );
733                $output[ 'employees' ] = $employees;
734                $output[ 'categories' ] = array( );
735                foreach ( $availableCategories as $category )
736                {
737                        if ( ! in_array( $category[ 'funcionario_categoria_id' ], $usedCategories ) )
738                                continue;
739
740                        $category[ 'contagem' ] = $categoriesCount[ $category[ 'funcionario_categoria_id' ] ];
741                        $output[ 'categories' ][ ] = $category;
742                }
743
744                usort( $output[ 'employees' ], create_function( '$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);' ) );
745
746                return $output;
747        }
748
749        /**
750         * Return the list of employees in alphabetical order
751         * @param int $organizationID The organization ID
752         * @return array The list o employees
753         * @access public
754         */
755        function getAlphabeticalEmployees( $organizationID )
756        {
757                $organizationID = ( int ) $organizationID;
758
759                // load the employees from the location
760                $query = "SELECT f.funcionario_id, f.organizacao_id, f.area_id, a.sigla AS area,"
761                        . " COALESCE(f.funcionario_categoria_id, 0) AS funcionario_categoria_id"
762                        . " FROM funcionario f, funcionario_status s, area a"
763                        . " WHERE (f.area_id = a.area_id)"
764                        . " AND (f.funcionario_status_id = s.funcionario_status_id)"
765                        . " AND (f.organizacao_id = ?)"
766                        . " AND (s.exibir = ?)";
767
768                $result = $this -> db -> query( $query, array( $organizationID, 'S' ) );
769
770                $employees = $result -> GetArray( -1 );
771
772                $cachedLDAP = $GLOBALS[ 'workflow' ][ 'factory' ] -> newInstance( 'CachedLDAP' );
773                $cachedLDAP -> setOperationMode( $cachedLDAP -> OPERATION_MODE_NORMAL );
774
775                $categoriesCount = array( );
776                for ( $i = 0; $i < count( $employees ); $i++ )
777                {
778                        // remove numeric fields
779                        for ( $j = 0; $j < $result -> _numOfFields; $j++ )
780                                unset( $employees[ $i ][ $j ] );
781
782                        $employees[ $i ][ 'cn' ] = '';
783                        $employees[ $i ][ 'telephoneNumber' ] = '';
784
785                        // try to find the telephone number
786                        $entry = $cachedLDAP -> getEntryByID( $employees[ $i ][ 'funcionario_id' ] );
787                        if ( $entry )
788                        {
789                                $employees[ $i ][ 'telephoneNumber' ] = is_null( $entry[ 'telephonenumber' ] ) ? '' : $entry[ 'telephonenumber' ];
790                                $employees[ $i ][ 'cn' ] = is_null( $entry[ 'cn' ] ) ? '' : $entry[ 'cn' ];
791                                $employees[ $i ][ 'removed' ] = is_null( $entry[ 'last_update' ] );
792                        }
793
794                }
795
796                usort( $employees, create_function( '$a,$b', 'return strcasecmp($a[\'cn\'],$b[\'cn\']);' ) );
797
798                $paging = $GLOBALS['workflow']['factory']->newInstance('Paging', 50, $_POST);
799                $employees = $paging->restrictItems( $employees );
800
801                // count the number of employees in each category
802                for ( $i = 0; $i < count( $employees ); $i++ )
803                {
804                        $categoryID = $employees[ $i ][ 'funcionario_categoria_id' ];
805                        if ( isset( $categoriesCount[ $categoryID ] ) )
806                                $categoriesCount[ $categoryID ]++;
807                        else
808                                $categoriesCount[ $categoryID ] = 1;
809                }
810
811                $usedCategories = array_keys( $categoriesCount );
812                $availableCategories = $this -> getCategoriesList( $organizationID );
813                $output = array( );
814
815                $output['employees'] = $employees;
816                $output['categories'] = array( );
817                $output['paging_links'] = $paging -> commonLinks();
818
819                foreach ( $availableCategories as $category )
820                {
821                        if ( ! in_array( $category[ 'funcionario_categoria_id' ], $usedCategories ) )
822                                continue;
823
824                        $category[ 'contagem' ] = $categoriesCount[ $category[ 'funcionario_categoria_id' ] ];
825                        $output[ 'categories' ][ ] = $category;
826                }
827
828                return $output;
829        }
830}
831?>
Note: See TracBrowser for help on using the repository browser.