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

Revision 5209, 40.9 KB checked in by gustavo, 12 years ago (diff)

Ticket #2347 - Erro na busca do F9 (Ao utlizar a busca do F9 no catalogo pessoal, não retorna dados. )

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