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

Revision 5202, 40.7 KB checked in by gustavo, 12 years ago (diff)

Ticket #2337 - Erro na busca do F9 quando o mesmo nao possue telefone

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