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