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

Revision 7712, 32.0 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Revisao das Melhorias de performance no codigo do Expresso.

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