source: trunk/prototype/services/ImapServiceAdapter.php @ 7673

Revision 7673, 28.4 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

Line 
1<?php
2/**
3 *
4 * Copyright (C) 2012 Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
5 *
6 * This program is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU Affero General Public License version 3 as published by
8 * the Free Software Foundation with the addition of the following permission
9 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
10 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
11 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
12 *
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16 * details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program; if not, see www.gnu.org/licenses or write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 * MA 02110-1301 USA.
22 *
23 * This code is based on the OpenXchange Connector and on the Prognus pSync
24 * Connector both developed by the community and licensed under the GPL
25 * version 2 or above as published by the Free Software Foundation.
26 *
27 * You can contact Prognus Software Livre headquarters at Av. Tancredo Neves,
28 * 6731, PTI, Edifício do Saber, 3º floor, room 306, Foz do Iguaçu - PR - Brasil or at
29 * e-mail address prognus@prognus.com.br.
30 *
31 * Classe de abstração que faz uma adaptação para manipulação de informações
32 * no IMAP a partir de vários métodos.
33 *
34 * @package    Prototype
35 * @license    http://www.gnu.org/copyleft/gpl.html GPL
36 * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
37 * @version    2.4
38 * @sponsor    Caixa Econômica Federal
39 * @since      Arquivo disponibilizado na versão 2.4
40 */
41
42include_once ROOTPATH."/../expressoMail1_2/inc/class.imap_functions.inc.php";
43
44use prototype\api\Config as Config;
45
46/**
47 *
48 * @package    Prototype (Mail)
49 * @license    http://www.gnu.org/copyleft/gpl.html GPL
50 * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
51 * @version    2.4
52 * @sponsor    Caixa Econômica Federal
53 * @since      Classe disponibilizada na versão 2.4
54 */
55class ImapServiceAdapter extends imap_functions/* implements Service*/
56{
57    public function open( $config )
58    {
59                $this->init();
60    }
61
62//     public function connect( $config )
63//     {
64//                      $this->init();
65//     }
66       
67    public function find( $URI, $justthese = false, $criteria = false )
68        {
69
70                $context = isset($justthese['context']) ? $justthese['context'] : '' ;
71
72                switch( $URI['concept'] )
73                {
74                        case 'folder':
75                        {
76                                $result = $this->getFolders();
77
78                                foreach ($result as $res) {
79
80                                        //monta o array padrao
81                                        $array = array(
82                                                        'id' => mb_convert_encoding( $res['folder_id'], 'UTF-8', 'UTF7-IMAP' ),
83                                                        'commonName' => mb_convert_encoding( $res['folder_name'], 'UTF-8' , 'UTF7-IMAP' ),
84                                                        'parentFolder' => mb_convert_encoding( $res['folder_parent'], 'UTF-8' , 'UTF7-IMAP' ),
85                                                        'messageCount' => array('unseen' => isset($res['folder_unseen']) ? $res['folder_unseen'] : null, 'total' => null)
86                                        );
87
88                                        //se existir compartilhamento para pasta compartilhada
89                                        //adicionar array de permissoes
90                                        if(isset($res['acl_share'])){
91                                                $array['acl_share'] = $res['acl_share'];
92                                        }
93                                        $response[] = $array;
94                                }
95                                return $response;
96                        }
97                        case 'message':
98                        {
99                                //begin: for grid       
100                                $page  = isset($criteria['page']) ? $criteria['page'] : 1 ; //{1}    get the requested page
101                                $limit = isset($criteria['rows']) ? $criteria['rows'] : 10 ; //{10}   get how many rows we want to have into the grid
102                                $sidx  = isset($criteria['sidx']) ? $criteria['sidx'] : 0; //{id}   get index row - i.e. user click to sort
103                                $sord  = isset($criteria['sord']) ? $criteria['sord'] : ''; //{desc} get the direction
104
105                                $filter =  isset($criteria['filter']) ? $criteria['filter'] : '';
106
107                                if( !$sidx ) $sidx = 1;
108
109                                $folder_name =  isset($URI['folder']) ?  $URI['folder'] : str_replace( '.', $this->imap_delimiter, isset($context['folder']) ?  $context['folder'] : 'INBOX');
110                       
111                                $count = imap_num_msg( $this->open_mbox( $folder_name ) );
112
113                                $total_pages = $count > 0 ? ceil( $count/$limit ) : 0;
114
115                                if( $page > $total_pages )
116                                        $page = $total_pages;
117
118                                $start = $limit * $page - $limit;
119                                // do not put $limit*($page - 1)
120                                //end: for grid
121                               
122                               
123                                /**
124                                 * Trata o caso específico de retorno do atributo messageId
125                                 *
126                                 * TODO - refazer todo a operação find do conceito message, uma vez que esta
127                                 * foi desenvolvida quando a nova API ainda era muito imatura e se encontra
128                                 * muito acoplada à estrutura de retorno esperada pelo plugin jqGrid
129                                 */
130                                if ( $justthese )
131                                {
132                                        if (isset($justthese[0]) && $justthese[0] == 'messageId') {
133                                                $map = array(
134                                                        'folderName' => array(),
135                                                        'messageNumber' => array()
136                                                );
137                                               
138                                                self::parseFilter($criteria["filter"], &$map);
139                                               
140                                                if (count($map['folderName']) == 0) {
141                                                        $folders = $this->get_folders_list();
142                                                        foreach ($folders as $folder)
143                                                                if (isset($folder['folder_id']))
144                                                                        $map['folderName'][] = $folder['folder_id'];
145                                                }
146                                               
147                                                $result = array();
148                                                foreach ($map['folderName'] as $folder) {
149                                                        $this->mbox = $this->open_mbox($folder);
150
151                                                        /**
152                                                         * Se não foi passado messageNumber no filtro,
153                                                         * busca todas as mensagens de cada pasta
154                                                         */
155                                                        $messages = empty($map['messageNumber']) ? '1:*' : implode(',', $map['messageNumber']);
156                                                        $sequenceType = empty($map['messageNumber']) ? 0 : FT_UID;
157
158                                                        $headers = imap_fetch_overview($this->mbox, $messages, $sequenceType);
159                                                        foreach ($headers as $h) {
160                                                                if(isset($h->message_id ))
161                                                                        $result[] = array ( 'messageId' => $h->message_id );
162                                                        }
163       
164                                                }
165                                                return $result;
166                                        }
167                                }
168                               
169                                if( $filter )
170                                {
171                                        if( $filter[0] !== 'msgNumber' )
172                                        {
173                        $filter_count = count($filter);
174                        for( $i = 0; $i < $filter_count; ++$i )
175                        {
176                            if( count( $filter[$i] ) === 4 )
177                            $criteria['isExact'] = ( array_shift( $filter[$i] ) === 'AND' );
178
179                            $criteria[ $filter[$i][0] ] = array( 'criteria' => $filter[$i][2], 'filter' => $filter[$i][1] );
180                        }
181
182                        return $this->searchSieveRule($criteria);
183                                        }
184
185                                        $msgNumber = array();
186
187                                        for( $i = $start; $i < $start + $limit && isset( $filter[2][$i] ); ++$i )
188                                          $msgNumber[] = $filter[2][$i];
189
190                                        if( empty( $msgNumber ) )
191                                            return( false );
192
193                                        $result = $this->get_info_msgs( array( 'folder' => $folder_name,
194                                                                           'msgs_number' => implode( ',', $msgNumber ) ) );
195
196                                        foreach( $result as $i => $val )
197                                        $result[$i] = unserialize( $val );
198
199                                }
200                                else
201                                {
202                                        $result = $this->get_range_msgs2(
203                                                array(
204                                                        'folder' => $folder_name, //INBOX
205                                                        'msg_range_begin' => $start + 1, //??
206                                                        'msg_range_end' => $start + $limit, //$limit = $_GET['rows']; // get how many rows we want to have into the grid
207                                                        'sort_box_type' => 'SORTARRIVAL',
208                                                        'search_box_type' => 'ALL',
209                                                        'sort_box_reverse' => 1
210                                                )
211                                        );
212                                }
213                                //return var_export($result);
214
215                                $response = array( "page" => $page, "total" => $total_pages, "records" => $count );
216                                $result_count = count($result);
217                                for ($i=0; $i<$result_count; ++$i)
218                                {
219                                        $flags_enum = array('Unseen'=> 1,  'Answered'=> 1, 'Forwarded'=> 1, 'Flagged'=> 1, 'Recent'=> 1, 'Draft'=> 1 );
220
221                                        foreach ($flags_enum as $key => $flag)
222                                        {
223                                                if ( !isset($result[$i][$key]) || !trim($result[$i][$key]) || trim($result[$i][$key]) == '') 
224                                                        $flags_enum[$key] = 0;
225
226                                                unset($result[$i][$flag]);
227                                        }
228
229                                        if (array_key_exists($i, $result))
230                                        {
231                                                $response["rows"][$i] = $result[$i];
232                                                $response["rows"][$i]['timestamp'] = $result[$i]['udate'] * 1000;
233                                                $response["rows"][$i]['flags'] = implode(',', $flags_enum);
234                                                $response["rows"][$i]['size'] = $response["rows"][$i]['Size'];
235                                                $response["rows"][$i]['folder'] = $folder_name;
236                                                //$response["rows"][$i]['udate'] = ( $result[$i]['udate'] + $this->functions->CalculateDateOffset()  * 1000 );
237                                                unset($response["rows"][$i]['Size']);
238                                        }
239                                 }
240
241                                return $this->to_utf8($response);
242                        }
243                       
244                        /**
245                         * Filtros suportados:
246                         * - ['=', 'folderName', $X]
247                         * - [
248                         *              'AND',
249                         *              [
250                         *                      'AND',
251                         *                      ['=', 'folderName', $X],
252                         *                      ['IN', 'messageNumber', $Ys]
253                         *              ],
254                         *              ['IN', 'labelId', $Zs]
255                         * ]
256                         * - ['=', 'labelId', $X]
257                         * - [
258                         *              'AND',
259                         *              ['=', 'folderName', $X],
260                         *              ['=', 'labelId', $Y]
261                         * ]
262                         * - ['IN', 'labelId', $Ys]
263                         * - [
264                         *              'AND',
265                         *              ['=', 'folderName', $X],
266                         *              ['IN', 'labelId', $Ys]
267                         * ]                   
268                         */
269                        case 'labeled':
270                        {
271                                $result = array ( );
272                                if (isset($criteria["filter"]) && is_array($criteria['filter'])) {
273                                        //TODO - melhorar o tratamento do filter com a lista de todos os labelIds dado pelo interceptor
274                                        $map = array(
275                                                'id' => array(),
276                                                'folderName' => array(),
277                                                'messageNumber' => array(),
278                                                'labelId' => array()
279                                        );
280                                       
281                                        self::parseFilter($criteria["filter"], &$map);
282                                       
283                                        if (count($map['folderName']) == 0) {
284                                                $folders = $this->get_folders_list();
285                                                foreach ($folders as $folder)
286                                                        if (isset($folder['folder_id']))
287                                                                $map['folderName'][] = $folder['folder_id'];
288                                        }
289
290                                        foreach ($map['folderName'] as $folder) {
291                                                $this->mbox = $this->open_mbox($folder);
292                                               
293                                                foreach ($map['labelId'] as $label) {
294                                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$label.'"', SE_UID);
295                                                       
296                                                        if(is_array($messagesLabeleds))
297                                                        foreach ($messagesLabeleds as $messageLabeled) {
298                                                                if (count($map['messageNumber']) > 0 && !in_array($messageLabeled, $map['messageNumber']))
299                                                                        continue;
300                                                                       
301                                                                $result[] = array (
302                                                                        'id' => $folder . '/' . $messageLabeled . '#' . $label,
303                                                                        'folderName' => $folder,
304                                                                        'messageNumber' => $messageLabeled,
305                                                                        'labelId' => $label
306                                                                );
307                                                        }
308                                                }
309
310                                        }
311                                }
312                               
313                                return $result;
314                        }
315                       
316                        case 'followupflagged':
317                        {                                       
318                                $result = array ( );
319
320                                $map = array(
321                                        //'id' => array(),
322                                        'folderName' => array(),
323                                        'messageNumber' => array(),
324                                        'messageId' => array()
325                                );
326                               
327                                self::parseFilter($criteria["filter"], &$map);
328       
329                                if (empty($map['folderName'])) {
330                                        $folders = $this->get_folders_list();
331                                        foreach ($folders as $folder)
332                                                if (isset($folder['folder_id']))
333                                                        $map['folderName'][] = $folder['folder_id'];
334                                }
335                               
336                                $messagesIds = $map['messageId'];
337
338                                foreach ($map['folderName'] as $folder) {
339                                        $messages = array();
340                                       
341                                        $this->mbox = $this->open_mbox($folder);
342
343                                        /**
344                                         * Se é uma busca por messageId
345                                         */
346                                        if (!empty($map['messageId'])) {
347                                                       
348                                                foreach ($messagesIds as $k => $v) {
349
350                                                        $r = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged" TEXT "Message-Id: '.$v.'"', SE_UID);
351
352                                                        if ($r) {
353
354                                                                $messages = array_merge($messages, $r);
355                                                                unset($messagesIds[$k]);
356                                                               
357                                                        }
358                                                }
359
360                                        /**
361                                         * Se é uma busca por messageNumber.
362                                         * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
363                                         */
364                                        } else {
365                                                $messages = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged"', SE_UID);
366                                        }
367
368                                        /**
369                                         * Se é uma busca por messageId, deve ser comparado com os messageNumbers
370                                         * passados no filtro, se houverem.
371                                         */
372                                        if (!empty($map['messageNumber']) && is_array($messages)) {
373                                                                                               
374                                                foreach ($messages as $k => $m)
375                                                        if (!in_array($m, $map['messageNumber']))
376                                                                unset($messages[$k]);
377                                        }
378
379                                        /**
380                                         * Adicionar demais atributos às mensagens para retorno
381                                         */
382                                        if(is_array($messages))
383                                        foreach ($messages as $k => $m) {
384                                                $headers = imap_fetch_overview($this->mbox, $m, FT_UID);
385
386                                                $result[] = array (
387                                                        'messageId' => $headers[0]->message_id,
388                                                        'messageNumber' => $m,
389                                                        'folderName' => $folder
390                                                );
391                                        }
392
393                                       
394                                        /**
395                                         * Se é uma busca por messageId e todos os messageIds foram econstrados:
396                                         * Stop searching in all folders
397                                         */
398                                        if (!empty($map['messageId']) && empty($messagesIds))
399                                                break;
400                                }
401                               
402
403                                return $result;
404                               
405                        } //CASE 'followupflag'
406                }
407    }
408
409    public function read( $URI, $justthese = false )
410    {
411
412                switch( $URI['concept'] )
413                {
414                        case 'message':
415                        {       
416                                return $this->to_utf8(
417                                        $this->get_info_msg( array('msg_number'=>$URI['id'],
418                                        'msg_folder'=>str_replace( '.', $this->imap_delimiter, $justthese['context']['folder'] ) ,
419                                        'decoded' => true ) )
420                                );
421                        }
422                        case 'labeled':
423                        {
424                                /**
425                                 * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#labelId
426                                 */
427                                list($messageId, $labelId) = explode('#', $URI['id']);
428                                $folderName = basename($messageId);
429                                $messageNumber = dirname($messageId);
430                               
431                                $result = array();
432
433                                if ($folderName && $messageNumber && $labelId) {
434                                        $this->mbox = $this->open_mbox($folderName);
435                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$labelId.'"', SE_UID);
436                                       
437                                        if (in_array($messageNumber, $messagesLabeleds)) {
438                                                $result = array (
439                                                        'id' => $URI['id'],
440                                                        'folderName' => $folderName,
441                                                        'messageNumber' => $messageNumber,
442                                                        'labelId' => $labelId
443                                                );
444                                        }
445
446                                }
447                               
448                                return $result;
449                        }
450                       
451                        case 'followupflagged':
452                        {
453                       
454                                /**
455                                 * identifica se o formato de ID é "folder/subfolder/subsubfolder/<messageNumber>" ou "<message-id>"
456                                 */
457                                $folderName = $messageNumber = false;
458                                if(!($messageHasId = preg_match('/<.*>/', $URI['id']))) {
459                                        $folderName = dirname($URI['id']);
460                                        $messageNumber = basename($URI['id']);
461                                }
462
463                                $result = array();
464                                if ($folderName && $messageNumber) {
465
466                                        $this->mbox = $this->open_mbox($folderName);
467                                        $r = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged"', SE_UID);
468
469                                        if (in_array($messageNumber, $r)) {
470                                                $headers = imap_fetch_overview($this->mbox, $messageNumber, FT_UID);
471                                                       
472                                                $result = array (
473                                                        'messageId' => $headers[0]->message_id,
474                                                        'messageNumber' => $messageNumber,
475                                                        'folderName' => $folderName
476                                                );
477                                        }
478                               
479                                } else {
480                                        /**
481                                         * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
482                                         * senão busca em todas.
483                                         */
484                                       
485                                        $folders = array ();
486                                        if ($folderName) {
487                                                $folders = array ($folderName);
488                                        } else {
489                                                $folder_list = $this->get_folders_list();
490                                                foreach ($folder_list as $folder)
491                                                        if (isset($folder['folder_id']))
492                                                                $folders[] = $folder['folder_id'];
493                                        }
494                                       
495                                        foreach ($folders as $folder) {
496                                               
497                                                $this->mbox = $this->open_mbox($folder);
498                                               
499                                                if ($messages = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged" TEXT "Message-Id: '.$URI['id'].'"', SE_UID)) {
500                               
501                                                        $result = array (
502                                                                'messageId' => $URI['id'],
503                                                                'messageNumber' => $messages[0],
504                                                                'folderName' => $folder
505                                                        );
506                                                       
507                                                        /**
508                                                         * Stop searching in all folders
509                                                         */
510                                                        break;
511                                                }
512       
513                                        }
514                                }
515                               
516                               
517                                return $result;
518                        }
519                }
520    }
521
522    public function create($URI, &$data)
523    {               
524                switch( $URI['concept'] )
525                {
526                        case 'labeled':
527                        {
528                                if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['labelId'])) {
529                                        $this->mbox = $this->open_mbox($data['folderName']);
530                                        imap_setflag_full($this->mbox, $data['messageNumber'], '$Label' . $data['labelId'], ST_UID);
531
532                                        return array ('id' => $data['folderName'].'/'.$data['messageNumber'].'#'.$data['labelId']);
533                                }
534                                return array ();
535                        }
536                        case 'followupflagged':
537                        {
538                                //deve ser gravado primeiro no imap, obtido o message-id e, depois gravado no banco
539                               
540                                if (isset($data['folderName']) && isset($data['messageNumber'])) {
541                                       
542                                        $this->mbox = $this->open_mbox($data['folderName']);
543                                        $s = imap_setflag_full($this->mbox, $data['messageNumber'], '$Followupflagged', ST_UID);
544                                       
545                                        $headers = imap_fetch_overview($this->mbox, $data['messageNumber'], FT_UID);
546                                       
547                                        $data['messageId'] = $headers[0]->message_id;
548                                       
549                                        /*
550                                         * TODO
551                                         * Verificar erro ao tentar setar uma flag com o limite de flags atingido
552                                         * onde o status retornado pelo imap_setflag_full é true mesmo não sendo possível
553                                         * a inserção da flag.
554                                         */
555
556                                        return (($s) && (imap_last_error() != 'Too many user flags in mailbox')) ? $data : array();
557
558                                } else if (isset($data['messageId'])) {
559                                        /**
560                                         * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
561                                         * senão busca em todas.
562                                         */
563                                        $folders = array ();
564                                        if (isset($data['folderName'])) {
565                                                $folders = array ($data['folderName']);
566                                        } else {
567                                                $folder_list = $this->get_folders_list();
568                                                foreach ($folder_list as $folder)
569                                                        if (isset($folder['folder_id']))
570                                                                $folders[] = $folder['folder_id'];
571                                        }
572                                       
573                                        foreach ($folders as $folder) {
574                                               
575                                                $this->mbox = $this->open_mbox($folder);
576                                                if ($messages = imap_search($this->mbox, 'ALL TEXT "Message-Id: '.$data['messageId'].'"', SE_UID)) {
577                                                       
578                                                        $s = imap_setflag_full($this->mbox, $messages[0], '$Followupflagged', ST_UID);
579                                               
580                                                        /**
581                                                         * Stop searching in all folders
582                                                         */
583                                                        return $data;
584                                                }
585                                               
586                                        }
587                                }
588                                return array ();
589                        }
590                       
591                        case 'message':
592                        {
593                                require_once ROOTPATH.'/library/uuid/class.uuid.php';
594                               
595                                $GLOBALS['phpgw_info']['flags'] = array( 'noheader' => true, 'nonavbar' => true,'currentapp' => 'expressoMail1_2','enable_nextmatchs_class' => True );
596                                $return = array();
597
598                                require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
599                                $mailService = ServiceLocator::getService('mail');
600
601                                $msg_uid = $data['msg_id'];
602                                $body = $data['body'];
603                                $body = str_replace("&lt;","&yzwkx;",$body); //Alterar as Entities padrão das tags < > para compatibilizar com o Expresso
604                                $body = str_replace("&gt;","&xzwky;",$body);
605                                $body = str_replace("%nbsp;","&nbsp;",$body);
606                                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );               
607                                $body = str_replace("&yzwkx;","&lt;",$body);
608                                $body = str_replace("&xzwky;","&gt;",$body);                           
609
610                                $folder = mb_convert_encoding($data['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
611                                $folder = @preg_replace('/INBOX[\/.]/i', "INBOX".$this->imap_delimiter, $folder);
612
613                                /**
614                                * Gera e preenche o field Message-Id do header
615                                */
616                                $mailService->addHeaderField('Message-Id', UUID::generate( UUID::UUID_RANDOM, UUID::FMT_STRING ) . '@Draft');
617                $mailService->addHeaderField('Reply-To', mb_convert_encoding(($data['input_reply_to']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
618                $mailService->addHeaderField('Date', date("d-M-Y H:i:s"));
619                                $mailService->addTo(mb_convert_encoding(($data['input_to']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
620                                $mailService->addCc( mb_convert_encoding(($data['input_cc']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
621                                $mailService->addBcc(mb_convert_encoding(($data['input_cco']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
622                                $mailService->setSubject(mb_convert_encoding(($data['input_subject']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
623                               
624                                if(isset($data['input_important_message']))
625                                        $mailService->addHeaderField('Importance','High');
626
627                                if(isset($data['input_return_receipt']))
628                                        $mailService->addHeaderField('Disposition-Notification-To', Config::me('mail'));
629
630                                $this->rfc2397ToEmbeddedAttachment($mailService , $body);
631
632                                $isHTML = ( isset($data['type']) && $data['type'] == 'html' )?  true : false;
633
634                                if (!$body) $body = ' ';
635
636
637                                $mbox_stream = $this->open_mbox($folder);
638
639                                $attachment = json_decode($data['attachments'],TRUE);
640
641                if(!empty($attachment))
642                                foreach ($attachment as &$value)
643                                {
644                                        if((int)$value > 0) //BD attachment
645                                        {
646                                                $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment'));
647
648                                                if($att['disposition'] == 'embedded' && $isHTML) //Caso mensagem em texto simples converter os embedded para attachments
649                                                {
650                                                        $body = str_replace('"../prototype/getArchive.php?mailAttachment='.$att['id'].'"', '"'.mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1').'"', $body);
651                                                        $mailService->addStringImage(base64_decode($att['source']), $att['type'], mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1'));
652                                                }
653                                                else
654                                                        $mailService->addStringAttachment(base64_decode($att['source']), mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
655
656                                                unset($att);
657                                        }
658                                        else
659                                        {
660                                                $value = json_decode($value, true);
661                                               
662                                                switch ($value['type']) {
663                                                        case 'imapPart':
664                                                                $att = $this->getForwardingAttachment($value['folder'],$value['uid'], $value['part']);
665                                                                if(strstr($body,'src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"') !== false)//Embeded IMG
666                                                                {   
667                                                                        $body = str_ireplace('src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"' , 'src="'.$att['name'].'"', $body);
668                                                                        $mailService->addStringImage($att['source'], $att['type'], mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1'));
669                                                                }
670                                                                else
671                                                                        $mailService->addStringAttachment($att['source'], mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
672                                                                unset($att);
673                                                                break;
674                                                        case 'imapMSG':
675                                                                $mbox_stream = $this->open_mbox($value['folder']);
676                                                                $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']);
677                                                                $mailService->addStringAttachment($rawmsg, mb_convert_encoding(base64_decode($value['name']), 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), 'message/rfc822', '7bit', 'attachment' );
678                                                                unset($rawmsg);
679                                                                break;
680
681                                                        default:
682                                                        break;
683                                                }
684                                        }
685
686                                }
687
688                                if($isHTML) $mailService->setBodyHtml($body); else $mailService->setBodyText(mb_convert_encoding($body, 'ISO-8859-1' , 'UTF-8,ISO-8859-1' ));
689
690                                if(imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft"))
691                                {
692                                        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
693                                        $return['id'] = $status->uidnext - 1;
694
695                                        if($data['uidsSave'] )
696                                                $this->delete_msgs(array('folder'=> $folder , 'msgs_number' => $data['uidsSave']));
697                                }
698
699                                return $return;
700                        }
701                }
702        }
703
704    public function delete( $URI, $justthese = false, $criteria = false )
705    {
706                switch( $URI['concept'] )
707                {
708                        case 'labeled':
709                        {
710                                list($messageId, $labelId) = explode('#', $URI['id']);
711                                $folderName = dirname($messageId);
712                                $messageNumber = basename($messageId);
713
714                                if ($folderName && $messageNumber && $labelId) {
715                                        $this->mbox = $this->open_mbox($folderName);
716                                        imap_clearflag_full($this->mbox, $messageNumber, '$Label' . $labelId, ST_UID);
717
718                                }
719                        }
720                        case 'followupflagged':
721                        {
722                                $map = array(
723                                        'folderName' => array(),
724                                        'messageNumber' => array(),
725                                        'messageId' => array()
726                                );
727                               
728                                self::parseFilter($criteria["filter"], &$map);
729                               
730                                if (!$map['folderName']) {
731                                        $folders = array ();
732                                       
733                                        $folder_list = $this->get_folders_list();
734                                        foreach ($folder_list as $folder)
735                                                if (isset($folder['folder_id']))
736                                                        $folders[] = $folder['folder_id'];
737                                        $map['folderName'] = $folders;
738                                }
739
740                                $messagesIds = $map['messageId'];
741
742                                foreach ($map['folderName'] as $folder) {
743                                        $messages = array();
744                                       
745                                        $this->mbox = $this->open_mbox($folder);
746                               
747                                        /**
748                                         * Se é uma busca por messageId
749                                         */
750                                        if (!empty($map['messageId'])) {
751                                                       
752                                                foreach ($messagesIds as $k => $v) {
753                                                        $r = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged" TEXT "Message-Id: '.$v.'"', SE_UID);
754
755                                                        if ($r) {
756                                                                $messages = $messages + $r;
757                                                                unset($messagesIds[$k]);       
758                                                        }
759                                                }
760
761                                        /**
762                                         * Se é uma busca por messageNumber.
763                                         * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
764                                         */
765                                        } else {
766                                                $messages = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged"', SE_UID);
767                                        }
768
769                                        /**
770                                         * Se é uma busca por messageId, deve ser comparado com os messageNumbers
771                                         * passados no filtro, se houverem.
772                                         */
773                                        if (!empty($map['messageNumber'])) {
774                                                foreach ($messages as $k => $m)
775                                                        if (!in_array($m, $map['messageNumber']))
776                                                                unset($messages[$k]);
777                                        }
778
779                                        $s = true;
780                                        foreach ($messages as $k => $m) {                                               
781                                                $s = imap_clearflag_full($this->mbox, $m, '$Followupflagged', ST_UID) && $s;
782                                        }
783
784                                        /**
785                                         * Se é uma busca por messageId e todos os messageIds foram econstrados:
786                                         * Stop searching in all folders
787                                         */
788                                        if (!empty($map['messageId']) && empty($messagesIds))
789                                                break;
790                                }
791                               
792                                return $s;
793                        }
794                }
795
796                //TODO - return
797        }
798
799    public function deleteAll( $URI, $justthese = false, $criteria = false )
800    {
801                $op = $criteria['filter'][0];
802                $ids = $criteria['filter'][2];
803                if($op == 'IN'){
804                        foreach ($ids as $id){
805                                self::delete( array( 'concept' => $URI['concept'], 'id' => $id), false, false);
806                        }
807                }
808
809                /**
810                 * TODO - implementar a deleção de todos os followupflaggeds conforme filtro
811                 */
812        }
813
814    public function update( $URI, $data, $criteria = false )
815    {
816                /**
817                 * Os únicos atributos da sinalização presentes no IMAP são folderName, messageNumber e messageId,
818                 * porém a operação de update desses atributos não faz sentido para o usuário da DataLayer,
819                 * pois na prática elas são executadas através das operações de CREATE e DELETE.
820                 * Assim, para os conceitos "labeled" e "followupflagged", só faz sentido o update de
821                 * atributos gravados no banco de dados e nunca no IMAP.
822                 */
823        }
824
825//     public function retrieve( $concept, $id, $parents, $justthese = false, $criteria = false )
826//     {
827//                      return $this->read( array( 'id' => $id,
828//                          'concept' => $concept,
829//                          'context' => $parents ), $justthese );
830//     }
831
832    public function replace( $URI, $data, $criteria = false )
833    {}
834
835    public function close()
836    {}
837
838    public function setup()
839    {}
840
841    public function commit( $uri )
842    { return( true ); }
843
844    public function rollback( $uri )
845    {}
846
847    public function begin( $uri )
848    {}
849
850
851    public function teardown()
852    {}
853
854    function to_utf8($in)
855    {
856                if (is_array($in)) {
857                        foreach ($in as $key => $value) {
858                                $out[$this->to_utf8($key)] = $this->to_utf8($value);
859                        }
860                } elseif(is_string($in)) {
861                                return mb_convert_encoding( $in , 'UTF-8' , 'UTF-8 , ISO-8859-1' );
862                } else {
863                        return $in;
864                }
865                return $out;
866    }
867       
868           
869    private static function parseFilter($filter ,&$map){
870               
871                if( !is_array( $filter ) || count($filter) <= 0) return null;
872                                       
873                $op = array_shift( $filter );
874                switch(strtolower($op))
875                {
876                        case 'and': {
877                                foreach ($filter as $term)
878                                        self::parseFilter($term ,&$map);
879                                return;
880                        }
881                        case 'in': {
882                                if(is_array($map[$filter[0]]) && is_array($filter[1]))
883                                        $map[$filter[0]] = array_unique(array_merge($map[$filter[0]], $filter[1]));
884                                return;
885                        }
886                        case '=': {
887                                $map[$filter[0]][] = $filter[1];
888                        }
889                }
890        }
891
892}
Note: See TracBrowser for help on using the repository browser.