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

Revision 7673, 32.5 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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