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

Revision 5172, 40.2 KB checked in by wmerlotto, 13 years ago (diff)

Ticket #2305 - Enviando alteracoes, desenvolvidas internamente na Prognus. Ultimas sincronizacoes...

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