source: trunk/expressoMail1_2/inc/class.ldap_functions.inc.php @ 5509

Revision 5509, 41.8 KB checked in by gustavo, 12 years ago (diff)

Ticket #2488 - Adicionar cabecalho de licenca em arquivos que nao o possuem

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2                /***************************************************************************
3                * Expresso Livre                                                           *
4                * http://www.expressolivre.org                                             *
5                * --------------------------------------------                             *
6                *  This program is free software; you can redistribute it and/or modify it *
7                *  under the terms of the GNU General Public License as published by the   *
8                *  Free Software Foundation; either version 2 of the License, or (at your  *
9                *  option) any later version.                                              *
10                \**************************************************************************/
11               
12require_once(dirname(__FILE__).'/../../services/class.servicelocator.php');
13include_once("class.imap_functions.inc.php");
14include_once("class.functions.inc.php");
15
16function ldapRebind($ldap_connection, $ldap_url)
17{
18        @ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'],$_SESSION['phpgw_info']['expressomail']['ldap_server']['pw']);
19}
20
21class ldap_functions
22{
23        var $ds;
24        var $ldap_host;
25        var $ldap_context;
26        var $imap;
27        var $external_srcs;
28        var $max_result;
29        var $functions;
30        var $ldapService;
31       
32        function ldap_functions(){
33        // todo: Page Configuration for External Catalogs.
34                @include("../contactcenter/setup/external_catalogs.inc.php");
35                $this->ldapService = ServiceLocator::getService('ldap');
36                if(isset($external_srcs))
37                $this->external_srcs = $external_srcs;
38                $this->max_result = $this->ldapService->limit;
39                $this->functions = new functions();
40        }
41        // Using ContactCenter configuration.
42        function ldapConnect($refer = false,$catalog = 0){
43                if ($catalog > 0 && is_array($this->external_srcs)){
44                        $this->ldap_host        = $this->external_srcs[$catalog]['host'];
45                        $this->ldap_context = $this->external_srcs[$catalog]['dn'];
46                        $this->bind_dn          = $this->external_srcs[$catalog]['acc'];
47                        $this->bind_dn_pw       = $this->external_srcs[$catalog]['pw'];
48                        $this->object_class = $this->external_srcs[$catalog]['obj'];
49                        $this->base_dn          = $this->external_srcs[$catalog]['dn'];
50                        $this->branch           = $this->external_srcs[$catalog]['branch'];
51                }else {
52                        $this->ldap_host        = $_SESSION['phpgw_info']['expressomail']['ldap_server']['host'];
53                        $this->ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn'];
54                        $this->bind_dn = $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'];
55                        $this->bind_dn_pw = $_SESSION['phpgw_info']['expressomail']['ldap_server']['pw'];
56                        $this->branch = 'ou';
57                }
58
59                $this->ds = ldap_connect($this->ldap_host);
60                ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, 3);
61                ldap_set_option($this->ds, LDAP_OPT_REFERRALS, $refer);
62                if ($refer)     {
63                        ldap_set_rebind_proc($this->ds, ldapRebind);
64                }
65                @ldap_bind($this->ds,$this->bind_dn,$this->bind_dn_pw );
66        }
67
68        //Teste jakjr retornando o DS
69        function ldapConnect2($refer = false){
70                $ds = ldap_connect($_SESSION['phpgw_info']['expressomail']['ldap_server']['host']);
71
72                if (!$ds)
73                        return false;
74
75                ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
76                ldap_set_option($ds, LDAP_OPT_REFERRALS, $refer);
77                if ($refer)
78                        ldap_set_rebind_proc($ds, 'rebind');
79                @ldap_bind($ds, $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'],$_SESSION['phpgw_info']['expressomail']['ldap_server']['pw']);
80
81                return $ds;
82        }
83
84
85        // usa o host e context do setup.
86        function ldapRootConnect($refer = false){
87                $this->ldap_host        = $_SESSION['phpgw_info']['expressomail']['server']['ldap_host'];
88                $this->ldap_context = $_SESSION['phpgw_info']['expressomail']['server']['ldap_context'];
89                $this->ds                       = ldap_connect($this->ldap_host);
90                ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, 3);
91                ldap_set_option($this->ds, LDAP_OPT_REFERRALS, $refer);
92                ldap_bind($this->ds, $_SESSION['phpgw_info']['expressomail']['server']['ldap_root_dn'],$_SESSION['phpgw_info']['expressomail']['server']['ldap_root_pw']);
93
94        }
95
96        function quicksearch($params)
97        {
98                include_once("class.functions.inc.php");
99                $functions = new functions;
100
101                $field          = $params['field'];
102                $ID                     = $params['ID'];
103               
104                $ldapService = ServiceLocator::getService('ldap');
105                $filter =  $ldapService->getSearchFilter($params['search_for']);
106
107                $contacts_result = array();
108                $contacts_result['field'] = $field;
109                $contacts_result['ID'] = $ID;
110                $search_for = utf8_encode($params['search_for']);
111               
112                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['extended_info'])
113                        $extendedinfo=true;
114                else
115                        $extendedinfo=false;
116
117                // follow the referral
118                $this->ldapConnect(true);
119
120                if ($this->ds)
121                {
122                    $ldapService->connection = $this->ds;
123                                if($extendedinfo)
124                                        $justthese = array("cn", "mail", "telephonenumber", "uid","uidNumber", "mobile", "phpgwaccountvisible", "employeenumber", "ou");
125                                else
126                                        $justthese = array("cn", "mail", "telephoneNumber", "phpgwAccountVisible", "uidNumber","uid");
127                $types = false;
128
129                if( $field == 'null' || $ID == 'null' )
130                        {
131                    $justthese[] = "jpegphoto";
132                    $types = 'u';
133                }
134
135                $filter = $ldapService->getSearchFilter( $params['search_for'], $types );
136
137                $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese, 0, $this->max_result);
138                       
139                                if(!$sr)
140                                        return null;
141
142                                $count_entries = ldap_count_entries($this->ds,$sr);
143
144                $info = ldap_get_entries($this->ds, $sr);
145
146            // New search only on user sector
147            if ($count_entries == $this->max_result)
148            {
149                $overload = $count_entries;
150                                }
151                                else
152                                {
153                                $catalogsNum=count($this->external_srcs);
154                for ($i=0; $i<=$catalogsNum; $i++)      {
155                                        if ($this->external_srcs[$i]["quicksearch"]) {
156                                                $this->ldapConnect(true,$i);
157                                                $filter="(|(cn=*$search_for*)(mail=*$search_for*))";
158                                                if($extendedinfo)
159                                        $justthese = array("cn", "mail", "telephonenumber", "uid","uidNumber", "mobile", "phpgwaccountvisible", "employeenumber", "ou");
160                                                else
161                                                        $justthese = array("cn", "mail", "telephoneNumber", "phpgwAccountVisible","uidNumber", "uid");
162                                                $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese, 0, $this->max_result+1);
163                                                if(!$sr)
164                                                        return null;
165                                                $count_entries = ldap_count_entries($this->ds,$sr);
166                                                $search = ldap_get_entries($this->ds, $sr);
167                                                for ($j=0; $j<$search["count"]; $j++) {
168                                                        $info[] = $search[$j];
169                                                }
170                                                $info["count"] = count($info)-1;
171                                        }
172                                }
173                        }
174
175            $tmp = array();
176            $tmp_users_from_user_org = array();
177
178                        for ($i=0; $i<$info["count"]; $i++)
179                        {
180                $key = $info[$i]["mail"][0] . '%' . $info[$i]["telephonenumber"][0] . '%'. $info[$i]["mobile"][0] . '%' . $info[$i]["uid"][0] . '%' . $info[$i]["jpegphoto"]['count'] . '%' . $info[$i]["employeenumber"][0] . '%' .    $info[$i]["ou"][0];
181
182                if (/*(!$quickSearch_only_in_userSector) &&*/ preg_match("/$user_sector_dn/i", $info[$i]['dn']))
183                                {
184                        $tmp_users_from_user_org[$key] = utf8_decode($info[$i]["cn"][0]);
185                        continue;
186                                }
187
188                $tmp[$key] = utf8_decode($info[$i]["cn"][0]);
189                                        }
190
191                        natcasesort($tmp_users_from_user_org);
192                        natcasesort($tmp);
193
194                        if (($field != 'null') && ($ID != 'null'))
195                        {
196                                $i = 0;
197
198                                $tmp = array_merge($tmp, $tmp_users_from_user_org);
199                                natcasesort($tmp);
200
201                                foreach ($tmp as $info => $cn)
202                                {
203                                        $contacts_result[$i] = array();
204                                        $contacts_result[$i]["cn"] = $cn;
205                                        list ($contacts_result[$i]["mail"], $contacts_result[$i]["phone"], $contacts_result[$i]["mobile"], $contacts_result[$i]["uid"], $contacts_result[$i]["jpegphoto"], $contacts_result[$i]["employeenumber"], $contacts_result[$i]["ou"]) = split ('%', $info);
206                                        $i++;
207                                }
208                                $contacts_result['quickSearch_only_in_userSector'] = $quickSearch_only_in_userSector;
209                    $contacts_result['maxResult'] = $ldapService->limit;
210                        }
211                        else
212                        {
213                                $options_users_from_user_org = '';
214                                $options = '';
215
216           
217                                $i = 0;
218                                foreach ($tmp_users_from_user_org as $info => $cn)
219                                {
220                                        $contacts_result[$i] = array();
221                                        $options_users_from_user_org .= $this->make_quicksearch_card($info, $cn);
222                                        $i++;
223                                }
224
225           
226                                foreach ($tmp as $info => $cn)
227                                {
228                                        $contacts_result[$i] = array();
229                                        $options .= $this->make_quicksearch_card($info, $cn);
230                                        $i++;
231                                }
232
233
234                                        if (($options_users_from_user_org != '') && ($options != ''))
235                                        {
236                                                $head_option0 =
237                                                        '<tr class="quicksearchcontacts_unselected">' .
238                                                                '<td colspan="2" width="100%" align="center" style="background:#EEEEEE"><B>' .
239                                                                        $this->functions->getLang('Users from your organization') . '</B> ['.count($tmp_users_from_user_org).']';
240                                                                '</td>' .
241                                                        '</tr>';
242
243                                                $head_option1 =
244                                                        '<tr class="quicksearchcontacts_unselected">' .
245                                                                '<td colspan="2" width="100%" align="center" style="background:#EEEEEE"><B>' .
246                                                                        $this->functions->getLang('Users from others organizations') . '</B> ['.count($tmp).']';
247                                                                '</td>' .
248                                                        '</tr>';
249                                        }
250                   
251                    $head_option = '';
252
253                    if( $overload )
254                    $head_option = '<tr class="quicksearchcontacts_unselected">' .
255                                    '<td colspan="2" width="100%" align="center" style="background:#EEEEEE; color: red;"><B>' .str_replace('%1', $this->max_result, $this->functions->getLang('More than %1 results. Please, try to refine your search.')) . '</B> '.
256                                    '</td>' .
257                                    '</tr>';
258
259                    $contacts_result = $head_option.$head_option0 . $options_users_from_user_org . $head_option1. $options;
260
261                                }
262                        }
263
264                ldap_close($this->ds);
265
266                return $contacts_result;
267        }
268
269       
270         /**
271        * Método que faz o roteamento entre os métodos de busca (Catálogo pessoal, global e todos)
272        * @license    http://www.gnu.org/copyleft/gpl.html GPL
273        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
274        * @sponsor    Caixa Econômica Federal
275        * @author     Prognus Software Livre <airton@prognus.com.br | prognus@prognus.com.br>
276        * @param      <array> <$param> <parametros vindos do cliente>
277        */
278        function quicksearchcontact($params)
279        {
280            if(array_key_exists('Type', $params)){
281                return $this->quickSearch($params);
282            }
283           
284            $modal = false;
285            if($params['catalog'])
286                $modal = true;
287             
288            include_once dirname(__FILE__). '/../../header.inc.php';
289           
290            if($modal)
291            {
292                if($params['catalog'] == "global")
293                {       
294                    return $this->quickSearchGlobal($params);
295                }
296                else
297                {
298                    if($params['catalog'] == "personal")
299                        return $this->quickSearchPersonal($params);
300                    else
301                        return $this->quickSearchAll($params);
302                }
303            }
304            else
305            {
306                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['catalog_search'] == "global")
307                {
308                    return $this->quickSearchGlobal($params);
309                }
310                else
311                {   
312                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['catalog_search'] == "personal")
313                        return $this->quickSearchPersonal($params);                   
314                    else
315                                                //Veirifica se quem chamou foi o campo de pesquisa rápida Expresso_Mail
316                                                if(($params['field'] == 'null') && ($params['ID'] == 'null'))
317                                                        return $this->quickSearch($params);
318                                                else
319                                                        return $this->quickSearchAll($params);                                                 
320                }
321            }
322        }
323       
324       
325
326        /**
327        * Método que faz a busca de usuários em todos os catálogos
328        * @license    http://www.gnu.org/copyleft/gpl.html GPL
329        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
330        * @sponsor    Caixa Econômica Federal
331        * @author     Prognus Software Livre <airton@prognus.com.br | prognus@prognus.com.br>
332        * @param      <array> <$param> <parametros vindos do cliente>
333        * @return     <array> <$retorno> <Array com os usuários de todos os catálogos, de acordo com o parâmetro>
334        */
335        function quickSearchAll($params)
336        {
337               
338            $retorno_personal = $this->quickSearchPersonal($params);
339            $retorno_global   = $this->quickSearchGlobal($params);
340            //$retorno = $retorno_personal + $retorno_global;
341            $retorno = array_merge($retorno_personal, $retorno_global);
342                       
343                        $retorno['type_catalog'] = "A";
344                        $retorno['search_for'] = $params['search_for'];
345            return $retorno;
346        }
347       
348       
349        /**
350        * Método que faz a busca de usuários no Catálogo Pessoal
351        * @license    http://www.gnu.org/copyleft/gpl.html GPL
352        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
353        * @sponsor    Caixa Econômica Federal
354        * @author     Prognus Software Livre <airton@prognus.com.br | prognus@prognus.com.br>
355        * @param      <array> <$param> <parametros vindos do cliente>
356        * @return     <array> <$retorno> <Array com os usuários do Catálogo Pessoal, de acordo com o parâmetro>
357        */
358        function quickSearchPersonal($params, $all=false)
359        {
360            $results = array();
361            $DBService = ServiceLocator::getService('db');
362            $results   = $DBService->search_contacts($params['search_for']);
363                        $results2 = array();
364            $results2   = $DBService->search_groups($params['search_for']);
365           
366            if(is_array($results)){
367                if(is_array($results2)){
368                        $results   = array_merge($results, $results2);
369                }
370            }
371            else if(is_array($results2)){
372                $results = $results2;
373            }
374           
375            if(!$all)
376                $results['type_catalog'] = "P";
377                       
378                        foreach($results as $i=>$value)
379                                $results[$i]['type_contact'] = "P";
380                       
381                        $results['search_for'] = $params['search_for'];
382                       
383                        return $results;
384        }
385       
386       
387        /**
388        * Método que faz a busca de usuários no Catálogo Geral
389        * @license    http://www.gnu.org/copyleft/gpl.html GPL
390        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
391        * @sponsor    Caixa Econômica Federal
392        * @author     Prognus Software Livre <airton@prognus.com.br | prognus@prognus.com.br>
393        * @param      <array> <$param> <parametros vindos do cliente>
394        * @return     <array> <$retorno> <Array com os usuários do Catálogo Global, de acordo com o parâmetro>
395        */
396        function quickSearchGlobal($params, $all=false)
397        {             
398            include_once dirname(__FILE__). '/../../header.inc.php';
399            $c = CreateObject('phpgwapi.config','contactcenter');
400            $all_data = $c->read_repository();
401           
402            $searchable_fields = array();           
403            foreach($all_data as $index => $value)
404            {
405                $parts = explode('_', $index);
406                if (is_numeric($parts[3]) && $parts[1]=='attribute')
407                {   
408                    if($parts[2] == 'searchable' /*&& $value == 'true'*/)
409                        $searchable_fields[$all_data['cc_attribute_ldapname_' . $parts[3]]] = $all_data['cc_attribute_name_' . $parts[3]];   
410                }
411            }   
412            include_once("class.functions.inc.php");
413            $functions      = new functions;
414            $field          = $params['field'];
415            $ID             = $params['ID'];
416            $ldapService    = ServiceLocator::getService('ldap');
417            $filter         = $ldapService->getSearchFilter($params['search_for']);
418 
419            $contacts_result          = array();
420            $contacts_result['field'] = $field;
421            $contacts_result['ID']    = $ID;
422            $search_for               = utf8_encode($params['search_for']);
423           
424            $this->ldapConnect(true);
425            if ($this->ds)
426            {
427                $ldapService->connection = $this->ds;
428                $campos_extras = '';
429                $justthese = array("cn", "mail", "telephonenumber", "mobile", "phpgwaccountvisible", "uid", "employeenumber", "ou");
430                foreach($searchable_fields as $fields_ldap => $value_field)
431                {   
432                    $campos_extras .= $fields_ldap . "|" . $value_field . "#";
433                    array_push($justthese, $fields_ldap);   
434                }
435                $types = false;
436
437                $campos_extras = substr($campos_extras,0,-1);
438               
439                if($field == 'null' || $ID == 'null')
440                {
441                    $justthese[] = "jpegphoto";
442                    $types = 'u';
443                } 
444                $filter = $ldapService->getSearchFilter($params['search_for'], $types);
445                // Retirei o this->max_results, que limitava a busca. Agora ta retornando tudo amigo.
446                $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese, 0);
447                 
448                if(!$sr)
449                    return null;
450               
451                $count_entries = ldap_count_entries($this->ds,$sr);
452                $info          = ldap_get_entries($this->ds, $sr);
453                $info_return   = $info;
454                //if($campos_extras != '')
455                //array_push($info_return, $campos_extras);
456                        }
457                        ldap_close($this->ds);     
458
459                        //Busca em Catalagos externos
460                        $catalogsNum=count($this->external_srcs);
461                        for ($i=0; $i<=$catalogsNum; $i++)      {
462                                if ($this->external_srcs[$i]["quicksearch"])
463                                {
464                                        $this->ldapConnect(true,$i);
465                                        $filter="(|(cn=*$search_for*)(mail=*$search_for*))";
466                                        $justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible", "uid","employeeNumber", "ou");
467                                        $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese, 0, $this->max_result+1);
468                                        if(!$sr)
469                                                return null;
470                                        $count_entries = ldap_count_entries($this->ds,$sr);
471                                        $search = ldap_get_entries($this->ds, $sr);
472                                        for ($j=0; $j<$search["count"]; $j++) {
473                                                $info_return[] = $search[$j];
474                                        }
475                                        $info_return["count"] = count($info_return)-1;
476                                }
477                        }
478                        //---------------------------------------------------------------//
479                       
480            if($all == false)
481                $info_return['type_catalog'] = "G";
482           
483                        $info_return['extra_ldap_fields'] = $campos_extras;
484                       
485                        foreach($info_return as $i=>$value)
486                                $info_return[$i]['type_contact'] = "G";
487                               
488                        $info_return['search_for'] = $params['search_for'];
489            return $info_return;
490        }
491       
492        function make_quicksearch_card($info, $cn)
493        {
494                include_once("class.functions.inc.php");
495                $functions = new functions;
496
497                $contacts_result = array();
498                $contacts_result["cn"] = $cn;
499                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['extended_info'])
500                    $extendedinfo=true;
501                else
502                    $extendedinfo=false;
503
504                list ($contacts_result["mail"], $contacts_result["phone"], $contacts_result["mobile"], $contacts_result["uid"], $contacts_result["jpegphoto"], $contacts_result["employeenumber"], $contacts_result["ou"]) = split ('%', $info);
505
506                if ($contacts_result['jpegphoto'])
507                        $photo_link = '<img src="./inc/show_user_photo.php?mail='.$contacts_result['mail'].'">';
508                else
509                        $photo_link = '<img src="./templates/default/images/photo.jpg">';
510
511                $phoneUser = $contacts_result['phone'];
512
513                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['voip_enabled'] && $phoneUser) {
514                        $phoneUser = '<a title="'.$this->functions->getLang("Call to Comercial Number").'" href="#" onclick="InfoContact.connectVoip(\''.$phoneUser.'\',\'com\')">'.$phoneUser.'</a>';
515                        if($contacts_result['mobile']){
516                                $phoneUser .= ' / <a title="'.$this->functions->getLang("Call to Mobile Number").'" href="#" onclick="InfoContact.connectVoip(\''.$contacts_result['mobile'].'\',\'mob\')">'.$contacts_result['mobile'].'</a>';
517                        }
518                }
519                //verifica de existe o celular do funcionario ($contacts_result["mobile"]), se nao, $phoneUser fica vazia;
520
521                    $mobileUser = $contacts_result["mobile"];
522                    if($mobileUser && !$voipMobile) {
523                            $phoneUser .= " / $mobileUser";
524                    }
525                    $empNumber = $contacts_result["employeenumber"];
526                        $uid = $contacts_result["uid"];
527                    if($empNumber) {
528                            $empNumber = "$empNumber - ";
529                    }
530                        else if($uid){
531                                $uid = "$uid - ";
532                        }                       
533                    $ou = $contacts_result["ou"];
534                    if($ou) {
535                            $ou = "<br/>$ou" ;
536                    }
537
538                // Begin: nickname, firstname and lastname for QuickAdd.
539                $fn = $contacts_result["cn"];
540                $array_name = explode(" ", $fn);
541                if(count($array_name) > 1){                     
542                        $fn = $array_name[0];
543                        array_shift($array_name);
544                        $sn = implode(" ",$array_name);
545                }
546                // End:
547                $option =
548                        '<tr class="quicksearchcontacts_unselected">' .
549                                '<td class="cc" width="1%">' .
550                                        '<a title="'.$this->functions->getLang("Write message").'" onClick="javascript:QuickSearchUser.create_new_message(\''.$contacts_result["cn"].'\', \''.$contacts_result["mail"].'\')">' .
551                                                $photo_link .
552                                        '</a>' .
553                                '</td>' .
554                                '<td class="cc">' .
555                                        '<span name="cn">' . ($empNumber != "" ? $empNumber : $uid) . $contacts_result['cn'] . '</span>' . '<br>' .
556                                        '<a title="'.$functions->getLang("Write message").'" onClick="javascript:QuickSearchUser.create_new_message(\''.$contacts_result["cn"].'\', \''.$contacts_result["mail"].'\')">' .
557                                                '<font color=blue>' .
558                                                '<span name="mail">' . $contacts_result['mail'] . '</span></a></font>'.
559                                                '<img src="templates/default/images/user_card.png" style="cursor: pointer;" title="'.$this->functions->getLang("Add Contact").'" onclick="javascript:connector.loadScript(\'ccQuickAdd\');ccQuickAddOne.showList(\''.$fn.','.$fn.','.$sn.','.$contacts_result["mail"].'\')">'.
560                                        '<br>' .
561                                        $phoneUser .
562                                        $ou .
563                                '</td>' .
564                                '</tr>';
565                return $option;
566        }
567
568        function get_catalogs(){
569                $catalogs = array();
570                $catalogs[0] = $this->functions->getLang("Global Catalog");
571                if($this->external_srcs)
572                        foreach ($this->external_srcs as $key => $valor ){
573                        $catalogs[$key] = $valor['name'];
574                }
575                return $catalogs;
576        }
577        function get_organizations($params){
578                $organizations = array();
579                $params['referral']?$referral = $params['referral']:$referral = false;
580                $cat = $params['catalog'];
581
582                $this->ldapConnect($referral,$cat);
583
584                        if($this->branch != '') {
585                                $filter="(&(".$this->branch."=*)(!(phpgwAccountVisible=-1)))";
586                                $justthese = array("$this->branch");
587                        $sr = ldap_list($this->ds, $this->ldap_context, $filter, $justthese);
588                        $info = ldap_get_entries($this->ds, $sr);
589
590                        if($info["count"] == 0)
591                        {
592                            $organizations[0]['ou'] = $this->ldap_context;
593                        }
594
595                        for ($i=0; $i<$info["count"]; $i++)
596                                $organizations[$i] = $info[$i]["ou"][0];
597
598                        ldap_close($this->ds);
599                        sort($organizations);
600                return $organizations;
601                        }else{
602                        return null;
603        }
604        }
605        function get_organizations2($params){
606                $organizations = array();
607                $referral = $params['referral'];
608                $this->ldapRootConnect($referral);
609                if ($this->ds) {
610                        $filter="(&(objectClass=organizationalUnit)(!(phpgwAccountVisible=-1)))";
611                        $justthese = array("ou");
612                        $sr = ldap_list($this->ds, $this->ldap_context, $filter, $justthese);
613                        $info = ldap_get_entries($this->ds, $sr);
614
615
616                        if($info["count"] == 0)
617                        {
618                            $organizations[0]['ou'] = $this->ldap_context;
619                            $organizations[0]['dn'] = $this->ldap_context;
620                        }
621                        else{
622                            for ($i=0; $i<$info["count"]; $i++)
623                            {
624                                    $organizations[$i]['ou'] = $info[$i]["ou"][0];
625                                    $organizations[$i]['dn'] = $info[$i]["dn"];
626                            }
627                        }
628                        ldap_close($this->ds);
629                        sort($organizations);
630                }
631                return $organizations;
632        }
633        //Busca usuarios de um contexto e ja retorna as options do select - usado por template serpro;
634        function search_users($params)
635        {
636                $owner = $_SESSION['phpgw_info']['expressomail']['user']['owner'];
637                        $ldapService = ServiceLocator::getService('ldap');
638                        $ldapService->connect($_SESSION['phpgw_info']['expressomail']['server']['ldap_host'],
639                        $_SESSION['phpgw_info']['expressomail']['server']['ldap_root_dn'],
640                        $_SESSION['phpgw_info']['expressomail']['server']['ldap_root_pw']);
641
642                        $groups = $ldapService->accountSearch($params['filter'], array("gidNumber","cn", 'uid'), $params['context'] , 'g', 'cn');
643                        $users = $ldapService->accountSearch($params['filter'], array("uidNumber","cn", 'uid'), $params['context'] , 'u', 'cn');
644                        $compartilhadas = $ldapService->accountSearch($params['filter'], array("uidNumber","cn",'uid'), $params['context'] , 's', 'cn');
645                       
646
647                        $group_options = array();
648                        $user_options  = array();
649                        $shared_options = array();
650
651                        foreach($groups as $group)
652                {
653                                $group_options[] = '"'.$group['gidnumber'].'U'.'":"'.$group['cn'].' ('.$group['uid'].')"';
654                }
655                foreach($users as $user)
656                    {
657                                if($owner != $user['uidnumber']) 
658                                        $user_options[] = '"'.$user['uidnumber'].'U'.'":"'.$user['cn'].' ('.$user['uid'].')"';
659                        }       
660                        foreach($compartilhadas as $shared)
661                        {
662                                if($owner != $shared['uidnumber']) 
663                                        $shared_options[] = '"'.$shared['uidnumber'].'U'.'":"'.$shared['cn'].' ('.$shared['uid'].')"';
664                    }
665       
666                        $user_options = '{'.implode( ',', $user_options ).'}';
667                        $group_options = '{'.implode( ',', $group_options ).'}';
668                        $shared_options = '{'.implode( ',', $shared_options ).'}';
669
670                 return '{"users":'.$user_options.',"groups":'.$group_options.',"shared":'. $shared_options .'}';
671        }
672
673        function catalogsearch($params)
674        {
675                $ldapService = ServiceLocator::getService('ldap');
676                $filter =  $ldapService->getSearchFilter($params['search_for'],array('u','l','s'));
677               
678                $catalog = $params['catalog'];
679                $error = False;
680
681                //if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['extended_info'])
682                    //$extendedinfo=true;
683                //else
684                    //$extendedinfo=false;
685
686
687                $this->ldapConnect(true,$catalog);
688
689                $params['organization'] == 'all' ? $user_context = $this->ldap_context :$user_context = $this->branch."=".$params['organization'].",".$this->ldap_context;
690
691                if ($this->ds) {
692                                $justthese = array("cn", "mail", "phpgwaccounttype", "phpgwAccountVisible", "employeeNumber", "ou");
693                        $sr=@ldap_search($this->ds, $user_context, $filter, $justthese, 0, $ldapService->limit+1);
694
695                        if(!$sr)
696                                return null;
697                        $count_entries = ldap_count_entries($this->ds,$sr);
698                        if ($count_entries > $ldapService->limit){
699                                $info = null;
700                                $error = True;
701                        }
702                        else
703                                $info = ldap_get_entries($this->ds, $sr);
704
705                        ldap_close($this->ds);
706
707                        $u_tmp = array();
708                        $g_tmp = array();
709
710                        for ($i=0; $i<$info["count"]; $i++){
711                                if((!$catalog==0)||(strtoupper($info[$i]["phpgwaccounttype"][0]) == 'U') && ($info[$i]["phpgwaccountvisible"][0] != '-1'))
712                                        //aqui eh feita a concatenacao do departamento ao cn;
713                                        $u_tmp[$info[$i]["mail"][0]] = utf8_decode($info[$i]["cn"][0]). '%' . $info[$i]["ou"][0];
714                                if((!$catalog==0)||(strtoupper($info[$i]["phpgwaccounttype"][0]) == 'L') && ($info[$i]["phpgwaccountvisible"][0] != '-1'))
715                                        $g_tmp[$info[$i]["mail"][0]] = utf8_decode($info[$i]["cn"][0]);
716                        }
717
718                        natcasesort($u_tmp);
719                        natcasesort($g_tmp);
720
721                        $i = 0;
722                        $users = array();
723
724                        foreach ($u_tmp as $mail => $cn){
725
726                                $tmp = explode("%", $cn); //explode o cn pelo caracter "%" e joga em $tmp;
727                                $name = $tmp[0]; //pega o primeiro item (cn) do vetor resultante do explode acima;
728                                $department = $tmp[1]; //pega o segundo item (ou) do vetor resultanto do explode acima;
729                                $users[$i++] = array("name" => $name, "email" => $mail, "department" => $department);
730
731                        }
732                        unset($u_tmp);
733
734                        $i = 0;
735                        $groups = array();
736
737                        foreach ($g_tmp as $mail => $cn){
738                                $groups[$i++] = array("name" => $cn, "email" => $mail);
739                        }
740                        unset($g_tmp);
741
742                        return  array('users' => $users, 'groups' => $groups, 'error' => $error,'maxResult' => $ldapService->limit);
743                }else
744                return null;
745        }
746
747        function get_emails_ldap(){
748
749                $result['mail']= array();
750                $result['mailalter']= array();
751                $user = $_SESSION['phpgw_info']['expressomail']['user']['account_lid'];
752                $this->ldapRootConnect(false);
753                if ($this->ds) {
754                        $filter="uid=".$user;
755                        $justthese = array("mail","mailAlternateAddress");
756                        $sr = ldap_search($this->ds,$this->ldap_context, $filter, $justthese);
757                        $ent = ldap_get_entries($this->ds, $sr);
758                        ldap_close($this->ds);
759
760                        for ($i=0; $i<$ent["count"]; $i++){
761                                $result['mail'][] = $ent[$i]["mail"][0];
762                                $result['mailalter'][] = $ent[$i]["mailalternateaddress"][0];
763                        }
764                }
765                return $result;
766        }
767
768        //Busca usuarios de um contexto e ja retorna as options do select;
769        function get_available_users($params)
770    {
771        $this->ldapRootConnect();
772        //Monta lista de Grupos e Usuarios
773        $users = Array();
774        $groups = Array();
775        $user_context= $params['context'];
776        $owner = $_SESSION['phpgw_info']['expressomail']['user']['owner'];
777
778        if ($this->ds)
779        {
780            $justthese = array("gidNumber","cn");
781            if ($params['type'] == 'search')
782                $sr=ldap_search($this->ds, $user_context, ("(&(cn=*)(phpgwaccounttype=g)(!(phpgwaccountvisible=-1)))"),$justthese);
783            else
784                $sr=ldap_list($this->ds, $user_context, ("(&(cn=*)(phpgwaccounttype=g)(!(phpgwaccountvisible=-1)))"),$justthese);
785            $info = ldap_get_entries($this->ds, $sr);
786            for ($i=0; $i<$info["count"]; $i++)
787                $groups[$uids=$info[$i]["gidnumber"][0]] = Array('name'    =>    $uids=$info[$i]["cn"][0], 'type'    =>    g);
788            $justthese = array("phpgwaccountvisible","uidNumber","cn");
789            if ($params['type'] == 'search')
790                $sr=ldap_search($this->ds, $user_context, ("(&(cn=*)(phpgwaccounttype=u)(!(phpgwaccountvisible=-1)))"),$justthese);
791            else
792                $sr=ldap_list($this->ds, $user_context, ("(&(cn=*)(phpgwaccounttype=u)(!(phpgwaccountvisible=-1)))"),$justthese);
793
794            $info = ldap_get_entries($this->ds, $sr);
795            for ($i=0; $i<$info["count"]; $i++)
796            {
797                if ($info[$i]["phpgwaccountvisible"][0] == '-1')
798                    continue;
799                $users[$uids=$info[$i]["uidnumber"][0]] = Array('name'    =>    $uids=$info[$i]["cn"][0], 'type'    =>    u);
800            }
801        }
802        ldap_close($this->ds);
803
804        @asort($users);
805        @reset($users);
806        @asort($groups);
807        @reset($groups);
808        $user_options ='';
809        $group_options ='';
810
811        foreach($groups as $id => $user_array) {
812                $newId = $id.'U';
813                $group_options .= '<option  value="'.$newId.'">'.utf8_decode($user_array['name']).'</option>'."\n";
814        }
815        foreach($users as $id => $user_array) {
816            if($owner != $id){
817                $newId = $id.'U';
818                $user_options .= '<option  value="'.$newId.'">'.utf8_decode($user_array['name']).'</option>'."\n";
819            }
820        }
821        return array("users" => $user_options, "groups" => $group_options);
822    }
823
824        //Busca usuarios de um contexto e ja retorna as options do select;
825        function get_available_users2($params)
826        {
827                $ldapService = ServiceLocator::getService('ldap');
828                $ldapService->connect($_SESSION['phpgw_info']['expressomail']['server']['ldap_host'],
829                $_SESSION['phpgw_info']['expressomail']['server']['ldap_root_dn'],
830                $_SESSION['phpgw_info']['expressomail']['server']['ldap_root_pw']);
831
832                $entries = $ldapService->accountSearch($params['sentence'], array('cn', 'uid'), $params['context'], 'u', 'cn');
833
834                $options = array();
835
836                foreach ($entries as $value)
837                        $options[] = '"'.$value['uid'].'"'.':'.'"'.$value['cn'].'"';
838
839                return "{".implode(',',$options)."}";           
840                                }
841
842        function uid2cn($uid)
843        {
844                // do not follow the referral
845                $this->ldapRootConnect(false);
846                if ($this->ds)
847                {
848                        $filter="(&(phpgwAccountType=u)(uid=$uid))";
849                        $justthese = array("cn");
850                        $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
851                        if(!$sr)
852                                return false;
853                        $info = ldap_get_entries($this->ds, $sr);
854                        return utf8_decode($info[0]["cn"][0]);
855                }
856                return false;
857        }
858        function uidnumber2uid($uidnumber)
859        {
860                // do not follow the referral
861                $this->ldapRootConnect(false);
862                if ($this->ds)
863                {
864                        $filter="(&(phpgwAccountType=u)(uidnumber=$uidnumber))";
865                        $justthese = array("uid");
866                        $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
867                        if(!$sr)
868                                return false;
869                        $info = ldap_get_entries($this->ds, $sr);
870                        return $info[0]["uid"][0];
871                }
872                return false;
873        }
874        function getSharedUsersFrom($params){
875                $filter = '';
876                $i = 0;         
877                //Added to save if must save sent messages in shared folder
878                $acl_save_sent_in_shared = array();
879               
880                if($params['uids']) {
881                        $uids = explode(";",$params['uids']);
882                        $this->imap = new imap_functions();                     
883                        foreach($uids as $index => $uid){
884                                $params = array();
885                                //Added to save if user has create permission
886                                $acl_create_message = array();
887                                $acl = $this->imap->getacltouser($uid);
888                                if ( preg_match("/a/",$acl )){                         
889                                        $filter .= "(uid=$uid)";                                       
890                                        if ( preg_match("/p/",$acl )){                         
891                                                $acl_save_sent_in_shared[ $i ] =$uid;
892                                                $i++;
893                                        }                                       
894                                }                                                       
895                        }                       
896                }
897               
898                $this->ldapRootConnect(false);
899                if ($this->ds) {
900                        $justthese = array("cn","mail","uid");
901                        if($filter) {
902                                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s))(|$filter))";
903                                $sr             =       ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
904                                ldap_sort($this->ds,$sr,"cn");
905                                $info   =       ldap_get_entries($this->ds, $sr);
906                                $var = print_r($acl_save_sent_in_shared, true);                         
907                                for ($i = 0;$i < $info["count"]; $i++){
908                                        $info[$i]['cn'][0] = utf8_decode($info[$i]['cn'][0]);
909                                        //verify if user has permission to save sent messages in a shared folder
910                                        if ( in_array( $info[$i]['uid'][0],$acl_save_sent_in_shared) ){                                         
911                                                $info[$i]['save_shared'][0] = 'y';
912                                        } else $info[$i]['save_shared'][0] = 'n';
913                                }
914                        }
915               
916                        $info['myname'] = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
917
918                        //Find institucional_account.
919                        $filter="(&(phpgwAccountType=i)(mailForwardingAddress=".$_SESSION['phpgw_info']['expressomail']['user']['email']."))";
920                        $sr     = ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
921                        ##
922                        # @AUTHOR Rodrigo Souza dos Santos
923                        # @DATE 2008/09/17
924                        # @BRIEF Changing to ensure that the variable session is always with due value.
925                        ##
926                        if(ldap_count_entries($this->ds,$sr))
927                        {
928                                ldap_sort($this->ds,$sr,"cn");
929                                $result = ldap_get_entries($this->ds, $sr);
930                                for ($j = 0;$j < $result["count"]; $j++){
931                                        $info[$i]['cn'][0] = utf8_decode($result[$j]['cn'][0]);
932                                        $info[$i]['mail'][0] = $result[$j]['mail'][0];
933                                        $info[$i]['save_shared'][0] = 'n';
934                                        $info[$i++]['uid'][0] = $result[$j]['uid'][0];                                 
935                                }
936                        }
937
938                        $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] = $info;
939                       
940                        return $info;
941                }
942        }
943
944        function getUserByEmail($params)
945        {
946                $expires = 60*60*24*30; /* 30 days */
947                header("Cache-Control: maxage=".$expires);
948                header("Pragma: public");
949                header("Expires: ".gmdate('D, d M Y H:i:s', time()+$expires)); 
950                $filter="(&(phpgwAccountType=u)(mail=" . $params['email'] . "))";
951                $ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn'];
952                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['extended_info'])
953                    $extendedinfo=true;
954                else
955                    $extendedinfo=false;
956
957                if($extendedinfo)
958                    $justthese = array("cn","uid","telephoneNumber","jpegPhoto","mobile","ou","employeeNumber");
959                else
960                    $justthese = array("cn","uid","telephoneNumber","jpegPhoto","mobile");
961
962                // Follow the referral
963                $ds = $this->ldapConnect2(true);
964                if ($ds)
965                {
966                        $sr=@ldap_search($ds, $ldap_context, $filter, $justthese);
967
968                        if (!$sr)
969                                return null;
970
971                        $entry = ldap_first_entry($ds, $sr);
972
973                        if($entry) {
974                                $obj =  array("cn" => utf8_decode(current(ldap_get_values($ds, $entry, "cn"))),
975                                                  "email" => $params['email'],
976                                                  "uid" => ldap_get_values($ds, $entry, "uid"),
977                                                  "type" => "global",
978                                                  "mobile" =>  @ldap_get_values($ds, $entry, "mobile"),
979                                                  "telefone" =>  @ldap_get_values($ds, $entry, "telephonenumber"),
980                                                  "ou" =>  @ldap_get_values($ds, $entry, "ou"),
981                                                  "employeeNumber" =>  @ldap_get_values($ds, $entry, "employeeNumber")
982                                        );
983
984                                $_SESSION['phpgw_info']['expressomail']['contact_photo'] = @ldap_get_values_len($ds, $entry, "jpegphoto");
985                                ldap_close($ds);
986                                return $obj;
987                        }
988                }
989                return null;
990        }
991       
992        function uid2uidnumber($uid)
993        {
994                // do not follow the referral
995                $this->ldapRootConnect(false);
996                if ($this->ds)
997                {
998                        $filter="(&(phpgwAccountType=u)(uid=$uid))";
999                        $justthese = array("uidnumber");
1000                        $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
1001                        if(!$sr)
1002                                return false;
1003                        $info = ldap_get_entries($this->ds, $sr);
1004                        return $info[0]["uidnumber"][0];
1005                }
1006                return false;
1007        }
1008       
1009        function get_user_groups($uid)
1010        {
1011
1012                $organizations = array();
1013       
1014                $this->ldapRootConnect();
1015
1016                $justthese = array("gidnumber","cn");
1017                $filter="(&(phpgwAccountType=g)(memberuid=".$uid."))";
1018
1019                $search = ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
1020
1021                $result = array();
1022                $entries = ldap_get_entries($this->ds, $search);
1023
1024
1025                for ($i=0; $i<$entries['count']; $i++)
1026                {
1027                        $result[ $entries[$i]['gidnumber'][0] ] = $entries[$i]['cn'][0];
1028                }
1029
1030                return $result;
1031        }
1032       
1033       function getMailByUid($pUid)
1034        {
1035                // do not follow the referral
1036                $this->ldapRootConnect(false);
1037                if ($this->ds)
1038                {
1039                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s)(phpgwAccountType=l))(uid=$pUid))";
1040                        $justthese = array("mail");
1041                        $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
1042                        if(!$sr)
1043                                return false;
1044                        $info = ldap_get_entries($this->ds, $sr);
1045
1046
1047                        return utf8_decode($info[0]["mail"][0]);
1048                }
1049                return false;
1050        }
1051 
1052        function mail2uid($mail)
1053        {
1054                if(!$this-ds)
1055                    $this->ldapRootConnect(false);
1056
1057                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s)(phpgwAccountType=i)(phpgwAccountType=g))(mail=$mail))";
1058                $justthese = array("uid");
1059                $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
1060                if(!$sr)
1061                    return false;
1062                $info = ldap_get_entries($this->ds, $sr);
1063                return $info[0]["uid"][0];
1064        }
1065
1066       
1067        /**
1068         * Retorna as contas compartilhas
1069         * @param string $toaddress emails
1070         * @param string $ccaddress emails
1071         * @param string $ccoaddress emails
1072         * @param array $groups array com os grupos que o usuario pertence
1073         * @return array
1074         */
1075        function returnSharedsAccounts($toaddress,$ccaddress,$ccoaddress)
1076        {
1077
1078          $arrayAllAddres = array();
1079          $arrayAllAddres =  array_merge($arrayAllAddres , explode(',',$toaddress));
1080          $arrayAllAddres =  array_merge($arrayAllAddres, explode(',',$ccaddress));
1081          $arrayAllAddres = array_merge($arrayAllAddres, explode(',',$ccoaddress));
1082
1083          $mailsArray = array();
1084
1085           foreach ($arrayAllAddres as $toAddres)
1086           {
1087
1088               if(strchr($toAddres,'@') && strchr($toAddres,'<') && strchr($toAddres,'>'))
1089               {
1090                    $alias = substr($toAddres, strpos($toAddres,'<'), strpos($toAddres,'>'));
1091                    $alias = str_replace('<','', str_replace('>','',$alias));
1092                    array_push($mailsArray, $alias);
1093               }
1094               else if(strchr($toAddres,'@'))
1095               {
1096                    array_push($mailsArray, $toAddres);
1097               }
1098           }
1099           $arraySharedAccounts = array();
1100
1101           $conexao = $this->ldapConnect2(true);
1102
1103
1104           $mailFilter = '';
1105
1106           foreach ($mailsArray as $mail)
1107             $mailFilter .= '(|(mail='.$mail.')(mailAlternateAddress='.$mail.'))';
1108
1109
1110           $filter = '(&(phpgwAccountType=s)(|'.$mailFilter.') )';
1111           $ldap_context = $_SESSION['phpgw_info']['expressomail']['server']['ldap_context'];
1112           $justthese = array('cn','uid','mail');
1113
1114           if ($conexao)
1115           {
1116                $search = @ldap_search($conexao, $ldap_context, $filter, $justthese);
1117                if($search)
1118                {
1119                    $results = ldap_get_entries($conexao, $search);
1120
1121                    foreach ($results as $result)
1122                    {
1123                        if($result['mail'][0])
1124                            array_push($arraySharedAccounts, $result['mail'][0]);
1125                    }
1126                }
1127
1128           }
1129
1130           return $arraySharedAccounts;
1131        }
1132        /**
1133        * Verifica se um email é uma conta compartilhada
1134        *
1135        * @license    http://www.gnu.org/copyleft/gpl.html GPL
1136        * @author     Cons?rcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1137        * @author     Cristiano Corrêa Schmidt
1138        * @param      String $mail Email a ser verificado
1139        * @return     bolean
1140        * @access     public
1141        */
1142        function isSharedAccountByMail($mail)
1143        {
1144            $return = false;
1145            $conexao = $this->ldapConnect2(true);
1146            $filter = '(&(phpgwAccountType=s)(mail='.$mail.'))';
1147            $ldap_context = $_SESSION['phpgw_info']['expressomail']['server']['ldap_context'];
1148            $justthese = array('cn','uid','mail');
1149            if ($conexao)
1150            {
1151                $search = @ldap_search($conexao, $ldap_context, $filter, $justthese);
1152                if(ldap_count_entries ($conexao , $search))
1153                    $return = true;
1154            }
1155
1156            return $return;
1157        }
1158}
1159?>
Note: See TracBrowser for help on using the repository browser.