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

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