source: sandbox/2.4.1-2/prototype/services/ImapServiceAdapter.php @ 6259

Revision 6259, 25.6 KB checked in by cristiano, 12 years ago (diff)

Ticket #2778 - Permitir inserir imagens no corpo de e-mail via area de transferencia

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