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

Revision 6115, 25.7 KB checked in by marcosw, 12 years ago (diff)

Ticket #2697 - Inserir informações de copyright em cabeçalho de arquivos

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
44class ImapServiceAdapter extends imap_functions/* implements Service*/
45{
46    public function open( $config )
47    {
48                $this->init();
49    }
50
51//     public function connect( $config )
52//     {
53//                      $this->init();
54//     }
55       
56    public function find( $URI, $justthese = false, $criteria = false )
57        {
58       
59                $context = $justthese['context'];
60                $URI = $URI['concept'];
61
62                switch( $URI )
63                {
64                        case 'folder':
65                        {
66                                $result = $this->to_utf8($this->get_folders_list());
67
68                                foreach ($result as $res) {
69
70                                        $response[] = array(
71                                                        'id' => $res['folder_id'],
72                                                        'commonName' => $res['folder_name'],
73                                                        'parentFolder' => $res['folder_parent'],
74                                                        'messageCount' => array('unseen' => isset($res['folder_unseen']) ? $res['folder_unseen'] : null, 'total' => null)
75                                                );
76                                }
77
78                                return $response;
79                        }
80                        case 'message':
81                        {
82                                //begin: for grid       
83                                $page  = $criteria['page']; //{1}    get the requested page
84                                $limit = $criteria['rows']; //{10}   get how many rows we want to have into the grid
85                                $sidx  = $criteria['sidx']; //{id}   get index row - i.e. user click to sort
86                                $sord  = $criteria['sord']; //{desc} get the direction
87
88                                $filter = $criteria['filter'];
89
90                                if( !$sidx ) $sidx = 1;
91
92                                $folder_name = str_replace( '.', $this->imap_delimiter, $context['folder'] );
93                               
94                                $count = imap_num_msg( $this->open_mbox( $folder_name ) );
95
96                                $total_pages = $count > 0 ? ceil( $count/$limit ) : 0;
97
98                                if( $page > $total_pages )
99                                        $page = $total_pages;
100
101                                $start = $limit * $page - $limit;
102                                // do not put $limit*($page - 1)
103                                //end: for grid
104                               
105                               
106                                /**
107                                 * Trata o caso específico de retorno do atributo messageId
108                                 *
109                                 * TODO - refazer todo a operação find do conceito message, uma vez que esta
110                                 * foi desenvolvida quando a nova API ainda era muito imatura e se encontra
111                                 * muito acoplada à estrutura de retorno esperada pelo plugin jqGrid
112                                 */
113                                if ( $justthese )
114                                {
115                                        if ($justthese[0] == 'messageId') {
116                                                $map = array(
117                                                        'folderName' => array(),
118                                                        'messageNumber' => array()
119                                                );
120                                               
121                                                self::parseFilter($criteria["filter"], &$map);
122                                               
123                                                if (count($map['folderName']) == 0) {
124                                                        $folders = $this->get_folders_list();
125                                                        foreach ($folders as $folder)
126                                                                if (isset($folder['folder_id']))
127                                                                        $map['folderName'][] = $folder['folder_id'];
128                                                }
129                                               
130                                                $result = array();
131                                                foreach ($map['folderName'] as $folder) {
132                                                        $this->mbox = $this->open_mbox($folder);
133
134                                                        /**
135                                                         * Se não foi passado messageNumber no filtro,
136                                                         * busca todas as mensagens de cada pasta
137                                                         */
138                                                        $messages = empty($map['messageNumber']) ? '1:*' : implode(',', $map['messageNumber']);
139                                                        $sequenceType = empty($map['messageNumber']) ? 0 : FT_UID;
140
141                                                        $headers = imap_fetch_overview($this->mbox, $messages, $sequenceType);
142                                                        foreach ($headers as $h) {
143                                                                $result[] = array ( 'messageId' => $h->message_id );
144                                                        }
145                                                                                                               
146                                                        imap_close($this->mbox);
147                                                        $this->mbox = false;
148                                                }
149                                                return $result;
150                                        }
151                                }
152                               
153                                if( $filter )
154                                {
155                                        if( $filter[0] !== 'msgNumber' )
156                                        {
157                                        for( $i = 0; $i < count($filter); $i++ )
158                                        {
159                                                if( count( $filter[$i] ) === 4 )
160                                                $criteria['isExact'] = ( array_shift( $filter[$i] ) === 'AND' );
161
162                                                $criteria[ $filter[$i][0] ] = array( 'criteria' => $filter[$i][2], 'filter' => $filter[$i][1] );
163                                        }
164
165                                        return $this->searchSieveRule($criteria);
166                                        }
167
168                                        $msgNumber = array();
169
170                                        for( $i = $start; $i < $start + $limit && isset( $filter[2][$i] ); $i++ )
171                                          $msgNumber[] = $filter[2][$i];
172
173                                        if( empty( $msgNumber ) )
174                                        return( false );
175
176                                        $result = $this->get_info_msgs( array( 'folder' => $folder_name,
177                                                                           'msgs_number' => implode( ',', $msgNumber ) ) );
178
179                                        foreach( $result as $i => $val )
180                                        $result[$i] = unserialize( $val );
181
182                                }
183                                else
184                                {
185                                        $result = $this->get_range_msgs2(
186                                                array(
187                                                        'folder' => $folder_name, //INBOX
188                                                        'msg_range_begin' => $start + 1, //??
189                                                        'msg_range_end' => $start + $limit, //$limit = $_GET['rows']; // get how many rows we want to have into the grid
190                                                        'sort_box_type' => 'SORTARRIVAL',
191                                                        'search_box_type' => 'ALL',
192                                                        'sort_box_reverse' => 1
193                                                )
194                                        );
195                                }
196                                //return var_export($result);
197
198                                $response = array( "page" => $page, "total" => $total_pages, "records" => $count );
199                               
200                                for ($i=0; $i<count($result); $i++)
201                                {
202                                        $flags_enum = array('Unseen'=> 1,  'Answered'=> 1, 'Forwarded'=> 1, 'Flagged'=> 1, 'Recent'=> 1, 'Draft'=> 1 );
203
204                                        foreach ($flags_enum as $key => $flag)
205                                        {
206                                                if ( !isset($result[$i][$key]) || !trim($result[$i][$key]) || trim($result[$i][$key]) == '') 
207                                                        $flags_enum[$key] = 0;
208
209                                                unset($result[$i][$flag]);
210                                        }
211
212                                        if (array_key_exists($i, $result))
213                                        {
214                                                $response["rows"][$i] = $result[$i];
215                                                $response["rows"][$i]['timestamp'] = ( ( $result[$i]['udate'] + $this->functions->CalculateDateOffset() ) * 1000 );
216                                                $response["rows"][$i]['flags'] = implode(',', $flags_enum);
217                                                $response["rows"][$i]['size'] = $response["rows"][$i]['Size'];
218                                                $response["rows"][$i]['folder'] = $folder_name;
219                                                //$response["rows"][$i]['udate'] = ( $result[$i]['udate'] + $this->functions->CalculateDateOffset()  * 1000 );
220                                                unset($response["rows"][$i]['Size']);
221                                        }
222                                 }
223
224                                return $this->to_utf8($response);
225                        }
226                       
227                        /**
228                         * Filtros suportados:
229                         * - ['=', 'folderName', $X]
230                         * - [
231                         *              'AND',
232                         *              [
233                         *                      'AND',
234                         *                      ['=', 'folderName', $X],
235                         *                      ['IN', 'messageNumber', $Ys]
236                         *              ],
237                         *              ['IN', 'labelId', $Zs]
238                         * ]
239                         * - ['=', 'labelId', $X]
240                         * - [
241                         *              'AND',
242                         *              ['=', 'folderName', $X],
243                         *              ['=', 'labelId', $Y]
244                         * ]
245                         * - ['IN', 'labelId', $Ys]
246                         * - [
247                         *              'AND',
248                         *              ['=', 'folderName', $X],
249                         *              ['IN', 'labelId', $Ys]
250                         * ]                   
251                         */
252                        case 'labeled':
253                        {
254                                $result = array ( );
255                                if (isset($criteria["filter"]) && is_array($criteria['filter'])) {
256                                        //TODO - melhorar o tratamento do filter com a lista de todos os labelIds dado pelo interceptor
257                                        $map = array(
258                                                'id' => array(),
259                                                'folderName' => array(),
260                                                'messageNumber' => array(),
261                                                'labelId' => array()
262                                        );
263                                       
264                                        self::parseFilter($criteria["filter"], &$map);
265                                       
266                                        if (count($map['folderName']) == 0) {
267                                                $folders = $this->get_folders_list();
268                                                foreach ($folders as $folder)
269                                                        if (isset($folder['folder_id']))
270                                                                $map['folderName'][] = $folder['folder_id'];
271                                        }
272
273                                        foreach ($map['folderName'] as $folder) {
274                                                $this->mbox = $this->open_mbox($folder);
275                                               
276                                                foreach ($map['labelId'] as $label) {
277                                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$label.'"', SE_UID);
278                                                       
279                                                        foreach ($messagesLabeleds as $messageLabeled) {
280                                                                if (count($map['messageNumber']) > 0 && !in_array($messageLabeled, $map['messageNumber']))
281                                                                        continue;
282                                                                       
283                                                                $result[] = array (
284                                                                        'id' => $folder . '/' . $messageLabeled . '#' . $label,
285                                                                        'folderName' => $folder,
286                                                                        'messageNumber' => $messageLabeled,
287                                                                        'labelId' => $label
288                                                                );
289                                                        }
290                                                }
291                                               
292                                                imap_close($this->mbox);
293                                                $this->mbox = false;
294                                        }
295                                }
296                               
297                                return $result;
298                        }
299                       
300                        case 'followupflagged':
301                        {                                       
302                                $result = array ( );
303
304                                $map = array(
305                                        //'id' => array(),
306                                        'folderName' => array(),
307                                        'messageNumber' => array(),
308                                        'messageId' => array()
309                                );
310                               
311                                self::parseFilter($criteria["filter"], &$map);
312       
313                                if (empty($map['folderName'])) {
314                                        $folders = $this->get_folders_list();
315                                        foreach ($folders as $folder)
316                                                if (isset($folder['folder_id']))
317                                                        $map['folderName'][] = $folder['folder_id'];
318                                }
319                               
320                                $messagesIds = $map['messageId'];
321
322                                foreach ($map['folderName'] as $folder) {
323                                        $messages = array();
324                                       
325                                        $this->mbox = $this->open_mbox($folder);
326
327                                        /**
328                                         * Se é uma busca por messageId
329                                         */
330                                        if (!empty($map['messageId'])) {
331                                                       
332                                                foreach ($messagesIds as $k => $v) {
333
334                                                        $r = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged" TEXT "Message-Id: '.$v.'"', SE_UID);
335
336                                                        if ($r) {
337
338                                                                $messages = array_merge($messages, $r);
339                                                                unset($messagesIds[$k]);
340                                                               
341                                                        }
342                                                }
343
344                                        /**
345                                         * Se é uma busca por messageNumber.
346                                         * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
347                                         */
348                                        } else {
349                                                $messages = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged"', SE_UID);
350                                        }
351
352                                        /**
353                                         * Se é uma busca por messageId, deve ser comparado com os messageNumbers
354                                         * passados no filtro, se houverem.
355                                         */
356                                        if (!empty($map['messageNumber'])) {
357                                                foreach ($messages as $k => $m)
358                                                        if (!in_array($m, $map['messageNumber']))
359                                                                unset($messages[$k]);
360                                        }
361
362                                        /**
363                                         * Adicionar demais atributos às mensagens para retorno
364                                         */
365
366                                        foreach ($messages as $k => $m) {
367                                                $headers = imap_fetch_overview($this->mbox, $m, FT_UID);
368
369                                                $result[] = array (
370                                                        'messageId' => $headers[0]->message_id,
371                                                        'messageNumber' => $m,
372                                                        'folderName' => $folder
373                                                );
374                                        }
375
376                                        imap_close($this->mbox);
377                                        $this->mbox = false;
378                                       
379                                        /**
380                                         * Se é uma busca por messageId e todos os messageIds foram econstrados:
381                                         * Stop searching in all folders
382                                         */
383                                        if (!empty($map['messageId']) && empty($messagesIds))
384                                                break;
385                                }
386                               
387                                if ($this->mbox) {
388                                        imap_close($this->mbox);
389                                        $this->mbox = false;
390                                }
391
392                                return $result;
393                               
394                        } //CASE 'followupflag'
395                }
396    }
397
398    public function read( $URI, $justthese = false )
399    {
400
401                switch( $URI['concept'] )
402                {
403                        case 'message':
404                        {
405                                return $this->to_utf8(
406                                        $this->get_info_msg( array('msg_number'=>$URI['id'],
407                                        'msg_folder'=>str_replace( '.', $this->imap_delimiter, $justthese['context']['folder'] )) )
408                                );
409                        }
410                        case 'labeled':
411                        {
412                                /**
413                                 * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#labelId
414                                 */
415                                list($messageId, $labelId) = explode('#', $URI['id']);
416                                $folderName = basename($messageId);
417                                $messageNumber = dirname($messageId);
418                               
419                                $result = array();
420
421                                if ($folderName && $messageNumber && $labelId) {
422                                        $this->mbox = $this->open_mbox($folderName);
423                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$labelId.'"', SE_UID);
424                                       
425                                        if (in_array($messageNumber, $messagesLabeleds)) {
426                                                $result = array (
427                                                        'id' => $URI['id'],
428                                                        'folderName' => $folderName,
429                                                        'messageNumber' => $messageNumber,
430                                                        'labelId' => $labelId
431                                                );
432                                        }
433                                        imap_close($this->mbox);
434                                        $this->mbox = false;
435                                }
436                               
437                                return $result;
438                        }
439                       
440                        case 'followupflagged':
441                        {
442                       
443                                /**
444                                 * identifica se o formato de ID é "folder/subfolder/subsubfolder/<messageNumber>" ou "<message-id>"
445                                 */
446                                $folderName = $messageNumber = false;
447                                if(!($messageHasId = preg_match('/<.*>/', $URI['id']))) {
448                                        $folderName = dirname($URI['id']);
449                                        $messageNumber = basename($URI['id']);
450                                }
451
452                                $result = array();
453                                if ($folderName && $messageNumber) {
454
455                                        $this->mbox = $this->open_mbox($folderName);
456                                        $r = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged"', SE_UID);
457
458                                        if (in_array($messageNumber, $r)) {
459                                                $headers = imap_fetch_overview($this->mbox, $messageNumber, FT_UID);
460                                                       
461                                                $result = array (
462                                                        'messageId' => $headers[0]->message_id,
463                                                        'messageNumber' => $messageNumber,
464                                                        'folderName' => $folderName
465                                                );
466                                        }
467                                       
468                                        imap_close($this->mbox);
469                                        $this->mbox = false;
470                               
471                                } else {
472                                        /**
473                                         * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
474                                         * senão busca em todas.
475                                         */
476                                       
477                                        $folders = array ();
478                                        if ($folderName) {
479                                                $folders = array ($folderName);
480                                        } else {
481                                                $folder_list = $this->get_folders_list();
482                                                foreach ($folder_list as $folder)
483                                                        if (isset($folder['folder_id']))
484                                                                $folders[] = $folder['folder_id'];
485                                        }
486                                       
487                                        foreach ($folders as $folder) {
488                                               
489                                                $this->mbox = $this->open_mbox($folder);
490                                               
491                                                if ($messages = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged" TEXT "Message-Id: '.$URI['id'].'"', SE_UID)) {
492                               
493                                                        $result = array (
494                                                                'messageId' => $URI['id'],
495                                                                'messageNumber' => $messages[0],
496                                                                'folderName' => $folder
497                                                        );
498                                                       
499                                                        /**
500                                                         * Stop searching in all folders
501                                                         */
502                                                        break;
503                                                }
504                                               
505                                                imap_close($this->mbox);
506                                                $this->mbox = false;
507                                        }
508                                }
509                               
510                                if ($this->mbox) {
511                                        imap_close($this->mbox);
512                                        $this->mbox = false;
513                                }
514                               
515                                return $result;
516                        }
517                }
518    }
519
520    public function create($URI, &$data)
521    {               
522                switch( $URI['concept'] )
523                {
524                        case 'labeled':
525                        {
526                                if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['labelId'])) {
527                                        $this->mbox = $this->open_mbox($data['folderName']);
528                                        imap_setflag_full($this->mbox, $data['messageNumber'], '$Label' . $data['labelId'], ST_UID);
529
530                                        imap_close($this->mbox);
531                                        $this->mbox = false;
532
533                                        return array ('id' => $data['folderName'].'/'.$data['messageNumber'].'#'.$data['labelId']);
534                                }
535                                return array ();
536                        }
537                        case 'followupflagged':
538                        {
539                                //deve ser gravado primeiro no imap, obtido o message-id e, depois gravado no banco
540                               
541                                if (isset($data['folderName']) && isset($data['messageNumber'])) {
542                                       
543                                        $this->mbox = $this->open_mbox($data['folderName']);
544                                        $s = imap_setflag_full($this->mbox, $data['messageNumber'], '$Followupflagged', ST_UID);
545                                       
546                                        $headers = imap_fetch_overview($this->mbox, $data['messageNumber'], FT_UID);
547                                       
548                                        $data['messageId'] = $headers[0]->message_id;
549                                                       
550                                        imap_close($this->mbox);
551                                        $this->mbox = false;
552
553                                        return ($s) ? $data : array();
554
555                                } else if (isset($data['messageId'])) {
556                                        /**
557                                         * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
558                                         * senão busca em todas.
559                                         */
560                                        $folders = array ();
561                                        if (isset($data['folderName'])) {
562                                                $folders = array ($data['folderName']);
563                                        } else {
564                                                $folder_list = $this->get_folders_list();
565                                                foreach ($folder_list as $folder)
566                                                        if (isset($folder['folder_id']))
567                                                                $folders[] = $folder['folder_id'];
568                                        }
569                                       
570                                        foreach ($folders as $folder) {
571                                               
572                                                $this->mbox = $this->open_mbox($folder);
573                                                if ($messages = imap_search($this->mbox, 'ALL TEXT "Message-Id: '.$data['messageId'].'"', SE_UID)) {
574                                                       
575                                                        $s = imap_setflag_full($this->mbox, $messages[0], '$Followupflagged', ST_UID);
576                                                       
577                                                        imap_close($this->mbox);
578                                                        $this->mbox = false;
579                                                       
580                                                        /**
581                                                         * Stop searching in all folders
582                                                         */
583                                                        return $data;
584                                                }
585                                               
586                                                imap_close($this->mbox);
587                                                $this->mbox = false;
588                                        }
589                                }
590                                return array ();
591                        }
592                       
593                        case 'message':
594                        {
595                                require_once ROOTPATH.'/library/uuid/class.uuid.php';
596                               
597                                $GLOBALS['phpgw_info']['flags'] = array( 'noheader' => true, 'nonavbar' => true,'currentapp' => 'expressoMail1_2','enable_nextmatchs_class' => True );
598                                $return = array();
599
600                                require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
601                                $mailService = ServiceLocator::getService('mail');
602
603                                $msg_uid = $data['msg_id'];
604                                $body = $data['body'];
605                                $body = str_replace("%nbsp;","&nbsp;",$body);
606                                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );                                       
607
608                                $folder = mb_convert_encoding($data['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
609                                $folder = @preg_replace('/INBOX[\/.]/i', "INBOX".$this->imap_delimiter, $folder);
610
611                                /**
612                                * Gera e preenche o field Message-Id do header
613                                */
614                                $mailService->addHeaderField('Message-Id', UUID::generate( UUID::UUID_RANDOM, UUID::FMT_STRING ) . '@Draft');
615
616                                $mailService->addTo(mb_convert_encoding(($data['input_to']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
617                                $mailService->addCc( mb_convert_encoding(($data['input_cc']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
618                                $mailService->addBcc(mb_convert_encoding(($data['input_cco']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
619                                $mailService->setSubject(mb_convert_encoding(($data['input_subject']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
620                               
621                                if(isset($data['input_important_message']))
622                                        $mailService->addHeaderField('Importance','High');
623
624                                if(isset($data['input_return_receipt']))
625                                        $mailService->addHeaderField('Disposition-Notification-To', Config::me('mail'));
626
627                                $isHTML = ( isset($data['type']) && $data['type'] == 'html' )?  true : false;
628
629                                if (!$body) $body = ' ';
630
631
632                                $mbox_stream = $this->open_mbox($folder);
633
634                                $attachment = json_decode($data['attachments'],TRUE);
635
636
637                                foreach ($attachment as &$value)
638                                {
639                                        if((int)$value > 0) //BD attachment
640                                        {
641                                                $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment'));
642
643                                                if($att['disposition'] == 'embedded')
644                                                {
645                                                        $body = str_replace('"../prototype/getArchive.php?mailAttachment='.$att['id'].'"', $att['name'], $body);
646                                                        $mailService->addStringImage(base64_decode($att['source']), $att['type'], $att['name']);
647                                                }
648                                                else
649                                                        $mailService->addStringAttachment(base64_decode($att['source']), $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
650
651                                                unset($att);
652                                        }
653                                        else
654                                        {
655                                                $value = json_decode($value, true);
656
657                                                switch ($value['type']) {
658                                                        case 'imapPart':
659                                                                $att = $this->getForwardingAttachment($value['folder'],$value['uid'], $value['part']);
660                                                                if(strstr($body,'<img src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'" />') !== false)//Embeded IMG
661                                                                {   
662                                                                        $body = str_ireplace('<img src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'" />' , '<img src="'.$att['name'].'" />', $body);
663                                                                        $mailService->addStringImage($att['source'], $att['type'], $att['name']);
664                                                                }
665                                                                else
666                                                                        $mailService->addStringAttachment($att['source'], $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
667                                                                unset($att);
668                                                                break;
669                                                        case 'imapMSG':
670                                                                $sub =  $value['name'] ? $value['name'].'.eml' :'no title.eml';
671                                                                $mbox_stream = $this->open_mbox($value['folder']);
672                                                                $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']);
673                                                                $mailService->addStringAttachment($rawmsg, $sub, 'message/rfc822', '7bit', 'attachment' );
674                                                                unset($rawmsg);
675                                                                break;
676
677                                                        default:
678                                                        break;
679                                                }
680                                        }
681
682                                }
683
684                                if($isHTML) $mailService->setBodyHtml($body); else $mailService->setBodyText($body);
685
686                                if(imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft"))
687                                {
688                                        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
689                                        $return['id'] = $status->uidnext - 1;
690
691                                        if($data['uidsSave'] )
692                                                $this->delete_msgs(array('folder'=> $folder , 'msgs_number' => $data['uidsSave']));
693                                }
694
695                                if($mbox_stream) imap_close($mbox_stream);
696
697                                return $return;
698                        }
699                }
700        }
701
702    public function delete( $URI, $justthese = false, $criteria = false )
703    {
704                switch( $URI['concept'] )
705                {
706                        case 'labeled':
707                        {
708                                list($messageId, $labelId) = explode('#', $URI['id']);
709                                $folderName = dirname($messageId);
710                                $messageNumber = basename($messageId);
711
712                                if ($folderName && $messageNumber && $labelId) {
713                                        $this->mbox = $this->open_mbox($folderName);
714                                        imap_clearflag_full($this->mbox, $messageNumber, '$Label' . $labelId, ST_UID);
715
716                                        imap_close($this->mbox);
717                                        $this->mbox = false;
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                                        imap_close($this->mbox);
785                                        $this->mbox = false;
786                                       
787                                        /**
788                                         * Se é uma busca por messageId e todos os messageIds foram econstrados:
789                                         * Stop searching in all folders
790                                         */
791                                        if (!empty($map['messageId']) && empty($messagesIds))
792                                                break;
793                                }
794                               
795                                return $s;
796                        }
797                }
798
799                //TODO - return
800        }
801
802    public function deleteAll( $URI, $justthese = false, $criteria = false )
803    {
804                /**
805                 * TODO - implementar a deleção de todos os followupflaggeds conforme filtro
806                 */
807        }
808
809    public function update( $URI, $data, $criteria = false )
810    {
811                /**
812                 * Os únicos atributos da sinalização presentes no IMAP são folderName, messageNumber e messageId,
813                 * porém a operação de update desses atributos não faz sentido para o usuário da DataLayer,
814                 * pois na prática elas são executadas através das operações de CREATE e DELETE.
815                 * Assim, para os conceitos "labeled" e "followupflagged", só faz sentido o update de
816                 * atributos gravados no banco de dados e nunca no IMAP.
817                 */
818        }
819
820//     public function retrieve( $concept, $id, $parents, $justthese = false, $criteria = false )
821//     {
822//                      return $this->read( array( 'id' => $id,
823//                          'concept' => $concept,
824//                          'context' => $parents ), $justthese );
825//     }
826
827    public function replace( $URI, $data, $criteria = false )
828    {}
829
830    public function close()
831    {}
832
833    public function setup()
834    {}
835
836    public function commit( $uri )
837    { return( true ); }
838
839    public function rollback( $uri )
840    {}
841
842    public function begin( $uri )
843    {}
844
845
846    public function teardown()
847    {}
848
849    function to_utf8($in)
850    {
851                if (is_array($in)) {
852                        foreach ($in as $key => $value) {
853                                $out[$this->to_utf8($key)] = $this->to_utf8($value);
854                        }
855                } elseif(is_string($in)) {
856                                return mb_convert_encoding( $in , 'UTF-8' , 'UTF-8 , ISO-8859-1' );
857                } else {
858                        return $in;
859                }
860                return $out;
861    }
862       
863           
864    private static function parseFilter($filter ,&$map){
865               
866                if( !is_array( $filter ) || count($filter) <= 0) return null;
867                                       
868                $op = array_shift( $filter );
869                switch(strtolower($op))
870                {
871                        case 'and': {
872                                foreach ($filter as $term)
873                                        self::parseFilter($term ,&$map);
874                                return;
875                        }
876                        case 'in': {
877                                if(is_array($map[$filter[0]]) && is_array($filter[1]))
878                                        $map[$filter[0]] = array_unique(array_merge($map[$filter[0]], $filter[1]));
879                                return;
880                        }
881                        case '=': {
882                                $map[$filter[0]][] = $filter[1];
883                        }
884                }
885        }
886
887}
Note: See TracBrowser for help on using the repository browser.