source: sandbox/workflow/trunk/inc/class.so_userinterface.inc.php @ 2466

Revision 2466, 29.3 KB checked in by pedroerp, 14 years ago (diff)

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

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