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

Revision 5237, 41.0 KB checked in by gustavo, 12 years ago (diff)

Ticket #2331 - Preferência do ExpressoMail? aparentemente sem efeito

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