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

Revision 5134, 40.0 KB checked in by wmerlotto, 12 years ago (diff)

Ticket #2305 - Enviando alteracoes, desenvolvidas internamente na Prognus, do modulo ExpressoMail?.

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